From 61affc6311906aee71b16ee8632c1e7468cd1990 Mon Sep 17 00:00:00 2001 From: "Benjamin, Max (mb388a)" Date: Mon, 5 Nov 2018 11:00:36 -0500 Subject: Catchup commits for Dublin added property for retry timer multiplier for testing Infra APIH table, fixed test assertNull condition. Infra APIH table, added tests for request-url = null. Infra APIH should write request_url to infra_active_requests. Return SelfLink URL on ServiceInstantiation SyncResponse. Added JUNITS. Added helper method to get AAI ResourceUri to faciliate unit test. Fixed code to correctly extract related generic vnf or vce id. updated unit test coverage for update network Handle REST NotFoundException for serviceInstance nodes query. Process should continue for new order request and throw exception only for SUPP request. Added disconnect functionality to the gw vnf test tool. Added conversion of vnf management option to dhv change speed sync subnet status with network update updated macroData vol assigned delete continue script Correct the name of DeleteVfModuleBB subprocess. fix the custom resolver to not convert int in string to int Write the returned value from Homing to gBBInput Use explicit conversion to JSON to read cloudConfiguration settings. added property for retry timer multiplier for testing avoid storing AAI yang models in execution added handlingCode to rollback test in workflowactionbb passed in alacarte flag to execute layer for rainy day added test cases for RollbackToAssigned rainy day hand added rollback to assign in catalog db rainy day hand Updated vnf adapter delete stubs to be a post for test. Added a javadoc to basic auth override method Added a check to not add blank headers to the headerMap in httpClient. Added check for if entity exist before calling readEntity. Fixed failing junits and updated way the body is obtained Added missing import statement for http client. Fixed mistakes and made updates caught during review. Removed post and httpPost methods from RESTClient and refactored references Refactored multiple http post references to use httpClient instead. Removed close connection method and randomized port in unit test Added http client unit test, coverage is currently at 90 percent Resolve conflict in sdnc adapter reste v1 method Began removing http delete and delete methods from RESTClient and aaiUtil. Removed http put method and executeput method, refactored references. fixed broken tests in the branch in jenkins build Fix Springboot 2.0 start up issues, and other issues added in implementation to generate self link if there isnt one removed dbcp2 from poms that still had them added rollbackstatusmessage to stub in testprocess added rollback_status_message to the schema sql file Added variable for rollbackStatusMessage Added rollbackStatusMessage to get response added rollback status message to archived infra request set rollback status message to successful on boolean added logic to split rollback and regular error message added rollback status message to infra active requests pushing the cloud config changes as well Added media type and fixed cast plural issue. Made various updated and fixes to code that was changed. Removed all no longer used RESTClient imports from classes Removed and refactored references for aaiUtil methods and all remaining RESTClient methods, removed RESTClient project and updated poms. Return canonical stack id on multicloud create Fix OOF Config Ingestion Fix variable to retrieve sdnc endpoint Prepare resources for service uuid req Fix swapped parameters for multicloud DELETE Update msb-java-sdk to resolve license issues cloud owner support for SDNC interface correlationId is now read from userParams Fix up request body of multicloud adapter body removed LinkedHashMap from java classes Cut over logging project to release not snapshot Update unit tests, revert test code, fix comments Fix remaining number of Unit Tests, on avpn flow Fix JUNITS add callback url, fix BPMN issues Update SDNC interaction to support a-sync updated bpm assert import and corrected tests updated test case to be mockito 2 compliant additional changes to import statements and tests Change the place where the data for multistage gets set Update treatment of PENDING_ACTIVATION VF_MODULE CREATE entries to SILENT_SUCCESS to support first stage of multistage. Implement second stage of multistage design VF Module Creation removed LinkedHashMap from java classes Removed SNAPSHOT from dependency Cut over logging project to release not snapshot Fixed failing BBInputSetup tests Update unit tests, revert test code, fix comments Updated apih tests to use networkInstanceGroup Updated ModelType enum and fixed compilation issues Fix remaining number of Unit Tests, on avpn flow Fix JUNITS add callback url, fix BPMN issues Implementation of the first stage of multistage design for VF Module creation. Update SDNC interaction to support a-sync no longer leave modified files after test runs Remove generated CSAR, that occurs during JUNIT Update Camunda Pods to use Flyway Migration in 1902 Updated hashcode method and removed comment. Added aggregate routes to the sdnw request and updated pom sdnw dependency. Began to set aggreagate route information for vrf configuration. modified remaining files with att-aic references Correct rollbackData setting and protect against potential null objects. correct AAIObjectPlurals enum value name Update POJO to use type URL for selfLink. Optional - construct SelfLink Url format. Construct SelfLink Url format from full Url. added missing properties to application-test.yaml fixed compliation error after merge of unit test restored files which should not have been deleted Fix SO vulnerabilities with cxf Fixing bpmn infra endpoint in so-monitoring yaml removed att-aic from codebase default cloud owner now configurable Set homingService in WorkflowAction Fix Java Ex in Homing Version should be 1.3.1 to release new dockers Pnf Spring Environment correction test property now has dynamic wiremock port removed test specific wiremock rule that was causing problems re-enabled and corrected integration tests for so-bpmn-tasks Test to get sniro homing v2 test working by splitting test suites for each spring application Reverted changes to old migration scripts.. Fixed spring context issue with test HomingV2. Removed unused import to fix compilation errors Fixed onap changes to homing, migrated homingV2 to homingBB, fixed broken junits again. - Updated isUseHttpsWithDmaapTest to check assertTrue rather than assertFalse. - Upgraded code to make the isUseHttpsWithDmaap configurable. It will default to true if no value is found in the config file. moved workflowaction test class to the test section added status message update for retry and rollback beefed up error message debug logging and req db msg added debug lines to workflowactionbbtasks reqdbcall Issue-ID: SO-1187 Change-Id: Iec1aff4ed30a43c0e0b2cdb06c28d8db8a99a830 Signed-off-by: Benjamin, Max (mb388a) --- bpmn/MSOCommonBPMN/pom.xml | 11 +- .../org/onap/so/bpmn/common/scripts/AaiUtil.groovy | 397 +----------- .../so/bpmn/common/scripts/CatalogDbUtils.groovy | 52 +- .../so/bpmn/common/scripts/ExternalAPIUtil.groovy | 85 +-- .../common/scripts/GenerateVfModuleName.groovy | 67 ++- .../so/bpmn/common/scripts/NetworkUtils.groovy | 169 +++--- .../onap/so/bpmn/common/scripts/OofHoming.groovy | 34 +- .../onap/so/bpmn/common/scripts/OofUtils.groovy | 25 +- .../common/scripts/PrepareUpdateAAIVfModule.groovy | 82 +-- .../bpmn/common/scripts/SDNCAdapterRestV1.groovy | 36 +- .../bpmn/common/scripts/SDNCAdapterRestV2.groovy | 23 +- .../so/bpmn/common/scripts/SniroHomingV1.groovy | 28 +- .../so/bpmn/common/scripts/VnfAdapterRestV1.groovy | 40 +- .../workflow/context/WorkflowContextHolder.java | 5 +- .../bbobjects/AggregateRoute.java | 107 ++++ .../servicedecomposition/bbobjects/L3Network.java | 13 +- .../tasks/ExecuteBuildingBlockRainyDay.java | 16 +- .../subprocess/BuildingBlock/HomingV2.bpmn | 194 ------ .../onap/so/bpmn/common/scripts/AaiUtilTest.groovy | 168 ------ .../AbstractServiceTaskProcessorTest.groovy | 39 +- .../tasks/ExecuteBuildlingBlockRainyDayTest.java | 61 +- .../SniroHoming/SniroManagerRequest1Vpn.json | 6 - .../SniroHoming/SniroManagerRequest3AR.json | 6 - .../SniroHoming/SniroManagerRequest3Vpn.json | 6 - .../src/test/resources/application-test.yaml | 2 + bpmn/MSORESTClient/pom.xml | 37 -- .../main/java/org/onap/so/rest/APIResponse.java | 145 ----- .../java/org/onap/so/rest/HostNameVerifier.java | 49 -- .../src/main/java/org/onap/so/rest/HttpHeader.java | 65 -- .../src/main/java/org/onap/so/rest/RESTClient.java | 614 ------------------- .../src/main/java/org/onap/so/rest/RESTConfig.java | 131 ---- .../main/java/org/onap/so/rest/RESTException.java | 85 --- .../java/org/onap/so/rest/APIResponseTest.java | 57 -- .../test/java/org/onap/so/rest/HttpHeaderTest.java | 40 -- .../test/java/org/onap/so/rest/RESTClientTest.java | 184 ------ .../test/java/org/onap/so/rest/RESTConfigTest.java | 42 -- .../java/org/onap/so/rest/RESTExceptionTest.java | 40 -- bpmn/mso-infrastructure-bpmn/pom.xml | 2 +- .../delegate/CreateAndActivatePnfResourceTest.java | 2 +- bpmn/pom.xml | 2 +- bpmn/so-bpmn-building-blocks/pom.xml | 2 +- .../subprocess/BuildingBlock/AssignVnfBB.bpmn | 3 +- .../subprocess/BuildingBlock/HomingBB.bpmn | 323 ++++++---- .../subprocess/BuildingBlock/SDNCHandler.bpmn | 259 ++++++++ .../subprocess/BuildingBlock/WorkflowActionBB.bpmn | 5 +- .../test/java/org/onap/so/bpmn/BaseBPMNTest.java | 50 +- .../so/bpmn/buildingblock/SniroHomingV2BBTest.java | 74 --- .../bpmn/subprocess/HomingBBTest.java | 59 ++ .../bpmn/subprocess/SDNCHandlerTest.java | 77 +++ .../test/resources/SDNCClientPut200Response.json | 15 + .../SDNCClientPut200ResponseNotFinal.json | 15 + .../src/test/resources/SDNCFlowRequest.json | 11 + .../src/test/resources/SDNC_Client_Request.json | 28 + .../src/test/resources/application-test.yaml | 2 +- bpmn/so-bpmn-infrastructure-common/pom.xml | 33 +- .../scripts/Create3rdONAPE2EServiceInstance.groovy | 179 +++--- .../scripts/CreateDeviceResource.groovy | 56 +- .../scripts/CreateSDNCNetworkResource.groovy | 36 +- .../scripts/CreateVFCNSResource.groovy | 63 +- .../scripts/Delete3rdONAPE2EServiceInstance.groovy | 249 ++++---- .../scripts/DeleteDeviceResource.groovy | 37 +- .../scripts/DeleteVfModuleVolumeInfraV1.groovy | 1 - .../scripts/DoCompareModelVersions.groovy | 69 +-- .../scripts/DoCreateE2EServiceInstance.groovy | 6 +- .../DoCreateE2EServiceInstanceRollback.groovy | 3 - .../scripts/DoCreateNetworkInstance.groovy | 662 ++++++++------------- .../scripts/DoCreateNetworkInstanceRollback.groovy | 117 ++-- .../scripts/DoCreateServiceInstance.groovy | 10 +- .../scripts/DoCreateServiceInstanceRollback.groovy | 21 +- .../DoCreateVFCNetworkServiceInstance.groovy | 66 +- .../infrastructure/scripts/DoCreateVfModule.groovy | 59 +- .../scripts/DoCreateVfModuleRollback.groovy | 92 +-- .../DoCustomDeleteE2EServiceInstanceV2.groovy | 2 +- .../scripts/DoDeleteE2EServiceInstance.groovy | 64 +- .../scripts/DoDeleteNetworkInstance.groovy | 27 +- .../scripts/DoDeleteNetworkInstanceRollback.groovy | 76 ++- .../DoDeleteVFCNetworkServiceInstance.groovy | 102 ++-- .../infrastructure/scripts/DoDeleteVfModule.groovy | 21 +- .../DoScaleVFCNetworkServiceInstance.groovy | 42 +- .../scripts/DoUpdateNetworkInstance.groovy | 574 +++++++----------- .../scripts/DoUpdateNetworkInstanceRollback.groovy | 10 +- .../infrastructure/scripts/DoUpdateVfModule.groovy | 2 +- .../scripts/DoUpdateVnfAndModules.groovy | 181 +++--- .../bpmn/infrastructure/scripts/RollbackVnf.groovy | 44 +- .../vcpe/scripts/DeleteVcpeResCustService.groovy | 2 +- .../DoCreateAllottedResourceTXCRollback.groovy | 34 +- .../delegate/CheckAaiForCorrelationIdDelegate.java | 1 - .../pnf/delegate/PnfCheckInputsTest.java | 2 +- bpmn/so-bpmn-infrastructure-flows/pom.xml | 11 +- bpmn/so-bpmn-tasks/pom.xml | 32 + .../onap/so/bpmn/buildingblock/SniroHomingV2.java | 3 +- .../infrastructure/sdnc/tasks/SDNCQueryTasks.java | 20 +- .../sdnc/tasks/SDNCRequestTasks.java | 99 +++ .../workflow/tasks/WorkflowActionBBTasks.java | 118 ++-- .../orchestration/SDNCConfigurationResources.java | 159 +++-- .../java/org/onap/so/client/sdnc/SDNCClient.java | 17 +- .../org/onap/so/client/sdnc/SdnCommonTasks.java | 7 +- .../org/onap/so/client/sdnc/beans/SDNCRequest.java | 94 +++ .../mapper/GCTopologyOperationRequestMapper.java | 14 +- .../sdnc/mapper/GeneralTopologyObjectMapper.java | 10 + .../java/org/onap/so/client/sniro/SniroClient.java | 8 +- .../org/onap/so/client/sniro/SniroValidator.java | 4 +- .../java/org/onap/so/AllIntegrationTestSuites.java | 12 + .../test/java/org/onap/so/BaseIntegrationTest.java | 32 +- .../java/org/onap/so/IntegrationTestSuite.java | 12 + .../src/test/java/org/onap/so/UnitTestSuite.java | 13 + .../test/java/org/onap/so/bpmn/BaseTaskTest.java | 57 +- .../onap/so/bpmn/common/data/TestDataSetup.java | 14 +- .../aai/tasks/AAIUpdateTasksTest.java | 1 + .../infrastructure/appc/tasks/AppcRunTasksIT.java | 101 ++++ .../appc/tasks/AppcRunTasksITTest.java | 101 ---- .../flowspecific/tasks/SniroHomingV2IT.java | 496 +++++++++++++++ .../flowspecific/tasks/SniroHomingV2Test.java | 497 ---------------- .../sdnc/tasks/SDNCQueryTasksTest.java | 5 + .../sdnc/tasks/SDNCRequestTasksTest.java | 170 ++++++ .../workflow/tasks/WorkflowActionBBTasksTest.java | 92 +-- .../WorkflowActionBBTasksUpdateReqDbTest.java | 74 +++ .../adapter/network/NetworkAdapterClientIT.java | 7 +- .../so/client/adapter/vnf/VnfAdapterClientIT.java | 6 +- .../org/onap/so/client/oof/OofClientTestIT.java | 15 +- .../SDNCConfigurationResourcesTest.java | 37 +- .../java/org/onap/so/client/sdnc/SDNCClientIT.java | 82 +++ .../org/onap/so/client/sdnc/SDNCClientTest.java | 89 --- .../GCTopologyOperationRequestMapperTest.java | 13 +- .../onap/so/client/sniro/SniroClientTestIT.java | 6 +- .../SniroHoming/SniroManagerRequest1Vpn.json | 2 +- .../SniroHoming/SniroManagerRequest3AR.json | 6 + .../SniroHoming/SniroManagerRequest3Vpn.json | 2 +- .../__files/SDNCClientPut200ResponseNotFinal.json | 15 + .../test/resources/__files/SDNC_ASYNC_Request.json | 15 + .../resources/__files/SDNC_Client_Request.json | 28 + .../src/test/resources/application-test.yaml | 5 +- 132 files changed, 4099 insertions(+), 5535 deletions(-) create mode 100644 bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java delete mode 100644 bpmn/MSOCommonBPMN/src/main/resources/subprocess/BuildingBlock/HomingV2.bpmn delete mode 100644 bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AaiUtilTest.groovy delete mode 100644 bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1Vpn.json delete mode 100644 bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3AR.json delete mode 100644 bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3Vpn.json delete mode 100644 bpmn/MSORESTClient/pom.xml delete mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/APIResponse.java delete mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HostNameVerifier.java delete mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HttpHeader.java delete mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTClient.java delete mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTConfig.java delete mode 100644 bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTException.java delete mode 100644 bpmn/MSORESTClient/src/test/java/org/onap/so/rest/APIResponseTest.java delete mode 100644 bpmn/MSORESTClient/src/test/java/org/onap/so/rest/HttpHeaderTest.java delete mode 100644 bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTClientTest.java delete mode 100644 bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTConfigTest.java delete mode 100644 bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTExceptionTest.java create mode 100644 bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/SDNCHandler.bpmn delete mode 100644 bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/buildingblock/SniroHomingV2BBTest.java create mode 100644 bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/HomingBBTest.java create mode 100644 bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/SDNCHandlerTest.java create mode 100644 bpmn/so-bpmn-building-blocks/src/test/resources/SDNCClientPut200Response.json create mode 100644 bpmn/so-bpmn-building-blocks/src/test/resources/SDNCClientPut200ResponseNotFinal.json create mode 100644 bpmn/so-bpmn-building-blocks/src/test/resources/SDNCFlowRequest.json create mode 100644 bpmn/so-bpmn-building-blocks/src/test/resources/SDNC_Client_Request.json create mode 100644 bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java create mode 100644 bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java create mode 100644 bpmn/so-bpmn-tasks/src/test/java/org/onap/so/AllIntegrationTestSuites.java create mode 100644 bpmn/so-bpmn-tasks/src/test/java/org/onap/so/IntegrationTestSuite.java create mode 100644 bpmn/so-bpmn-tasks/src/test/java/org/onap/so/UnitTestSuite.java create mode 100644 bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java delete mode 100644 bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksITTest.java create mode 100644 bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java delete mode 100644 bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2Test.java create mode 100644 bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java create mode 100644 bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksUpdateReqDbTest.java create mode 100644 bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientIT.java delete mode 100644 bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientTest.java create mode 100644 bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3AR.json create mode 100644 bpmn/so-bpmn-tasks/src/test/resources/__files/SDNCClientPut200ResponseNotFinal.json create mode 100644 bpmn/so-bpmn-tasks/src/test/resources/__files/SDNC_ASYNC_Request.json create mode 100644 bpmn/so-bpmn-tasks/src/test/resources/__files/SDNC_Client_Request.json (limited to 'bpmn') diff --git a/bpmn/MSOCommonBPMN/pom.xml b/bpmn/MSOCommonBPMN/pom.xml index a507b1ea0d..c85bcd7522 100644 --- a/bpmn/MSOCommonBPMN/pom.xml +++ b/bpmn/MSOCommonBPMN/pom.xml @@ -159,7 +159,7 @@ - org.eclipse.m2e @@ -232,7 +232,7 @@ org.camunda.connect - camunda-connect-connectors-all + camunda-connect-connectors-all commons-beanutils @@ -277,11 +277,6 @@ common ${project.version} - - org.onap.so - MSORESTClient - ${project.version} - org.onap.so.adapters mso-adapters-rest-interface @@ -358,7 +353,7 @@ org.glassfish.jersey.inject - jersey-hk2 + jersey-hk2 2.26 diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy index 8a262251b1..8cc232c2a4 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AaiUtil.groovy @@ -22,20 +22,21 @@ package org.onap.so.bpmn.common.scripts import java.util.regex.Matcher import java.util.regex.Pattern +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response import javax.ws.rs.core.UriBuilder import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.aai.domain.yang.GenericVnf import org.onap.so.bpmn.core.UrnPropertiesReader; +import org.onap.so.client.HttpClient import org.onap.so.client.aai.AAIVersion import org.onap.so.client.aai.entities.uri.AAIUri import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger import org.onap.so.openpojo.rules.HasToStringRule -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.utils.TargetEntity @Deprecated class AaiUtil { @@ -54,37 +55,6 @@ class AaiUtil { this.taskProcessor = taskProcessor } - public String getBusinessSPPartnerUri(DelegateExecution execution) { - def uri = getUri(execution, 'sp-partner') - msoLogger.debug('AaiUtil.getBusinessSPPartnerUri() - AAI URI: ' + uri) - return uri - } - - public String getVersion(DelegateExecution execution, resourceName, processKey) { - def versionWithResourceKey = "mso.workflow.default.aai.${resourceName}.version" - def versionWithProcessKey = "mso.workflow.custom.${processKey}.aai.version" - - def version = UrnPropertiesReader.getVariable(versionWithProcessKey, execution) - if (version) { - msoLogger.debug("AaiUtil.getVersion() - using flow specific ${versionWithProcessKey}=${version}") - return version - } - - version = UrnPropertiesReader.getVariable(versionWithResourceKey, execution) - if (version) { - msoLogger.debug("AaiUtil.getVersion() - using resource specific ${versionWithResourceKey}=${version}") - return version - } - - version = UrnPropertiesReader.getVariable(DEFAULT_VERSION_KEY, execution) - if (version) { - msoLogger.debug("AaiUtil.getVersion() - using default version ${DEFAULT_VERSION_KEY}=${version}") - return version - } - - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, "Internal Error: One of the following should be defined in MSO URN properties file: ${versionWithResourceKey}, ${versionWithProcessKey}, ${DEFAULT_VERSION_KEY}") - } - public String createAaiUri(AAIUri uri) { return createAaiUri(AAIVersion.valueOf('V' + UrnPropertiesReader.getVariable(DEFAULT_VERSION_KEY)), uri) } @@ -94,14 +64,6 @@ class AaiUtil { return UriBuilder.fromUri(result + uri.build().toString()).build().toString() } - public String setNamespace(DelegateExecution execution) { - def key = AAI_NAMESPACE_STRING_KEY - aaiNamespace = UrnPropertiesReader.getVariable(key, execution) - if (aaiNamespace == null ) { - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file') - } - } - public String getNamespace() { return getNamespace(AAIVersion.valueOf('V' + UrnPropertiesReader.getVariable(DEFAULT_VERSION_KEY))) } @@ -114,330 +76,6 @@ class AaiUtil { return namespace + version } - /** - * This method can be used for getting the building namespace out of uri. - * NOTE: A getUri() method needs to be invoked first. - * Alternative method is the getNamespaceFromUri(DelegateExecution execution, String uri) - * return namespace (plus version from uri) - * - * @param url - * - * @return namespace - */ - public String getNamespaceFromUri(String uri) { - String namespace = UrnPropertiesReader.getVariable(AAI_NAMESPACE_STRING_KEY) - if (namespace == null) { - throw new Exception('Internal Error: AAI Namespace has not been set yet. A getUri() method needs to be invoked first.') - } - if(uri!=null){ - String version = getVersionFromUri(uri) - return namespace + "v"+version - }else{ - return namespace - } - } - - /** - * This method can be used for building namespace with aai version out of uri. - * NOTE: 2 arguments: DelegateExecution execution & String uri - * @param execution - * @param url - * - * @return namespace - */ - public String getNamespaceFromUri(DelegateExecution execution, String uri) { - String namespace = UrnPropertiesReader.getVariable(AAI_NAMESPACE_STRING_KEY, execution) - if (namespace == null ) { - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + AAI_NAMESPACE_STRING_KEY + ' not defined in the MSO URN properties file') - } - if(uri!=null){ - String version = getVersionFromUri(uri) - return namespace + "v"+version - }else{ - return namespace - } - } - - /** - * This is used to extract the version from uri. - * - * @param uri - * - * @return version - */ - private String getVersionFromUri(String uri) { - - Matcher versionRegEx = Pattern.compile("/v(\\d+)").matcher(uri) - if (versionRegEx.find()) { - return versionRegEx.group(1); - } - - return ""; - } - - - /** - * This reusable method can be used for making AAI Get Calls. The url should - * be passed as a parameter along with the execution. The method will - * return an APIResponse. - * - * @param execution - * @param url - * - * @return APIResponse - * - */ - public APIResponse executeAAIGetCall(DelegateExecution execution, String url){ - msoLogger.trace("STARTED Execute AAI Get Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); - - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpGet() - - msoLogger.trace("COMPLETED Execute AAI Get Process ") - }catch(Exception e){ - msoLogger.debug("Exception occured while executing AAI Get Call. Exception is: \n" + e) - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - - /** - * This reusable method can be used for making AAI httpPut Calls. The url should - * be passed as a parameter along with the execution and payload. The method will - * return an APIResponse. - * - * @param execution - * @param url - * @param payload - * - * @return APIResponse - * - */ - public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){ - msoLogger.trace("Started Execute AAI Put Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml"); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPut(payload) - - msoLogger.trace("Completed Execute AAI Put Process ") - }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - /** - * This reusable method can be used for making AAI httpPatch Calls. The url should - * be passed as a parameter along with the execution and payload. The method will - * return an APIResponse. - * - * @param execution - * @param url - * @param payload - * - * @return APIResponse - * - */ - public APIResponse executeAAIPatchCall(DelegateExecution execution, String url, String payload){ - msoLogger.trace("Started Execute AAI Patch Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/merge-patch+json").addHeader("Accept","application/json"); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPatch(payload) - - msoLogger.trace("Completed Execute AAI Patch Process ") - }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Patch Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - - /** - * This reusable method can be used for making AAI Delete Calls. The url should - * be passed as a parameter along with the execution. The method will - * return an APIResponse. - * - * @param execution - * @param url - * - * @return APIResponse - * - */ - public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url){ - msoLogger.trace("Started Execute AAI Delete Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.delete() - - msoLogger.trace("Completed Execute AAI Delete Process ") - }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Delete Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - /** - * This reusable method can be used for making AAI Delete Calls. The url should - * be passed as a parameter along with the execution. The method will - * return an APIResponse. - * - * @param execution - * @param url - * @param payload - * - * @return APIResponse - * - */ - public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url, String payload, String authHeader){ - msoLogger.trace("Started Execute AAI Delete Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml").addAuthorizationHeader(authHeader); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpDelete(payload) - - msoLogger.trace("Completed Execute AAI Delete Process ") - }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Delete Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - /** - * This reusable method can be used for making AAI Post Calls. The url - * and payload should be passed as a parameters along with the execution. - * The method will return an APIResponse. - * - * @param execution - * @param url - * @param payload - * - * @return APIResponse - * - */ - public APIResponse executeAAIPostCall(DelegateExecution execution, String url, String payload){ - msoLogger.trace("Started Execute AAI Post Process ") - APIResponse apiResponse = null - try{ - String uuid = utils.getRequestID() - msoLogger.debug("Generated uuid is: " + uuid) - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml"); - - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPost(payload) - - msoLogger.trace("Completed Execute AAI Post Process ") - }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - - /** - * This reusable method can be used for making AAI Post Calls. The url - * and payload should be passed as a parameters along with the execution. - * The method will return an APIResponse. - * - * @param execution - * @param url - * @param payload - * @param authenticationHeader - addAuthenticationHeader value - * @param headerName - name of header you want to add, i.e. addHeader(headerName, headerValue) - * @param headerValue - the header's value, i.e. addHeader(headerName, headerValue) - * - * @return APIResponse - * - */ - public APIResponse executeAAIPostCall(DelegateExecution execution, String url, String payload, String authenticationHeaderValue, String headerName, String headerValue){ - msoLogger.trace("Started Execute AAI Post Process ") - APIResponse apiResponse = null - try{ - msoLogger.debug("URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addAuthorizationHeader(authenticationHeaderValue).addHeader(headerName, headerValue) - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPost(payload) - - msoLogger.trace("Completed Execute AAI Post Process ") - }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); - (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } - /* Utility to get the Cloud Region from AAI * Returns String cloud region id, (ie, cloud-region-id) @@ -449,9 +87,17 @@ class AaiUtil { public String getAAICloudReqion(DelegateExecution execution, String url, String backend, inputCloudRegion){ String regionId = "" try{ - APIResponse apiResponse = executeAAIGetCall(execution, url) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + URL Url = new URL(url) + HttpClient client = new HttpClient(Url, MediaType.APPLICATION_XML, TargetEntity.AAI) + client.addBasicAuthHeader(UrnPropertiesReader.getVariable("aai.auth", execution), UrnPropertiesReader.getVariable("mso.msoKey", execution)) + client.addAdditionalHeader("X-FromAppId", "MSO") + client.addAdditionalHeader("X-TransactionId", utils.getRequestID()) + client.addAdditionalHeader("Accept", MediaType.APPLICATION_XML) + + Response apiResponse = client.get() + + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) msoLogger.debug("Call AAI Cloud Region Return code: " + returnCode) execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionReturnCode", returnCode) @@ -491,19 +137,6 @@ class AaiUtil { return regionId } - /* returns xml Node with service-type of searchValue */ - def searchServiceType(xmlInput, searchValue){ - def fxml= new XmlSlurper().parseText(xmlInput) - def ret = fxml.'**'.find {it.'service-type' == searchValue} - return ret - } - - /* returns xml Node with service-instance-id of searchValue */ - def searchServiceInstanceId(xmlInput, searchValue){ - def ret = xmlInput.'**'.find {it.'service-instance-id' == searchValue} - return ret - } - /** * Get the lowest unused VF Module index from AAI response for a given module type. The criteria for * determining module type is specified by "key" parameter (for example, "persona-model-id"), diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy index 9ce29dedb8..d5183ff5bb 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtils.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,23 +23,23 @@ package org.onap.so.bpmn.common.scripts import org.json.JSONObject; import org.json.JSONArray; import org.json.XML +import org.onap.logging.ref.slf4j.ONAPLogConstants import org.onap.so.bpmn.core.UrnPropertiesReader; import org.springframework.web.util.UriUtils; import org.onap.so.bpmn.core.json.JsonUtils - - +import org.onap.so.client.HttpClient import groovy.json.JsonBuilder import groovy.json.JsonSlurper import groovy.util.slurpersupport.GPathResult import groovy.xml.QName; +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.logger.MsoLogger; -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.utils.TargetEntity import org.onap.so.logger.MessageEnum @@ -731,12 +731,12 @@ class CatalogDbUtils { String endPoint = "/serviceResources?serviceModelUuid=" + UriUtils.encode(serviceModelUuid, "UTF-8") try { String catalogDbResponse = getResponseFromCatalogDb(execution, endPoint) - + if (catalogDbResponse != null) { - + resources = parseServiceResourcesJson(catalogDbResponse, "v1") } - + } catch (Exception e) { utils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) @@ -1230,32 +1230,32 @@ class CatalogDbUtils { String catalogDbEndpoint = UrnPropertiesReader.getVariable("mso.catalog.db.endpoint",execution) String queryEndpoint = catalogDbEndpoint + "/" + defaultDbAdapterVersion + endPoint - RESTConfig config = new RESTConfig(queryEndpoint); def responseData = '' def bpmnRequestId = UUID.randomUUID().toString() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', bpmnRequestId). - addHeader('X-FromAppId', 'BPMN'). - addHeader('Content-Type', 'application/json'). - addHeader('Accept','application/json'); + URL url = new URL(queryEndpoint) + HttpClient client = new HttpClient(url, MediaType.APPLICATION_JSON, TargetEntity.CATALOG_DB) + client.addAdditionalHeader(ONAPLogConstants.Headers.REQUEST_ID, bpmnRequestId) + client.addAdditionalHeader('X-FromAppId', "BPMN") + client.addAdditionalHeader('Accept', MediaType.APPLICATION_JSON) String basicAuthCred = execution.getVariable("BasicAuthHeaderValueDB") if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) + client.addAdditionalHeader("Authorization", basicAuthCred) }else { - client.addAuthorizationHeader(getBasicDBAuthHeader(execution)) + client.addAdditionalHeader("Authorization", getBasicDBAuthHeader(execution)) } + msoLogger.debug('sending GET to Catalog DB endpoint: ' + endPoint) - APIResponse response = client.httpGet() + Response response = client.get() - responseData = response.getResponseBodyAsString() + responseData = response.readEntity(String.class) if (responseData != null) { msoLogger.debug("Received data from Catalog DB: " + responseData) } - msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response code:' + response.getStatus()) msoLogger.debug('Response:' + System.lineSeparator() + responseData) - if (response.getStatusCode() == 200) { + if (response.getStatus() == 200) { // parse response as needed return responseData } @@ -1291,14 +1291,14 @@ class CatalogDbUtils { return responseJson } - + private String getBasicDBAuthHeader(DelegateExecution execution) { - + String encodedString = null try { String basicAuthValueDB = UrnPropertiesReader.getVariable("mso.adapters.db.auth", execution) utils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB) - + encodedString = utils.getBasicAuth(basicAuthValueDB, UrnPropertiesReader.getVariable("mso.msoKey", execution)) execution.setVariable("BasicAuthHeaderValueDB",encodedString) } catch (IOException ex) { @@ -1307,5 +1307,5 @@ class CatalogDbUtils { } return encodedString } - + } \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy index 3096bedda6..5c935e9081 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/ExternalAPIUtil.groovy @@ -22,14 +22,16 @@ package org.onap.so.bpmn.common.scripts import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.onap.so.client.HttpClient import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.apache.commons.lang3.StringEscapeUtils import java.util.regex.Matcher import java.util.regex.Pattern +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response +import org.onap.so.utils.TargetEntity + class ExternalAPIUtil { String Prefix="EXTAPI_" @@ -127,23 +129,22 @@ class ExternalAPIUtil { * @return APIResponse * */ - public APIResponse executeExternalAPIGetCall(DelegateExecution execution, String url){ + public Response executeExternalAPIGetCall(DelegateExecution execution, String url){ msoLogger.debug(" ======== STARTED Execute ExternalAPI Get Process ======== ") - APIResponse apiResponse = null + Response apiResponse = null try{ String uuid = utils.getRequestID() msoLogger.debug( "Generated uuid is: " + uuid) msoLogger.debug( "URL to be used is: " + url) - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey")) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/json"); + URL Url = new URL(url) + HttpClient client = new HttpClient(Url, MediaType.APPLICATION_JSON, TargetEntity.EXTERNAL) + client.addBasicAuthHeader(execution.getVariable("URN_externalapi_auth"), execution.getVariable("URN_mso_msoKey")) + client.addAdditionalHeader("X-FromAppId", "MSO") + client.addAdditionalHeader(ONAPLogConstants.Headers.REQUEST_ID, uuid) + client.addAdditionalHeader("Accept", MediaType.APPLICATION_JSON) - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpGet() + apiResponse = client.get() msoLogger.debug( "======== COMPLETED Execute ExternalAPI Get Process ======== ") }catch(Exception e){ @@ -162,25 +163,25 @@ class ExternalAPIUtil { * @param url * @param payload * - * @return APIResponse + * @return Response * */ - public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload){ + public Response executeExternalAPIPostCall(DelegateExecution execution, String urlString, String payload){ msoLogger.debug( " ======== Started Execute ExternalAPI Post Process ======== ") - APIResponse apiResponse = null + Response apiResponse = null try{ String uuid = utils.getRequestID() msoLogger.debug( "Generated uuid is: " + uuid) - msoLogger.debug( "URL to be used is: " + url) + msoLogger.debug( "URL to be used is: " + urlString) - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey")) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/json").addHeader("Accept","application/json"); + URL url = new URL(urlString); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPost(payload) + HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.AAI) + httpClient.addBasicAuthHeader(execution.getVariable("URN_externalapi_auth"), execution.getVariable("URN_mso_msoKey")) + httpClient.addAdditionalHeader("X-FromAppId", "MSO") + httpClient.addAdditionalHeader("X-TransactionId", uuid) + + apiResponse = httpClient.post(payload) msoLogger.debug( "======== Completed Execute ExternalAPI Post Process ======== ") }catch(Exception e){ @@ -190,42 +191,6 @@ class ExternalAPIUtil { return apiResponse } - /** - * This reusable method can be used for making ExternalAPI Post Calls. The url - * and payload should be passed as a parameters along with the execution. - * The method will return an APIResponse. - * - * @param execution - * @param url - * @param payload - * @param authenticationHeader - addAuthenticationHeader value - * @param headerName - name of header you want to add, i.e. addHeader(headerName, headerValue) - * @param headerValue - the header's value, i.e. addHeader(headerName, headerValue) - * - * @return APIResponse - * - */ - public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload, String authenticationHeaderValue, String headerName, String headerValue){ - msoLogger.debug( " ======== Started Execute ExternalAPI Post Process ======== ") - APIResponse apiResponse = null - try{ - msoLogger.debug( "URL to be used is: " + url) - - String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey")) - - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addAuthorizationHeader(authenticationHeaderValue).addHeader(headerName, headerValue) - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - apiResponse = client.httpPost(payload) - msoLogger.debug( "======== Completed Execute ExternalAPI Post Process ======== ") - }catch(Exception e){ - msoLogger.error("Exception occured while executing ExternalAPI Post Call. Exception is: \n" + e) - exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage()) - } - return apiResponse - } } \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy index 78d147e819..c961dd06eb 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/GenerateVfModuleName.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,19 +24,20 @@ import org.onap.so.bpmn.core.UrnPropertiesReader import java.io.Serializable; +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.springframework.web.util.UriUtils import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.client.HttpClient import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.client.graphinventory.entities.uri.Depth -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.utils.TargetEntity import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -46,8 +47,8 @@ public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ def Prefix="GVFMN_" ExceptionUtil exceptionUtil = new ExceptionUtil() - - + + public void preProcessRequest(DelegateExecution execution) { try { def vnfId = execution.getVariable("vnfId") @@ -76,7 +77,7 @@ public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ try { def vnfId = execution.getVariable('vnfId') def personaModelId = execution.getVariable('personaModelId') - + AaiUtil aaiUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) uri.depth(Depth.ONE) @@ -85,34 +86,34 @@ public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ msoLogger.debug("AAI endPoint: " + endPoint) try { - RESTConfig config = new RESTConfig(endPoint); + HttpClient client = new HttpClient(new URL(endPoint), MediaType.APPLICATION_XML, TargetEntity.AAI) + client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString()) + client.addAdditionalHeader('X-FromAppId', 'MSO') + client.addAdditionalHeader('Content-Type', 'application/xml') + client.addAdditionalHeader('Accept','application/xml') + def responseData = '' - def aaiRequestId = UUID.randomUUID().toString() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', aaiRequestId). - addHeader('X-FromAppId', 'MSO'). - addHeader('Content-Type', 'application/xml'). - addHeader('Accept','application/xml'); + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - APIResponse response = client.httpGet() + Response response = client.get() msoLogger.debug("GenerateVfModuleName - invoking httpGet() to AAI") - responseData = response.getResponseBodyAsString() + responseData = response.readEntity(String.class) if (responseData != null) { msoLogger.debug("Received generic VNF data: " + responseData) } msoLogger.debug("GenerateVfModuleName - queryAAIVfModule Response: " + responseData) - msoLogger.debug("GenerateVfModuleName - queryAAIVfModule ResponseCode: " + response.getStatusCode()) + msoLogger.debug("GenerateVfModuleName - queryAAIVfModule ResponseCode: " + response.getStatus()) - execution.setVariable('GVFMN_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('GVFMN_queryAAIVfModuleResponseCode', response.getStatus()) execution.setVariable('GVFMN_queryAAIVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response code:' + response.getStatus()) msoLogger.debug('Response:' + System.lineSeparator() + responseData) - if (response.getStatusCode() == 200) { - // Set the VfModuleXML - if (responseData != null) { + if (response.getStatus() == 200) { + // Set the VfModuleXML + if (responseData != null) { String vfModulesText = utils.getNodeXml(responseData, "vf-modules") if (vfModulesText == null || vfModulesText.isEmpty()) { msoLogger.debug("There are no VF modules in this VNF yet") @@ -131,18 +132,18 @@ public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ def personaModelIdFromAAI = utils.getNodeText(vfModuleXml, "model-invariant-id") if (!personaModelIdFromAAI) { // check old attribute name - personaModelIdFromAAI = utils.getNodeText(vfModuleXml, "persona-model-id") + personaModelIdFromAAI = utils.getNodeText(vfModuleXml, "persona-model-id") } if (personaModelIdFromAAI != null && personaModelIdFromAAI.equals(personaModelId)) { matchingVfModules = matchingVfModules + utils.removeXmlPreamble(vfModuleXml) - } + } } matchingVfModules = matchingVfModules + "" - msoLogger.debug("Matching VF Modules: " + matchingVfModules) + msoLogger.debug("Matching VF Modules: " + matchingVfModules) execution.setVariable("GVFMN_vfModuleXml", matchingVfModules) } } - } + } } catch (Exception ex) { ex.printStackTrace() msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) @@ -155,18 +156,18 @@ public class GenerateVfModuleName extends AbstractServiceTaskProcessor{ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAI(): ' + e.getMessage()) } - + } - + public void generateName (DelegateExecution execution) { def method = getClass().getSimpleName() + '.generateName() ' + 'execution=' + execution.getId() + ')' msoLogger.trace('Entered ' + method) - - String vfModuleXml = execution.getVariable("GVFMN_vfModuleXml") - - String moduleIndex = utils.getLowestUnusedIndex(vfModuleXml) + + String vfModuleXml = execution.getVariable("GVFMN_vfModuleXml") + + String moduleIndex = utils.getLowestUnusedIndex(vfModuleXml) msoLogger.debug("moduleIndex is: " + moduleIndex) def vnfName = execution.getVariable("vnfName") def vfModuleLabel = execution.getVariable("vfModuleLabel") diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy index a1e63dc150..27d067dfc1 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/NetworkUtils.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,6 +22,9 @@ package org.onap.so.bpmn.common.scripts import groovy.xml.XmlUtil import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.L3Network +import org.onap.aai.domain.yang.Subnet +import org.onap.aai.domain.yang.Subnets import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.logger.MsoLogger import org.w3c.dom.Document @@ -64,7 +67,7 @@ class NetworkUtils { * @param cloudRegionId the cloud-region-region * @return String request */ - def CreateNetworkRequestV2(execution, requestId, messageId, requestInput, queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) { + def CreateNetworkRequestV2(execution, requestId, messageId, requestInput,L3Network queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) { String createNetworkRequest = null if(requestInput!=null && queryIdResponse!=null) { String serviceInstanceId = "" @@ -72,8 +75,8 @@ class NetworkUtils { String externalValue = "" if (source == "VID") { - sharedValue = utils.getNodeText(queryIdResponse, "is-shared-network") != null ? utils.getNodeText(queryIdResponse, "is-shared-network") : "false" - externalValue = utils.getNodeText(queryIdResponse, "is-external-network") != null ? utils.getNodeText(queryIdResponse, "is-external-network") : "false" + sharedValue = queryIdResponse.isIsSharedNetwork() != null ? queryIdResponse.isIsSharedNetwork() : "false" + externalValue = queryIdResponse.isIsExternalNetwork() != null ? queryIdResponse.isIsExternalNetwork() : "false" serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id") } else { // source = 'PORTAL' @@ -100,14 +103,14 @@ class NetworkUtils { networkType = utils.getNodeText(networkModelInfo, "modelName") modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid") } else { - networkType = utils.getNodeText(queryIdResponse, "network-type") + networkType = queryIdResponse.getNetworkType() modelCustomizationUuid = utils.getNodeText(requestInput, "modelCustomizationId") } // queryIdResponse - String networkName = utils.getNodeText(queryIdResponse, "network-name") - String networkId = utils.getNodeText(queryIdResponse, "network-id") - String networkTechnology = utils.getNodeText(queryIdResponse, "network-technology") + String networkName = queryIdResponse.getNetworkName() + String networkId = queryIdResponse.getNetworkId() + String networkTechnology = queryIdResponse.getNetworkTechnology() // contrailNetwork - networkTechnology = 'Contrail' vs. 'AIC_SR_IOV') String contrailNetwork = "" @@ -124,13 +127,12 @@ class NetworkUtils { // rebuild subnets String subnets = "" - if (utils.nodeExists(queryIdResponse, "subnets")) { - def subnetsGroup = utils.getNodeXml(queryIdResponse, "subnets", false) - subnets = buildSubnets(subnetsGroup) + if (queryIdResponse.getSubnets() != null) { + subnets = buildSubnets(queryIdResponse) } String physicalNetworkName = "" - physicalNetworkName = utils.getNodeText(queryIdResponse, "physical-network-name") + physicalNetworkName = queryIdResponse.getPhysicalNetworkName() String vlansCollection = buildVlans(queryIdResponse) @@ -181,7 +183,7 @@ class NetworkUtils { * @param cloudRegionId the cloud-region-region * @return String request */ - def UpdateNetworkRequestV2(execution, requestId, messageId, requestInput, queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) { + def UpdateNetworkRequestV2(execution, requestId, messageId, requestInput, L3Network queryIdResponse, routeCollection, policyFqdns, tableCollection, cloudRegionId, backoutOnFailure, source) { String updateNetworkRequest = null if(requestInput!=null && queryIdResponse!=null) { String serviceInstanceId = "" @@ -189,8 +191,8 @@ class NetworkUtils { String externalValue = "" if (source == "VID") { - sharedValue = utils.getNodeText(queryIdResponse, "is-shared-network") != null ? utils.getNodeText(queryIdResponse, "is-shared-network") : "false" - externalValue = utils.getNodeText(queryIdResponse, "is-external-network") != null ? utils.getNodeText(queryIdResponse, "is-external-network") : "false" + sharedValue = queryIdResponse.isIsSharedNetwork() != null ? queryIdResponse.isIsSharedNetwork() : "false" + externalValue = queryIdResponse.isIsExternalNetwork() != null ? queryIdResponse.isIsExternalNetwork() : "false" serviceInstanceId = utils.getNodeText(requestInput, "service-instance-id") } else { // source = 'PORTAL' @@ -205,9 +207,9 @@ class NetworkUtils { String tenantId = utils.getNodeText(requestInput, "tenant-id") // queryIdResponse - String networkName = utils.getNodeText(queryIdResponse, "network-name") - String networkId = utils.getNodeText(queryIdResponse, "network-id") - + String networkName = queryIdResponse.getNetworkName() + String networkId = queryIdResponse.getNetworkId() + String networkType = "" String modelCustomizationUuid = "" if (utils.nodeExists(requestInput, "networkModelInfo")) { @@ -215,15 +217,14 @@ class NetworkUtils { networkType = utils.getNodeText(networkModelInfo, "modelName") modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid") } else { - networkType = utils.getNodeText(queryIdResponse, "network-type") + networkType = queryIdResponse.getNetworkType() modelCustomizationUuid = utils.getNodeText(requestInput, "modelCustomizationId") } // rebuild subnets String subnets = "" - if (utils.nodeExists(queryIdResponse, "subnets")) { - def subnetsGroup = utils.getNodeXml(queryIdResponse, "subnets", false) - subnets = buildSubnets(subnetsGroup) + if (queryIdResponse.getSubnets() != null) { + subnets = buildSubnets(queryIdResponse) } String networkParams = "" @@ -232,12 +233,12 @@ class NetworkUtils { networkParams = buildParams(netParams) } - String networkStackId = utils.getNodeText(queryIdResponse, "heat-stack-id") + String networkStackId = queryIdResponse.getHeatStackId() if (networkStackId == 'null' || networkStackId == "" || networkStackId == null) { networkStackId = "force_update" } - String physicalNetworkName = utils.getNodeText(queryIdResponse, "physical-network-name") + String physicalNetworkName = queryIdResponse.getPhysicalNetworkName() String vlansCollection = buildVlans(queryIdResponse) updateNetworkRequest = @@ -418,7 +419,7 @@ class NetworkUtils { rebuildSegmentationAssignments = buildXMLElements(requeryIdAAIResponse, "segmentation-assignments", "segmentation-assignment", elementList) } else { rebuildSegmentationAssignments = buildXMLElements(requeryIdAAIResponse, "", "segmentation-assignments", elementList) - } + } } // rebuild 'ctag-assignments' / rebuildCtagAssignments @@ -736,7 +737,7 @@ class NetworkUtils { return rtn } - + def isInstanceValueMatch(linkResource, globalSubscriberId, serviceType) { Boolean rtn = false try { @@ -809,7 +810,7 @@ class NetworkUtils { } else { //pending-update or PendingUpdate xmlNetwork += "<"+element+">"+"Active"+"" } - } + } if (element=="heat-stack-id") { if (replaceNetworkId != "") { xmlNetwork += "<"+element+">"+replaceNetworkId+"" @@ -834,11 +835,11 @@ class NetworkUtils { } else { //pending-update or PendingUpdate xmlNetwork += "<"+element+">"+"Active"+"" } - } + } } else { xmlNetwork += "<"+element+">"+var.toString()+"" } - } + } } } return xmlNetwork @@ -863,7 +864,7 @@ class NetworkUtils { } else { def subnetList = ["subnet-id", "neutron-subnet-id", "gateway-address", "network-start-address", "cidr-mask", "ip-version", "orchestration-status", "dhcp-enabled", "dhcp-start", "dhcp-end", "subnet-role", "resource-version", "subnet-name", "ip-assignment-direction", "host-routes"] rebuildingSubnets += buildSubNetworkElements(subnetXml, createNetworkResponse, subnetList, "subnet") - } + } } if (utils.nodeExists(subnetsData, 'relationship')) { rebuildingSubnets = rebuildRelationship(requeryIdAAIResponse) @@ -878,29 +879,24 @@ class NetworkUtils { return rebuildingSubnets } - def buildSubnets(queryIdResponse) { + def buildSubnets(L3Network network) { 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.getNodeText(subnetXml, "orchestration-status") - if (orchestrationStatus == "pending-delete" || orchestrationStatus == "PendingDelete") { - // skip, do not include in processing, remove!!! - } else { - def subnetList = ["dhcp-start", "dhcp-end", "network-start-address", "cidr-mask", "dhcp-enabled", "gateway-address", "ip-version", "subnet-id", "subnet-name", "ip-assignment-direction", "host-routes"] - rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "subnets") - //rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "") - } + Subnets subnets = network.getSubnets() + try{ + for(Subnet s : subnets.getSubnet()){ + def orchestrationStatus = s.getOrchestrationStatus() + if (orchestrationStatus == "pending-delete" || orchestrationStatus == "PendingDelete") { + // skip, do not include in processing, remove!!! + } else { + def subnetList = ["dhcp-start", "dhcp-end", "network-start-address", "cidr-mask", "dhcp-enabled", "gateway-address", "ip-version", "subnet-id", "subnet-name", "ip-assignment-direction", "host-routes"] + rebuildingSubnets += buildSubNetworkElements(s, subnetList, "subnets") + //rebuildingSubnets += buildSubNetworkElements(subnetXml, subnetList, "") + } } } catch (Exception ex) { - // + // } finally { - //rebuildingSubnets += "" + //rebuildingSubnets += "" } return rebuildingSubnets } @@ -919,7 +915,7 @@ class NetworkUtils { var = xml.'**'.find {it.name() == element} if (var != null) { if (element=="orchestration-status") { - if(var.toString() == 'pending-create' || var.toString() == 'PendingCreate') { + if(var.toString() == 'pending-create' || var.toString() == 'PendingCreate') { xmlBuild += "<"+element+">"+"Created"+"" } else { // pending-update or PendingUpdate' xmlBuild += "<"+element+">"+"Active"+"" @@ -940,9 +936,9 @@ class NetworkUtils { List elementRoute = ["host-route-id", "route-prefix", "next-hop", "next-hop-type", "resource-version"] xmlBuild += buildXMLElements(subnetXml, "host-routes", "host-route", elementRoute) } - } else { + } else { xmlBuild += "<"+element+">"+var.toString()+"" - } + } } } } @@ -957,68 +953,69 @@ class NetworkUtils { } // build subnet sub-network single elements - def buildSubNetworkElements(subnetXml, elementList, parentName) { + def buildSubNetworkElements(Subnet subnet, elementList, parentName) { + def var = "" def xmlBuild = "" if (parentName != "") { xmlBuild += "<"+parentName+">" } - if (subnetXml != null) { + if (subnet != null) { def networkStartAddress = "" for (element in elementList) { - def xml= new XmlSlurper().parseText(subnetXml) - var = xml.'**'.find {it.name() == element} if (element == "dhcp-start") { + var = subnet.getDhcpStart() xmlBuild += "" - if (var.toString() == 'null') { + if (var == null) { xmlBuild += ""+""+"" } else { - xmlBuild += ""+var.toString()+"" + xmlBuild += ""+var+"" } } if (element == "dhcp-end") { - if (var.toString() == 'null') { + var = subnet.getDhcpEnd() + if (var == null) { xmlBuild += ""+""+"" } else { - xmlBuild += ""+var.toString()+"" + xmlBuild += ""+var+"" } xmlBuild += "" } if (element == "network-start-address" || element == "cidr-mask") { if (element == "network-start-address") { - networkStartAddress = var.toString() + networkStartAddress = subnet.getNetworkStartAddress() } if (element == "cidr-mask") { - xmlBuild += ""+networkStartAddress+"/"+var.toString()+"" + xmlBuild += ""+networkStartAddress+"/"+var+"" } } if (element == "dhcp-enabled") { - xmlBuild += ""+var.toString()+"" + xmlBuild += ""+subnet.isDhcpEnabled()+"" } if (element == "gateway-address") { - xmlBuild += ""+var.toString()+"" + xmlBuild += ""+subnet.getGatewayAddress()+"" } if (element == "ip-version") { - String ipVersion = getIpvVersion(var.toString()) + String ipVersion = getIpvVersion(subnet.getIpVersion()) xmlBuild += ""+ipVersion+"" } if (element == "subnet-id") { - xmlBuild += ""+var.toString()+"" + xmlBuild += ""+subnet.getSubnetId()+"" } - if ((element == "subnet-name") && (var != null)) { - xmlBuild += ""+var.toString()+"" + if ((element == "subnet-name") && (subnet.getSubnetName() != null)) { + xmlBuild += ""+subnet.getSubnetName()+"" } - if ((element == "ip-assignment-direction") && (var != null)) { - xmlBuild += ""+var.toString()+"" + if ((element == "ip-assignment-direction") && (subnet.getIpAssignmentDirection() != null)) { + xmlBuild += ""+subnet.getIpAssignmentDirection()+"" } if (element == "host-routes") { def routes = "" - if (subnetXml.contains("host-routes")) { - routes = buildHostRoutes(subnetXml) + if (subnet.getHostRoutes() != null) { + routes = buildHostRoutes(subnet) } - xmlBuild += routes - } - + xmlBuild += routes + } + } } if (parentName != "") { @@ -1053,12 +1050,12 @@ class NetworkUtils { } } buildHostRoutes += "" - } - } - return buildHostRoutes - + } + } + return buildHostRoutes + } - + // rebuild ctag-assignments def rebuildCtagAssignments(xmlInput) { def rebuildingCtagAssignments = "" @@ -1396,17 +1393,17 @@ class NetworkUtils { } return rollbackEnabled } - - + + /** * This method extracts the version for the the given ip-version. * * @param String ipvVersion - IP protocols version (ex: ipv4 or ipv6 or 4 or 6) * @return String version - digit version (ex: 4 or 6) */ - + public String getIpvVersion (String ipvVersion) { - + String version = "" try { if (ipvVersion.isNumber()) { @@ -1418,7 +1415,7 @@ class NetworkUtils { } } } catch (Exception ex) { - version = ipvVersion + version = ipvVersion } return version } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy index 533df72285..2e937ed134 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofHoming.groovy @@ -32,12 +32,13 @@ import org.onap.so.bpmn.core.domain.ServiceDecomposition import org.onap.so.bpmn.core.domain.Subscriber import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient +import org.onap.so.logger.MsoLogger import org.onap.so.db.catalog.beans.CloudIdentity import org.onap.so.db.catalog.beans.CloudSite -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig + import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.utils.TargetEntity import org.json.JSONArray import org.json.JSONObject @@ -45,6 +46,8 @@ import org.springframework.web.util.UriUtils import static org.onap.so.bpmn.common.scripts.GenericUtils.* +import javax.ws.rs.core.Response + /** * This class contains the scripts used * by the OOF Homing Subflow building block. The @@ -135,7 +138,7 @@ class OofHoming extends AbstractServiceTaskProcessor { //Prepare Callback String timeout = execution.getVariable("timeout") - if (isBlank(timeout)) { + if (isBlank(timeout)) { timeout = UrnPropertiesReader.getVariable("mso.oof.timeout", execution); if (isBlank(timeout)) { timeout = "PT30M" @@ -153,25 +156,18 @@ class OofHoming extends AbstractServiceTaskProcessor { execution.setVariable("oofRequest", oofRequest) utils.log("DEBUG", "OOF Request is: " + oofRequest, isDebugEnabled) - String url = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution) - utils.log("DEBUG", "Posting to OOF Url: " + url, isDebugEnabled) + String urlString = UrnPropertiesReader.getVariable("mso.oof.endpoint", execution) + utils.log("DEBUG", "Posting to OOF Url: " + urlString, isDebugEnabled) - logDebug("URL to be used is: " + url, isDebugEnabled) - RESTConfig config = new RESTConfig(url) - RESTClient client = new RESTClient(config).addAuthorizationHeader(authHeader). - addHeader("Content-Type", "application/json") - APIResponse response = client.httpPost(oofRequest) + URL url = new URL(urlString); + HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.SNIRO) + httpClient.addAdditionalHeader("Authorization", authHeader) + Response httpResponse = httpClient.post(oofRequest) - int responseCode = response.getStatusCode() - logDebug("OOF sync response code is: " + responseCode, isDebugEnabled) - String syncResponse = response.getResponseBodyAsString() - execution.setVariable("syncResponse", syncResponse) - logDebug("OOF sync response is: " + syncResponse, isDebugEnabled) + int responseCode = httpResponse.getStatus() + logDebug("OOF sync response code is: " + responseCode, isDebugEnabled) - if(responseCode != 202){ - exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.") - } utils.log("DEBUG", "*** Completed Homing Call OOF ***", isDebugEnabled) } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy index 197589efa1..b9bc1c7c00 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/OofUtils.groovy @@ -33,10 +33,9 @@ import org.onap.so.bpmn.core.domain.ServiceInstance import org.onap.so.bpmn.core.domain.Subscriber import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient import org.onap.so.db.catalog.beans.CloudSite -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.utils.TargetEntity import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod @@ -504,22 +503,16 @@ class OofUtils { String auth = UrnPropertiesReader.getVariable("mso.db.auth", execution) String uri = "/cloudSite" - HttpHeaders headers = new HttpHeaders() + URL url = new URL(endpoint + uri) + HttpClient client = new HttpClient(url, MediaType.APPLICATION_JSON, TargetEntity.EXTERNAL) + client.addAdditionalHeader(HttpHeaders.AUTHORIZATION, auth) + client.addAdditionalHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON) - headers.set(HttpHeaders.AUTHORIZATION, auth) - headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON) - headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + Response response = client.post(request.getBody().toString()) - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(endpoint + uri) - HttpEntity request = new HttpEntity(cloudSite, headers) - RESTConfig config = new RESTConfig(endpoint + uri) - RESTClient client = new RESTClient(config).addAuthorizationHeader(auth). - addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON).addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - APIResponse response = client.httpPost(request.getBody().toString()) - - int responseCode = response.getStatusCode() + int responseCode = response.getStatus() logDebug("CatalogDB response code is: " + responseCode, isDebugEnabled) - String syncResponse = response.getResponseBodyAsString() + String syncResponse = response.readEntity(String.class) logDebug("CatalogDB response is: " + syncResponse, isDebugEnabled) if(responseCode != 202){ diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy index 1a55bf2a0e..8f0e481c9a 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModule.groovy @@ -34,9 +34,6 @@ import org.onap.so.client.aai.entities.AAIResultWrapper import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.client.graphinventory.entities.uri.Depth -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.springframework.web.util.UriUtils import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -214,74 +211,31 @@ public class PrepareUpdateAAIVfModule extends VfModuleBase { msoLogger.trace('Entered ' + method) try { - // Construct payload - org.onap.aai.domain.yang.VfModule vfModule = execution.getVariable('PUAAIVfMod_vfModule') - - def orchestrationStatus = execution.getVariable('PUAAIVfMod_orchestrationStatus') - - vfModule.setOrchestrationStatus(orchestrationStatus) - - //def payload = utils.nodeToString(newVfModuleNode) - - // Construct endpoint def vnfId = execution.getVariable('PUAAIVfMod_vnfId') def vfModuleId = execution.getVariable('PUAAIVfMod_vfModuleId') + def orchestrationStatus = execution.getVariable('PUAAIVfMod_orchestrationStatus') - def payload = """{ - "vf-module-id": "${vfModuleId}", - "orchestration-status": "${orchestrationStatus}" - }""" + org.onap.aai.domain.yang.VfModule vfModule = execution.getVariable('PUAAIVfMod_vfModule') - msoLogger.debug("VfModule payload : " + payload) + vfModule.setVfModuleId(vfModuleId) + vfModule.setOrchestrationStatus(orchestrationStatus) - AaiUtil aaiUtil = new AaiUtil(this) + AAIResourcesClient client = new AAIResourcesClient() AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - uri.depth(Depth.ONE) - String endPoint = aaiUtil.createAaiUri(uri) + client.update(uri, vfModule) + + // Set the output for this flow. The updated VfModule is an output, the generic VNF name, and for + // backward compatibilty, the heat-stack-id is an output + execution.setVariable('PUAAIVfMod_outVfModule', vfModule) + def vnfName = execution.getVariable('PUAAIVfMod_vnfName') + msoLogger.debug('Output PUAAIVfMod_vnfName set to ' + vnfName) + // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead + execution.setVariable('WorkflowResponse', vfModule) + + def heatStackId = vfModule.getHeatStackId() + execution.setVariable('PUAAIVfMod_heatStackId', heatStackId) + msoLogger.debug('Output PUAAIVfMod_heatStackId set to \'' + heatStackId + '\'') - msoLogger.debug("PrepareUpdateAAIVfModule: AAI endPoint : " + endPoint) - String basicAuthCred = utils.getBasicAuth(UrnPropertiesReader.getVariable("aai.auth", execution),UrnPropertiesReader.getVariable("mso.msoKey", execution)) - try { - RESTConfig config = new RESTConfig(endPoint); - def responseData = '' - def aaiRequestId = utils.getRequestID() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', aaiRequestId). - addHeader('X-FromAppId', 'MSO'). - addHeader('Content-Type', 'application/merge-patch+json'). - addHeader('Accept','application/json'); - if (basicAuthCred != null && !"".equals(basicAuthCred)) { - client.addAuthorizationHeader(basicAuthCred) - } - msoLogger.debug('sending PATCH to AAI endpoint \'' + endPoint + '\'' + 'with payload \n' + payload) - APIResponse response = client.httpPatch(payload) - msoLogger.debug("PrepareUpdateAAIVfModule: - invoking httpPatch to AAI") - - responseData = response.getResponseBodyAsString() - execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', response.getStatusCode()) - execution.setVariable('PUAAIVfMod_updateVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) - msoLogger.debug('Response:' + System.lineSeparator() + responseData) - msoLogger.debug("PrepareUpdateAAIVfModule: AAI Response : " + responseData) - msoLogger.debug("PrepareUpdateAAIVfModule: AAI ResponseCode : " + response.getStatusCode()) - - // Set the output for this flow. The updated VfModule is an output, the generic VNF name, and for - // backward compatibilty, the heat-stack-id is an output - execution.setVariable('PUAAIVfMod_outVfModule', vfModule) - def vnfName = execution.getVariable('PUAAIVfMod_vnfName') - msoLogger.debug('Output PUAAIVfMod_vnfName set to ' + vnfName) - // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead - execution.setVariable('WorkflowResponse', vfModule) - - def heatStackId = vfModule.getHeatStackId() - execution.setVariable('PUAAIVfMod_heatStackId', heatStackId) - msoLogger.debug('Output PUAAIVfMod_heatStackId set to \'' + heatStackId + '\'') - } catch (Exception ex) { - ex.printStackTrace() - msoLogger.debug('Exception occurred while executing AAI PUT:' + ex.getMessage()) - execution.setVariable('PUAAIVfMod_updateVfModuleResponseCode', 500) - execution.setVariable('PUAAIVfMod_updateVfModuleResponse', 'AAI PATCH Failed:' + ex.getMessage()) - } msoLogger.trace('Exited ' + method) } catch (BpmnError e) { throw e; diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy index f610ea4782..d7fc6ac995 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV1.groovy @@ -21,6 +21,7 @@ package org.onap.so.bpmn.common.scripts import java.text.SimpleDateFormat +import javax.ws.rs.core.Response import java.net.URLEncoder import org.apache.commons.codec.binary.Base64 @@ -36,11 +37,10 @@ import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.domain.RollbackData import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.client.HttpClient import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger +import org.onap.so.utils.TargetEntity @@ -205,23 +205,23 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { String sdncAdapterRequest = execution.getVariable(prefix + 'sdncAdapterRequest') msoLogger.debug("SDNC Rest Request is: " + sdncAdapterRequest) - RESTConfig config = new RESTConfig(sdncAdapterUrl) - RESTClient client = new RESTClient(config). - addHeader("Content-Type", "application/json") - .addHeader("mso-request-id",execution.getVariable("mso-request-id")) - .addHeader("mso-service-instance-id",execution.getVariable("mso-service-instance-id")) - .addAuthorizationHeader(execution.getVariable(prefix + "basicAuthHeaderValue")) + URL url = new URL(sdncAdapterUrl); - APIResponse response + HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.SDNC_ADAPTER) + httpClient.addAdditionalHeader("mso-request-id", execution.getVariable("mso-request-id")) + httpClient.addAdditionalHeader("mso-service-instance-id", execution.getVariable("mso-service-instance-id")) + httpClient.addAdditionalHeader("Authorization", execution.getVariable(prefix + "basicAuthHeaderValue")) + + Response response if ("GET".equals(sdncAdapterMethod)) { - response = client.httpGet() + response = httpClient.get() } else if ("PUT".equals(sdncAdapterMethod)) { - response = client.httpPut(sdncAdapterRequest) + response = httpClient.put(sdncAdapterRequest) } else if ("POST".equals(sdncAdapterMethod)) { - response = client.httpPost(sdncAdapterRequest) + response = httpClient.post(sdncAdapterRequest) } else if ("DELETE".equals(sdncAdapterMethod)) { - response = client.httpDelete(sdncAdapterRequest) + response = httpClient.delete(sdncAdapterRequest) } else { String msg = 'Unsupported HTTP method "' + sdncAdapterMethod + '" in ' + method + ": " + e msoLogger.debug(msg) @@ -229,13 +229,15 @@ class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } - execution.setVariable(prefix + "sdncAdapterStatusCode", response.getStatusCode()) - execution.setVariable(prefix + "sdncAdapterResponse", response.getResponseBodyAsString()) + execution.setVariable(prefix + "sdncAdapterStatusCode", response.getStatus()) + if(response.hasEntity()){ + execution.setVariable(prefix + "sdncAdapterResponse", response.readEntity(String.class)) + } } catch (BpmnError e) { throw e } catch (Exception e) { String msg = 'Caught exception in ' + method + ": " + e - msoLogger.debug(msg) + msoLogger.debug(msg, e) msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy index 967b9fa93f..1a20497bbc 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SDNCAdapterRestV2.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -34,9 +34,6 @@ import org.json.JSONObject import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -224,7 +221,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { if (responseType.endsWith('Error')) { sdncAdapterBuildWorkflowException(execution, callback) } - + // Check for possible interim notification execution.setVariable(prefix + "interimNotification", null) execution.setVariable(prefix + "doInterimNotification", false) @@ -235,7 +232,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { execution.setVariable(prefix + "doInterimNotification", true) } } - + } catch (Exception e) { callback = callback == null || String.valueOf(callback).isEmpty() ? "NONE" : callback String msg = "Received error from SDNCAdapter: " + callback @@ -243,7 +240,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { exceptionUtil.buildWorkflowException(execution, 5300, msg) } } - + /** * Prepare to send an interim notification by extracting the variable/value definitions * in the interimNotification JSON object and placing them in the execution. These @@ -254,21 +251,21 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { 'execution=' + execution.getId() + ')' msoLogger.trace('Entered ' + method) - + String prefix = execution.getVariable('prefix') msoLogger.debug("Preparing Interim Notification") try { def interimNotification = execution.getVariable(prefix + "interimNotification") msoLogger.debug("Preparing Interim Notification:\n" + JsonUtils.prettyJson(interimNotification)) - + for (int i = 0; ; i++) { def variable = JsonUtils.getJsonParamValue(interimNotification, 'variableList', 'variable', i) - + if (variable == null) { break } - + def String variableName = JsonUtils.getJsonValue(variable, "name") if ((variableName != null) && !variableName.isEmpty()) { def variableValue = JsonUtils.getJsonValue(variable, "value") @@ -276,7 +273,7 @@ class SDNCAdapterRestV2 extends SDNCAdapterRestV1 { msoLogger.debug("Setting "+ variableName + "=" + variableValue) } } - + } catch (Exception e) { String msg = "Error preparing interim notification" msoLogger.debug(getProcessKey(execution) + ': ' + msg) diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroHomingV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroHomingV1.groovy index 8d14ead6e0..401cac9820 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroHomingV1.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/SniroHomingV1.groovy @@ -33,15 +33,18 @@ import org.onap.so.bpmn.core.domain.ServiceDecomposition import org.onap.so.bpmn.core.domain.Subscriber import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.client.HttpClient +import org.onap.so.utils.TargetEntity import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.json.JSONArray import org.json.JSONObject import static org.onap.so.bpmn.common.scripts.GenericUtils.*; + +import java.net.URL + +import javax.ws.rs.core.Response import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger @@ -126,20 +129,25 @@ class SniroHomingV1 extends AbstractServiceTaskProcessor{ String endpoint = UrnPropertiesReader.getVariable("sniro.manager.uri.v1", execution) String host = UrnPropertiesReader.getVariable("sniro.manager.host", execution) - String url = host + endpoint - msoLogger.debug("Sniro Url is: " + url) + String urlString = host + endpoint + msoLogger.debug("Sniro Url is: " + urlString) + + URL url = new URL(urlString); + HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.SNIRO) + httpClient.addAdditionalHeader("Authorization", authHeader) + Response httpResponse = httpClient.post(sniroRequest) - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addAuthorizationHeader(authHeader).addHeader("Content-Type", "application/json") - APIResponse response = client.httpPost(sniroRequest) + int responseCode = httpResponse.getStatus() - int responseCode = response.getStatusCode() msoLogger.debug("Sniro sync response code is: " + responseCode) - msoLogger.debug("Sniro sync response is: " + response.getResponseBodyAsString()) + if(httpResponse.hasEntity()){ + msoLogger.debug("Sniro sync response is: " + httpResponse.readEntity(String.class)) + } if(responseCode != 202){ exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from Sniro.") } + msoLogger.trace("Completed Sniro Homing Call Sniro") } }catch(BpmnError b){ diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy index 52f45c205c..13cc7f8d11 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,15 +20,15 @@ package org.onap.so.bpmn.common.scripts +import javax.ws.rs.core.Response import org.apache.commons.lang3.* import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.core.UrnPropertiesReader -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.client.HttpClient import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger +import org.onap.so.utils.TargetEntity @@ -67,7 +67,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { if ('rollbackVolumeGroupRequest'.equals(requestType)) { messageId = getMessageIdForVolumeGroupRollback(root) } - + if (messageId == null || messageId.isEmpty()) { String msg = getProcessKey(execution) + ': no messageId in ' + requestType msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); @@ -281,7 +281,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } } - + public String getVolumeGroupIdFromRollbackRequest(Node root) { return root.'volumeGroupRollback'.'volumeGroupId'.text() } @@ -289,7 +289,7 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { public String getMessageIdForVolumeGroupRollback(Node root) { return root.'volumeGroupRollback'.'messageId'.text() } - + /** * This method is used instead of an HTTP Connector task because the * connector does not allow DELETE with a body. @@ -307,29 +307,31 @@ class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { String vnfAdapterUrl = execution.getVariable(prefix + 'vnfAdapterUrl') String vnfAdapterRequest = execution.getVariable(prefix + 'vnfAdapterRequest') - RESTConfig config = new RESTConfig(vnfAdapterUrl) - RESTClient client = new RESTClient(config). - addHeader("Content-Type", "application/xml"). - addAuthorizationHeader(execution.getVariable(prefix + "basicAuthHeaderValue")); + URL url = new URL(vnfAdapterUrl); - APIResponse response; + HttpClient httpClient = new HttpClient(url, "application/xml", TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Authorization", execution.getVariable(prefix + "basicAuthHeaderValue")) + + Response response; if ("GET".equals(vnfAdapterMethod)) { - response = client.httpGet() + response = httpClient.get() } else if ("PUT".equals(vnfAdapterMethod)) { - response = client.httpPut(vnfAdapterRequest) + response = httpClient.put(vnfAdapterRequest) } else if ("POST".equals(vnfAdapterMethod)) { - response = client.httpPost(vnfAdapterRequest) + response = httpClient.post(vnfAdapterRequest) } else if ("DELETE".equals(vnfAdapterMethod)) { - response = client.httpDelete(vnfAdapterRequest) + response = httpClient.delete(vnfAdapterRequest) } else { String msg = 'Unsupported HTTP method "' + vnfAdapterMethod + '" in ' + method + ": " + e msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } - execution.setVariable(prefix + "vnfAdapterStatusCode", response.getStatusCode()) - execution.setVariable(prefix + "vnfAdapterResponse", response.getResponseBodyAsString()) + execution.setVariable(prefix + "vnfAdapterStatusCode", response.getStatus()) + if(response.hasEntity()){ + execution.setVariable(prefix + "vnfAdapterResponse", response.readEntity(String.class)) + } } catch (BpmnError e) { throw e } catch (Exception e) { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java index 39c32de77d..eb7290b685 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/workflow/context/WorkflowContextHolder.java @@ -81,13 +81,10 @@ public class WorkflowContextHolder { 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); + if (requestId.equals(context.getRequestId())) { return context; } } - - msoLogger.debug("Unable to find context for request id: " + requestId); return null; } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java new file mode 100644 index 0000000000..cb9c681fd5 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/AggregateRoute.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.servicedecomposition.bbobjects; + +import java.io.Serializable; + +import javax.persistence.Id; + +import org.onap.so.bpmn.servicedecomposition.ShallowCopy; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonRootName; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.EqualsBuilder; + +@JsonRootName("aggregate-route") +public class AggregateRoute implements Serializable, ShallowCopy{ + + private static final long serialVersionUID = -1059128545462701696L; + + @Id + @JsonProperty("route-id") + private String routeId; + @JsonProperty("route-name") + private String routeName; + @JsonProperty("network-start-address") + private String networkStartAddress; + @JsonProperty("cidr-mask") + private String cidrMask; + @JsonProperty("ip-version") + private String ipVersion; + + + public String getRouteId(){ + return routeId; + } + + public void setRouteId(String routeId){ + this.routeId = routeId; + } + + public String getRouteName(){ + return routeName; + } + + public void setRouteName(String routeName){ + this.routeName = routeName; + } + + public String getNetworkStartAddress(){ + return networkStartAddress; + } + + public void setNetworkStartAddress(String networkStartAddress){ + this.networkStartAddress = networkStartAddress; + } + + public String getCidrMask(){ + return cidrMask; + } + + public void setCidrMask(String cidrMask){ + this.cidrMask = cidrMask; + } + + public String getIpVersion(){ + return ipVersion; + } + + public void setIpVersion(String ipVersion){ + this.ipVersion = ipVersion; + } + + @Override + public boolean equals(final Object other){ + if(!(other instanceof AggregateRoute)){ + return false; + } + AggregateRoute castOther = (AggregateRoute) other; + return new EqualsBuilder().append(routeId, castOther.routeId).isEquals(); + } + + @Override + public int hashCode(){ + return new HashCodeBuilder().append(routeId).toHashCode(); + } + + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3Network.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3Network.java index 5f43ba076a..343bd95eaa 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3Network.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/L3Network.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -41,7 +41,7 @@ import com.fasterxml.jackson.annotation.JsonRootName; public class L3Network implements Serializable, ShallowCopy { private static final long serialVersionUID = 4434492567957111317L; - + @Id @JsonProperty("network-id") private String networkId; @@ -99,6 +99,8 @@ public class L3Network implements Serializable, ShallowCopy { private List segmentationAssignments = new ArrayList<>(); @JsonProperty("model-info-network") private ModelInfoNetwork modelInfoNetwork; + @JsonProperty("aggregate-routes") + private List aggregateRoutes = new ArrayList<>(); public ModelInfoNetwork getModelInfoNetwork() { return modelInfoNetwork; @@ -254,6 +256,11 @@ public class L3Network implements Serializable, ShallowCopy { public void setCloudParams(Map cloudParams) { this.cloudParams = cloudParams; } + + public List getAggregateRoutes(){ + return aggregateRoutes; + } + @Override public boolean equals(final Object other) { if (!(other instanceof L3Network)) { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java index e815051eaa..32540eb996 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java @@ -33,6 +33,7 @@ import org.onap.so.db.catalog.beans.macro.RainyDayHandlerStatus; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.logger.MsoLogger; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component @@ -44,12 +45,17 @@ public class ExecuteBuildingBlockRainyDay { @Autowired private CatalogDbClient catalogDbClient; private static final String ASTERISK = "*"; + + @Autowired + private Environment environment; + protected String retryDurationPath = "mso.rainyDay.retryDurationMultiplier"; public void setRetryTimer(DelegateExecution execution) { try { + int retryDurationMult = Integer.parseInt(this.environment.getProperty(retryDurationPath)); int retryCount = (int) execution.getVariable("retryCount"); - int retryTimeToWait = (int) Math.pow(5, retryCount); - String RetryDuration = "PT" + retryTimeToWait + "M"; + int retryTimeToWait = (int) Math.pow(retryDurationMult, retryCount) * 10; + String RetryDuration = "PT" + retryTimeToWait + "S"; execution.setVariable("RetryDuration", RetryDuration); } catch (Exception e) { msoLogger.error(e); @@ -64,6 +70,7 @@ public class ExecuteBuildingBlockRainyDay { GeneralBuildingBlock gBBInput = (GeneralBuildingBlock) execution.getVariable("gBBInput"); Map lookupKeyMap = (Map) execution.getVariable("lookupKeyMap"); String serviceType = ASTERISK; + boolean aLaCarte = (boolean) execution.getVariable("aLaCarte"); try { serviceType = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0).getModelInfoServiceInstance().getServiceType(); } catch (Exception ex) { @@ -115,10 +122,13 @@ public class ExecuteBuildingBlockRainyDay { handlingCode = rainyDayHandlerStatus.getSecondaryPolicy(); } } + if(handlingCode.equals("RollbackToAssigned")&&!aLaCarte){ + handlingCode = "Rollback"; + } msoLogger.debug("RainyDayHandler Status Code is: " + handlingCode); execution.setVariable(HANDLING_CODE, handlingCode); } catch (Exception e) { - msoLogger.debug("RainyDayHandler Status Code is: Abort"); + msoLogger.error("Failed to determine RainyDayHandler Status. Seting handlingCode = Abort"); execution.setVariable(HANDLING_CODE, "Abort"); } } diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/BuildingBlock/HomingV2.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/BuildingBlock/HomingV2.bpmn deleted file mode 100644 index 9481ad892e..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/BuildingBlock/HomingV2.bpmn +++ /dev/null @@ -1,194 +0,0 @@ - - - - - SequenceFlow_0gpuwes - - - - SequenceFlow_14dg22y - - - - SequenceFlow_0g3mn4b - - - - SequenceFlow_0g3mn4b - SequenceFlow_14dg22y - - - - - - - - seq - SequenceFlow_1epbfhx - - - - seq - - - - SequenceFlow_1epbfhx - - - - - - - - - - - - - - - sequence_2 - SequenceFlow_0m9c6gt - - - updateExecution - - - - - - - - SequenceFlow_0gpuwes - sequence_2 - - - SequenceFlow_0m9c6gt - updateExecution - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AaiUtilTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AaiUtilTest.groovy deleted file mode 100644 index 1165bbbc71..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AaiUtilTest.groovy +++ /dev/null @@ -1,168 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.bpmn.common.scripts - -import com.github.tomakehurst.wiremock.junit.WireMockRule - -import static org.junit.Assert.*; -import static org.mockito.Mockito.* - -import org.onap.so.rest.HttpHeader -import org.mockito.MockitoAnnotations -import org.mockito.runners.MockitoJUnitRunner -import org.mockito.internal.debugging.MockitoDebuggerImpl -import org.junit.Before -import org.onap.so.bpmn.common.scripts.AaiUtil; -import org.junit.Rule; -import org.junit.Test -import org.junit.rules.ExpectedException -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 - -class AaiUtilTest extends MsoGroovyTest { - - - @Rule - public WireMockRule wireMockRule = new WireMockRule(8090); - - @Rule - public ExpectedException thrown = ExpectedException.none() - - - def aaiPaylod = "\n" + - "\t\t\t\tallottedResourceId\n" + - "\t\t\t\t\n" + - "\t\t\t\tallottedResourceType\n" + - "\t\t\t\tallottedResourceRole\n" + - "\t\t\t\t\n" + - "\t\t\t\t\n" + - "\t\t\t\t\n" + - "\t\t\t\t\n" + - "\t\t\t\tPendingCreate\n" + - "\t\t\t\t\n" + - "\t\t\t\t\n" + - "\t\t\t\t\t\n" + - " \t\t\tservice-instance\n" + - " \t\t\tCSI_resourceLink\n" + - "\t\t\t\t\t\n" + - "\t\t\t\t\n" + - "\t\t\t"; - - @Test - public void testGetVersionDefault() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("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("mso.workflow.default.aai.l3-network.version")).thenReturn('7') - when(mockExecution.getVariable("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("mso.workflow.custom.CreateAAIVfModule.aai.version")).thenReturn('6') - when(mockExecution.getVariable("mso.workflow.default.aai.l3-network.version")).thenReturn('7') - - when(mockExecution.getVariable("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 - public void testGetVersionNotDefined() { - thrown.expect(Exception.class) - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("") - - def version = aaiUtil.getVersion(mockExecution, 'l3-network', 'CreateAAIVfModule') - - } - - @Test - @Ignore - public void testExecuteAAIGetCall() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("aai.auth")).thenReturn("9B2278E8B8E95F256A560719055F4DF3") - when(mockExecution.getVariable("mso.msoKey")).thenReturn("aa3871669d893c7fb8abbcda31b88b4f") - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.executeAAIGetCall(mockExecution,"http://localhost:8090/aai/v9/business/customers/customer/CUST/service-subscriptions/service-subscription/SVC/service-instances/service-instance/NST/allotted-resources/allotted-resource/allottedResourceId") - } - - - @Test - @Ignore - public void testExecuteAAIPutCall() { - ExecutionEntity mockExecution = setupMock('CreateAAIVfModule') - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("aai.auth")).thenReturn("9B2278E8B8E95F256A560719055F4DF3") - when(mockExecution.getVariable("mso.msoKey")).thenReturn("aa3871669d893c7fb8abbcda31b88b4f") - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def uri = aaiUtil.executeAAIPutCall(mockExecution,"http://localhost:8090/aai/v9/business/customers/customer/CUST/service-subscriptions/service-subscription/SVC/service-instances/service-instance/NST/allotted-resources/allotted-resource/allottedResourceId",aaiPaylod) - } - - @Test - public void testGetNamespaceFromUri_twoArguments() { // (execution, uri) - ExecutionEntity mockExecution = setupMock('DeleteVfModuleVolumeInfraV1') - // - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn('10') - when(mockExecution.getVariable("mso.workflow.default.aai.v10.l3-network.uri")).thenReturn('/aai/v10/network/l3-networks/l3-network') - when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') - // - when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') - CreateAAIVfModule myproc = new CreateAAIVfModule() - AaiUtil aaiUtil = new AaiUtil(myproc) - def ns = aaiUtil.getNamespaceFromUri(mockExecution, '/aai/v10/search/generic-query') - assertEquals('http://org.openecomp.aai.inventory/v10', ns) - } -} diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessorTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessorTest.groovy index 459b18b7f1..3c3e4aca91 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessorTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessorTest.groovy @@ -1,22 +1,22 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ package org.onap.so.bpmn.common.scripts @@ -30,7 +30,6 @@ import org.onap.so.bpmn.core.WorkflowException; import static org.junit.Assert.*; import static org.mockito.Mockito.* -import org.onap.so.rest.HttpHeader import org.mockito.MockitoAnnotations import org.mockito.junit.MockitoJUnitRunner; import org.mockito.internal.debugging.MockitoDebuggerImpl diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java index 8fe20de5f0..fc2de4307b 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildlingBlockRainyDayTest.java @@ -20,9 +20,7 @@ package org.onap.so.bpmn.servicedecomposition.tasks; -import static org.hamcrest.CoreMatchers.any; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Matchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; @@ -34,13 +32,13 @@ import org.camunda.bpm.engine.delegate.BpmnError; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.junit.Before; import org.junit.Test; +import org.onap.so.BaseTest; import org.onap.so.bpmn.core.WorkflowException; import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; -import org.onap.so.BaseTest; import org.onap.so.db.catalog.beans.macro.RainyDayHandlerStatus; import org.springframework.beans.factory.annotation.Autowired; @@ -77,7 +75,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { public void setRetryTimerTest() throws Exception{ delegateExecution.setVariable("retryCount", 2); executeBuildingBlockRainyDay.setRetryTimer(delegateExecution); - assertEquals("PT25M",delegateExecution.getVariable("RetryDuration")); + assertEquals("PT40S",delegateExecution.getVariable("RetryDuration")); } @Test @@ -93,7 +91,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { customer.getServiceSubscription().getServiceInstances().add(serviceInstance); serviceInstance.getModelInfoServiceInstance().setServiceType("st1"); vnf.setVnfType("vnft1"); - + delegateExecution.setVariable("aLaCarte", true); RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus(); rainyDayHandlerStatus.setErrorCode("7000"); rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB"); @@ -114,7 +112,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { customer.getServiceSubscription().getServiceInstances().add(serviceInstance); serviceInstance.getModelInfoServiceInstance().setServiceType("st1"); vnf.setVnfType("vnft1"); - + delegateExecution.setVariable("aLaCarte", true); RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus(); rainyDayHandlerStatus.setErrorCode(ASTERISK); rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB"); @@ -136,7 +134,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { customer.getServiceSubscription().getServiceInstances().add(serviceInstance); serviceInstance.getModelInfoServiceInstance().setServiceType("st1"); vnf.setVnfType("vnft1"); - + delegateExecution.setVariable("aLaCarte", true); doReturn(null).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class)); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true); @@ -147,7 +145,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { @Test public void queryRainyDayTableExceptionTest() { doThrow(RuntimeException.class).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep(isA(String.class), isA(String.class), isA(String.class), isA(String.class), isA(String.class)); - + delegateExecution.setVariable("aLaCarte", true); executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true); assertEquals("Abort", delegateExecution.getVariable("handlingCode")); @@ -158,6 +156,7 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { customer.getServiceSubscription().getServiceInstances().add(serviceInstance); serviceInstance.getModelInfoServiceInstance().setServiceType("st1"); vnf.setVnfType("vnft1"); + delegateExecution.setVariable("aLaCarte", true); RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus(); rainyDayHandlerStatus.setErrorCode("7000"); @@ -175,4 +174,50 @@ public class ExecuteBuildlingBlockRainyDayTest extends BaseTest { assertEquals("Abort", delegateExecution.getVariable("handlingCode")); } + @Test + public void queryRainyDayTableRollbackToAssignedMacro() throws Exception{ + customer.getServiceSubscription().getServiceInstances().add(serviceInstance); + serviceInstance.getModelInfoServiceInstance().setServiceType("st1"); + vnf.setVnfType("vnft1"); + delegateExecution.setVariable("aLaCarte", false); + + RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus(); + rainyDayHandlerStatus.setErrorCode("7000"); + rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB"); + rainyDayHandlerStatus.setServiceType("st1"); + rainyDayHandlerStatus.setVnfType("vnft1"); + rainyDayHandlerStatus.setPolicy("RollbackToAssigned"); + rainyDayHandlerStatus.setWorkStep(ASTERISK); + rainyDayHandlerStatus.setSecondaryPolicy("Abort"); + + doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", "st1", "vnft1", "7000", "*"); + + executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true); + + assertEquals("Rollback", delegateExecution.getVariable("handlingCode")); + } + + @Test + public void queryRainyDayTableRollbackToAssignedALaCarte() throws Exception{ + customer.getServiceSubscription().getServiceInstances().add(serviceInstance); + serviceInstance.getModelInfoServiceInstance().setServiceType("st1"); + vnf.setVnfType("vnft1"); + delegateExecution.setVariable("aLaCarte", true); + + RainyDayHandlerStatus rainyDayHandlerStatus = new RainyDayHandlerStatus(); + rainyDayHandlerStatus.setErrorCode("7000"); + rainyDayHandlerStatus.setFlowName("AssignServiceInstanceBB"); + rainyDayHandlerStatus.setServiceType("st1"); + rainyDayHandlerStatus.setVnfType("vnft1"); + rainyDayHandlerStatus.setPolicy("RollbackToAssigned"); + rainyDayHandlerStatus.setWorkStep(ASTERISK); + rainyDayHandlerStatus.setSecondaryPolicy("Abort"); + + doReturn(rainyDayHandlerStatus).when(MOCK_catalogDbClient).getRainyDayHandlerStatusByFlowNameAndServiceTypeAndVnfTypeAndErrorCodeAndWorkStep("AssignServiceInstanceBB", "st1", "vnft1", "7000", "*"); + + executeBuildingBlockRainyDay.queryRainyDayTable(delegateExecution,true); + + assertEquals("RollbackToAssigned", delegateExecution.getVariable("handlingCode")); + } + } diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1Vpn.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1Vpn.json deleted file mode 100644 index f05449a96f..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1Vpn.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "requestInfo" : {"sourceId":"mso","requestType":"create","requestId":"testRequestId","callbackUrl":"http://localhost:28080/mso/WorkflowMesssage/SNIROResponse/testRequestId","transactionId":"testRequestId","timeout":1800}, - "serviceInfo" : {"modelInfo":{"modelName":"testModelName1","modelVersionId":"testModelUUID1","modelVersion":"testModelVersion1","modelInvariantId":"testModelInvariantUUID1"},"serviceInstanceId":"testServiceInstanceId1","serviceName":"testServiceType1"}, - "placementInfo" : {"subscriberInfo":{"subscriberName":"testCustomerName","globalSubscriberId":"testCustomerId"},"placementDemands":[{"resourceModelInfo":{"modelName":"testProxyModelName1","modelVersionId":"testProxyModelUuid1","modelVersion":"testProxyModelVersion1","modelInvariantId":"testProxyModelInvariantUuid1"},"resourceModuleName":"testProxyModelInstanceName1","serviceResourceId":"testProxyId1"},{"resourceModelInfo":{"modelName":"testProxyModelName2","modelVersionId":"testProxyModelUuid2","modelVersion":"testProxyModelVersion2","modelInvariantId":"testProxyModelInvariantUuid2"},"requiredCandidates":[{"candidateType":{"name":"vnfId"},"candidates":["testVnfId"]}],"resourceModuleName":"testProxyModelInstanceName2","serviceResourceId":"testProxyId2"}],"requestParameters":{"aLaCarte":false,"subscriptionServiceType":"iptollfree"}}, - "licenseInfo" : {"licenseDemands":[]} -} \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3AR.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3AR.json deleted file mode 100644 index 6977224ffa..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3AR.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "requestInfo" : {"sourceId":"mso","requestType":"create","requestId":"testRequestId","callbackUrl":"http://localhost:28080/mso/WorkflowMesssage/SNIROResponse/testRequestId","transactionId":"testRequestId","timeout":1800}, - "serviceInfo" : {"modelInfo":{"modelName":"testModelName1","modelVersionId":"testModelUUID1","modelVersion":"testModelVersion1","modelInvariantId":"testModelInvariantUUID1"},"serviceInstanceId":"testServiceInstanceId1","serviceName":"testServiceType1"}, - "placementInfo" : {"subscriberInfo":{"subscriberName":"testCustomerName","globalSubscriberId":"testCustomerId"},"placementDemands":[{"resourceModelInfo":{"modelName":"testAllottedModelName1","modelVersionId":"testAllottedModelUuid1","modelVersion":"testAllottedModelVersion1","modelInvariantId":"testAllottedModelInvariantUuid1"},"resourceModuleName":"testAllottedModelInstanceName1","serviceResourceId":"testAllottedResourceId1"},{"resourceModelInfo":{"modelName":"testAllottedModelName2","modelVersionId":"testAllottedModelUuid2","modelVersion":"testAllottedModelVersion2","modelInvariantId":"testAllottedModelInvariantUuid2"},"resourceModuleName":"testAllottedModelInstanceName2","serviceResourceId":"testAllottedResourceId2"},{"resourceModelInfo":{"modelName":"testAllottedModelName3","modelVersionId":"testAllottedModelUuid3","modelVersion":"testAllottedModelVersion3","modelInvariantId":"testAllottedModelInvariantUuid3"},"resourceModuleName":"testAllottedModelInstanceName3","serviceResourceId":"testAllottedResourceId3"}],"requestParameters":{"aLaCarte":false,"subscriptionServiceType":"iptollfree"}}, - "licenseInfo" : {"licenseDemands":[]} -} \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3Vpn.json b/bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3Vpn.json deleted file mode 100644 index 877c6e7e74..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3Vpn.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "requestInfo" : {"sourceId":"mso","requestType":"create","requestId":"testRequestId","callbackUrl":"http://localhost:28080/mso/WorkflowMesssage/SNIROResponse/testRequestId","transactionId":"testRequestId","timeout":1800}, - "serviceInfo" : {"modelInfo":{"modelName":"testModelName1","modelVersionId":"testModelUUID1","modelVersion":"testModelVersion1","modelInvariantId":"testModelInvariantUUID1"},"serviceInstanceId":"testServiceInstanceId1","serviceName":"testServiceType1"}, - "placementInfo" : {"subscriberInfo":{"subscriberName":"testCustomerName","globalSubscriberId":"testCustomerId"},"placementDemands":[{"resourceModelInfo":{"modelName":"testProxyModelName1","modelVersionId":"testProxyModelUuid1","modelVersion":"testProxyModelVersion1","modelInvariantId":"testProxyModelInvariantUuid1"},"resourceModuleName":"testProxyModelInstanceName1","serviceResourceId":"testProxyId1"},{"resourceModelInfo":{"modelName":"testProxyModelName2","modelVersionId":"testProxyModelUuid2","modelVersion":"testProxyModelVersion2","modelInvariantId":"testProxyModelInvariantUuid2"},"requiredCandidates":[{"candidateType":{"name":"vnfId"},"candidates":["testVnfId"]}],"resourceModuleName":"testProxyModelInstanceName2","serviceResourceId":"testProxyId2"},{"resourceModelInfo":{"modelName":"testProxyModelName1","modelVersionId":"testProxyModelUuid1","modelVersion":"testProxyModelVersion1","modelInvariantId":"testProxyModelInvariantUuid1"},"resourceModuleName":"testProxyModelInstanceName1","serviceResourceId":"testProxyId1"},{"resourceModelInfo":{"modelName":"testProxyModelName2","modelVersionId":"testProxyModelUuid2","modelVersion":"testProxyModelVersion2","modelInvariantId":"testProxyModelInvariantUuid2"},"requiredCandidates":[{"candidateType":{"name":"vnfId"},"candidates":["testVnfId"]}],"resourceModuleName":"testProxyModelInstanceName2","serviceResourceId":"testProxyId2"},{"resourceModelInfo":{"modelName":"testProxyModelName1","modelVersionId":"testProxyModelUuid1","modelVersion":"testProxyModelVersion1","modelInvariantId":"testProxyModelInvariantUuid1"},"resourceModuleName":"testProxyModelInstanceName1","serviceResourceId":"testProxyId1"},{"resourceModelInfo":{"modelName":"testProxyModelName2","modelVersionId":"testProxyModelUuid2","modelVersion":"testProxyModelVersion2","modelInvariantId":"testProxyModelInvariantUuid2"},"requiredCandidates":[{"candidateType":{"name":"vnfId"},"candidates":["testVnfId"]}],"resourceModuleName":"testProxyModelInstanceName2","serviceResourceId":"testProxyId2"}],"requestParameters":{"aLaCarte":false,"subscriptionServiceType":"iptollfree"}}, - "licenseInfo" : {"licenseDemands":[]} -} \ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/resources/application-test.yaml b/bpmn/MSOCommonBPMN/src/test/resources/application-test.yaml index 2985505b46..1651f4f1fc 100644 --- a/bpmn/MSOCommonBPMN/src/test/resources/application-test.yaml +++ b/bpmn/MSOCommonBPMN/src/test/resources/application-test.yaml @@ -108,6 +108,8 @@ mso: db: endpoint: http://localhost:${wiremock.server.port}/ rollback: 'true' + rainyDay: + retryDurationMultiplier: '2' site-name: localDevEnv workflow: default: diff --git a/bpmn/MSORESTClient/pom.xml b/bpmn/MSORESTClient/pom.xml deleted file mode 100644 index a56afb0c0c..0000000000 --- a/bpmn/MSORESTClient/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - 4.0.0 - - - org.onap.so - bpmn - 1.4.0-SNAPSHOT - - - MSORESTClient - - jar - - MSO REST Client API - - - - org.apache.httpcomponents - httpmime - 4.5 - - - org.onap.so - common - ${project.version} - - - - MSORESTClient - - - - - - diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/APIResponse.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/APIResponse.java deleted file mode 100644 index b77c90b215..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/APIResponse.java +++ /dev/null @@ -1,145 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.rest; - -import java.io.IOException; -import java.util.Arrays; - -import org.apache.http.Header; -import org.apache.http.HttpResponse; -import org.apache.http.util.EntityUtils; - -/** - * An immutable class that encapsulates an API response. - * - * @version 1.0 - * @since 1.0 - */ -public class APIResponse { - private final int statusCode; - private final byte[] responseBody; - private final HttpHeader[] headers; - - /** - * Internal method used to create http headers using the specified - * HttpResponse object. - * - * @param httpResponse used to create headers - * @return http headers - */ - private static HttpHeader[] buildHeaders(final HttpResponse httpResponse) { - final Header[] headers = httpResponse.getAllHeaders(); - - HttpHeader[] httpHeaders = new HttpHeader[headers.length]; - for (int i = 0; i < headers.length; ++i) { - final Header header = headers[i]; - final String name = header.getName(); - final String value = header.getValue(); - final HttpHeader httpHeader = new HttpHeader(name, value); - httpHeaders[i] = httpHeader; - } - - return httpHeaders; - } - - /** - * Create an APIResponse object using the specified HttpResponse object. - * - * @param httpResponse used to create the APIResponse - * - * @throws RESTException if unable to read from the HttpResponse object - */ - public APIResponse(final HttpResponse httpResponse) throws RESTException { - try { - this.statusCode = httpResponse.getStatusLine().getStatusCode(); - - if (httpResponse.getEntity() == null) - { - this.responseBody = null; - } - else - { - this.responseBody = EntityUtils.toByteArray(httpResponse.getEntity()); - } - - this.headers = buildHeaders(httpResponse); - } catch (IOException ioe) { - throw new RESTException(ioe); - } - } - - /** - * Gets the http status code returned by the api server. - *

- * For example, status code 200 represents 'OK.' - * - * @return status code - */ - public int getStatusCode() { - return this.statusCode; - } - - /** - * Gets the http response body as a byte array. - * - * @return http response body - */ - public byte[] getResponseBodyAsByteArray() { - // avoid exposing internals, create copy - if (this.responseBody != null) { - return Arrays.copyOf(this.responseBody, this.responseBody.length); - } else { - return null; - } - } - - /** - * Gets the http response body as a string. - * - * @return http response body - */ - public String getResponseBodyAsString() { - if (this.responseBody != null) { - return new String(this.responseBody); - } else { - return ""; - } - } - - /** - * Gets a list of all the headers returned by the API response. - * - * @return an array of all the HttpHeaders - */ - public HttpHeader[] getAllHeaders() { - // avoid exposing internals, create copy - return Arrays.copyOf(this.headers, this.headers.length); - } - - public String getFirstHeader(String name) { - for (HttpHeader header : headers) { - if (header.getName().equals(name)) { - return header.getValue(); - } - } - return null; - } -} diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HostNameVerifier.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HostNameVerifier.java deleted file mode 100644 index 3d10c0391d..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HostNameVerifier.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.rest; - -import javax.net.ssl.SSLException; - -import org.apache.http.conn.ssl.AbstractVerifier; -import org.onap.so.logger.MsoLogger; - -/** - * @version 1.0 - * Place holder to validate host name, for now just invokes the super class method - * - */ -public class HostNameVerifier extends AbstractVerifier { - - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, HostNameVerifier.class); - - public final void verify( - final String host, - final String[] cns, - final String[] subjectAlts) throws SSLException { - try { - verify(host, cns, subjectAlts, true); - } catch (SSLException sex) { - LOGGER.debug("Exception:", sex); - } - } - -} diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HttpHeader.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HttpHeader.java deleted file mode 100644 index a96793334d..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/HttpHeader.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.rest; - -/** - * An immutable class used to wrap an http header. - * - * @version 1.0 - * @since 1.0 - */ -public class HttpHeader { - private final String name; - private final String value; - - /** - * Create an http header using the specified name and value - * - * @param name name of http header - * @param value value of http header - */ - public HttpHeader(final String name, final String value) { - if (name == null) { - throw new IllegalArgumentException("Name may not be null."); - } - - this.name = name; - this.value = value; - } - - /** - * Gets the header name. - * - * @return header name - */ - public String getName() { - return this.name; - } - - /** - * Gets the header value. - * - * @return header value - */ - public String getValue() { - return this.value; - } -} diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTClient.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTClient.java deleted file mode 100644 index c9dd6303bc..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTClient.java +++ /dev/null @@ -1,614 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.rest; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.net.ssl.SSLSocketFactory; - -import org.apache.http.HttpEntity; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPatch; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.AbstractHttpMessage; -import org.apache.http.util.EntityUtils; -import org.onap.so.logger.MsoLogger; -/** - * Client used to send RESTFul requests. - *

- * Many of the methods return a reference to the 'this,' thereby allowing - * method chaining. - *
- * An example of usage can be found below: - *

- * RESTClient client;
- * try {
- *     client = new RESTClient("http://www.openecomp.org");
- *     APIResponse response = client
- *         .setHeader("Accept", "application/json")
- *         .setHeader("Clientid", "clientid")
- *         .setHeader("header", "value")
- *         .httpPost("postbody");
- *     if (response.getStatusCode() == 200) {
- *         System.out.println("Success!");
- *     }
- *  } catch (RESTException re) {
- *      // Handle Exception
- *  }
- * 
- * - * @version 1.0 - * @since 1.0 - */ -public class RESTClient { - - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL,RESTClient.class); - private final String proxyHost; - private final int proxyPort; - - private final String url; - - private final Map> headers; - private final Map> parameters; - - - - private HttpEntity httpEntity; - - /** - * Internal method used to build an APIResponse using the specified - * HttpResponse object. - * - * @param response response wrapped inside an APIResponse object - * @return api response - */ - private APIResponse buildResponse(HttpResponse response) - throws RESTException { - - return new APIResponse(response); - } - - /** - * Used to release any resources used by the connection. - * @param response HttpResponse object used for releasing the connection - * @throws RESTException if unable to release connection - * - */ - private void releaseConnection(HttpResponse response) throws RESTException { - try { - EntityUtils.consume(response.getEntity()); - } catch (IOException ioe) { - throw new RESTException(ioe); - } - } - - /** - * Sets headers to the http message. - * - * @param httpMsg http message to set headers for - */ - private void addInternalHeaders(AbstractHttpMessage httpMsg) { - if (headers.isEmpty()) { - return; - } - - final Set keySet = headers.keySet(); - for (final String key : keySet) { - final List values = headers.get(key); - for (final String value : values) { - httpMsg.addHeader(key, value); - } - } - } - - /** - * Builds the query part of a URL. - * - * @return query - */ - private String buildQuery() { - if (this.parameters.size() == 0) { - return ""; - } - - StringBuilder sb = new StringBuilder(); - String charSet = "UTF-8"; - try { - Iterator keyitr = this.parameters.keySet().iterator(); - for (int i = 0; keyitr.hasNext(); ++i) { - if (i > 0) { - sb.append("&"); - } - - final String name = keyitr.next(); - final List values = this.parameters.get(name); - for(final String value : values) { - sb.append(URLEncoder.encode(name, charSet)); - sb.append("="); - sb.append(URLEncoder.encode(value, charSet)); - } - } - } catch (UnsupportedEncodingException e) { - LOGGER.debug("Exception :", e); - } - return sb.toString(); - } - - /** - * Creates an http client that can be used for sending http requests. - * - * @return created http client - * - * @throws RESTException if unable to create http client. - */ - private CloseableHttpClient createClient() throws RESTException { - HttpClientBuilder clientBuilder; - try { - SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory( - (SSLSocketFactory) SSLSocketFactory.getDefault(), - new HostNameVerifier()); - Registry registry = RegistryBuilder - . create() - .register("http", PlainConnectionSocketFactory.getSocketFactory()) - .register("https", sslSocketFactory).build(); - PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(registry); - clientBuilder = HttpClientBuilder.create().setConnectionManager(manager); - } catch (Exception ex) { - LOGGER.debug("Exception :", ex); - throw new RESTException(ex.getMessage()); - } - clientBuilder.disableRedirectHandling(); - - if ((this.proxyHost != null) && (this.proxyPort != -1)) { - HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort); - clientBuilder.setProxy(proxy); - } - int timeoutInSeconds = 300; - RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(timeoutInSeconds * 1000) - .setConnectionRequestTimeout(timeoutInSeconds * 1000) - .setSocketTimeout(timeoutInSeconds * 1000).build(); - return clientBuilder.setDefaultRequestConfig(requestConfig).build(); - } - - - - - - /** - * Creates a RESTClient with the specified URL, proxy host, and proxy port. - * - * @param url URL to send request to - * @param proxyHost proxy host to use for sending request - * @param proxyPort proxy port to use for sendin request - * - * @throws RESTException if unable to create a RESTClient - */ - public RESTClient(String url, String proxyHost, int proxyPort) { - this(new RESTConfig(url, proxyHost, proxyPort)); - } - - /** - * Creates a RESTClient with the specified URL. No proxy host nor port will - * be used. - * - * @param url URL to send request to - * - * @throws RESTException if unable to create a RESTClient - */ - public RESTClient(String url) { - this(new RESTConfig(url)); - } - - /** - * Creates a RESTClient with the RESTConfig object. - * - * @param restConfig config to use for sending request - * - * @throws RESTException if unable to create a RESTClient - */ - public RESTClient(RESTConfig restConfig) { - this.headers = new LinkedHashMap<>(); - this.parameters = new LinkedHashMap<>(); - this.url = restConfig.getURL(); - this.proxyHost = restConfig.getProxyHost(); - this.proxyPort = restConfig.getProxyPort(); - } - - /** - * Adds parameter to be sent during http request. - *

- * Does not remove any parameters with the same name, thus allowing - * duplicates. - * - * @param name name of parameter - * @param value value of parametr - * @return a reference to 'this', which can be used for method chaining - */ - public RESTClient addParameter(String name, String value) { - if (!parameters.containsKey(name)) { - parameters.put(name, new ArrayList<>()); - } - - List values = parameters.get(name); - values.add(value); - - return this; - } - - /** - * Sets parameter to be sent during http request. - *

- * Removes any parameters with the same name, thus disallowing duplicates. - * - * @param name name of parameter - * @param value value of parametr - * @return a reference to 'this', which can be used for method chaining - */ - public RESTClient setParameter(String name, String value) { - if (parameters.containsKey(name)) { - parameters.get(name).clear(); - } - - addParameter(name, value); - - return this; - } - - /** - * Adds http header to be sent during http request. - *

- * Does not remove any headers with the same name, thus allowing - * duplicates. - * - * @param name name of header - * @param value value of header - * @return a reference to 'this', which can be used for method chaining - */ - public RESTClient addHeader(String name, String value) { - if (!headers.containsKey(name)) { - headers.put(name, new ArrayList<>()); - } - - List values = headers.get(name); - values.add(value); - - return this; - } - - /** - * Sets http header to be sent during http request. - *

- * Does not remove any headers with the same name, thus allowing - * duplicates. - * - * @param name name of header - * @param value value of header - * @return a reference to 'this', which can be used for method chaining - */ - public RESTClient setHeader(String name, String value) { - if (headers.containsKey(name)) { - headers.get(name).clear(); - } - - addHeader(name, value); - - return this; - } - - /** - * Convenience method for adding the authorization header using the - * specified OAuthToken object. - * - * @param token token to use for setting authorization - * @return a reference to 'this,' which can be used for method chaining - */ - public RESTClient addAuthorizationHeader(String token) { - this.addHeader("Authorization", token); - return this; - } - - /** - * Sends an http GET request using the parameters and headers previously - * set. - * - * @return api response - * - * @throws RESTException if request was unsuccessful - */ - public APIResponse httpGet() throws RESTException { - HttpResponse response = null; - - try (CloseableHttpClient httpClient = createClient()) { - String query = ""; - if (!buildQuery().equals("")) { - query = "?" + buildQuery(); - } - HttpGet httpGet = new HttpGet(this.getURL() + query); - addInternalHeaders(httpGet); - - LOGGER.debug("Executing GET to url: " + this.getURL() + query); - - response = httpClient.execute(httpGet); - - return buildResponse(response); - } catch (IOException ioe) { - throw new RESTException(ioe); - } finally { - if (response != null) { - this.releaseConnection(response); - } - } - } - - /** - * Alias for httpPost() - * - * @see RESTClient#httpPost() - */ - public APIResponse post() throws RESTException { - return httpPost(); - } - - /** - * Sends an http POST request. - *

- * POST body will be set to the values set using add/setParameter() - * - * @return api response - * - * @throws RESTException if POST was unsuccessful - */ - public APIResponse httpPost() throws RESTException { - return httpPost(buildQuery()); - } - - /** - * Sends an http POST request using the specified body. - * - * @return api response - * - * @throws RESTException if POST was unsuccessful - */ - public APIResponse httpPost(String body) throws RESTException { - HttpResponse response = null; - try (CloseableHttpClient httpClient = createClient()) { - HttpPost httpPost = new HttpPost(this.getURL()); - addInternalHeaders(httpPost); - if (body != null && !body.equals("")) { - httpEntity = new StringEntity(body); - httpPost.setEntity(new StringEntity(body)); - } - LOGGER.debug("Executing POST to url: " + this.getURL()); - - response = httpClient.execute(httpPost); - - return buildResponse(response); - - } catch (IOException e) { - throw new RESTException(e); - } finally { - if (response != null) { - this.releaseConnection(response); - } - } - } - - /** - * - * @param body Data to PUT - * @return API response - * @throws RESTException - */ - public APIResponse httpPut(String body) throws RESTException { - HttpResponse response = null; - try (CloseableHttpClient httpClient = createClient()) { - - String query = ""; - if (!buildQuery().equals("")) { - query = "?" + buildQuery(); - } - HttpPut httpPut = new HttpPut(this.getURL() + query); - addInternalHeaders(httpPut); - if (body != null && !body.equals("")) { - httpEntity = new StringEntity(body); - httpPut.setEntity(httpEntity); - } - LOGGER.debug("Executing PUT to url: " + this.getURL() + query); - - response = httpClient.execute(httpPut); - - return buildResponse(response); - } catch (IOException e) { - throw new RESTException(e); - } finally { - if (response != null) { - this.releaseConnection(response); - } - } - } - - /** - * Alias for httpPatch(). - * - * @see RESTClient#httpPatch() - */ - public APIResponse patch(String body) throws RESTException { - return httpPatch(body); - } - - /** - * - * @param body Data to PATCH - * @return API response - * @throws RESTException - */ - public APIResponse httpPatch(String body) throws RESTException { - HttpResponse response = null; - try (CloseableHttpClient httpClient = createClient()) { - String query = ""; - if (!buildQuery().equals("")) { - query = "?" + buildQuery(); - } - HttpPatch httpPatch = new HttpPatch(this.getURL() + query); - addInternalHeaders(httpPatch); - if (body != null && !body.equals("")) { - httpEntity = new StringEntity(body); - httpPatch.setEntity(httpEntity); - } - LOGGER.debug("Executing PATCH to url: " + this.getURL() + query); - - response = httpClient.execute(httpPatch); - - return buildResponse(response); - } catch (IOException e) { - throw new RESTException(e); - } finally { - if (response != null) { - this.releaseConnection(response); - } - } - } - - /** - * Alias for httpDelete(). - * - * @see RESTClient#httpDelete() - */ - public APIResponse delete() throws RESTException { - return httpDelete(); - } - - /** - * Sends an http DELETE request using the parameters and headers previously - * set. - * - * @return api response - * - * @throws RESTException if request was unsuccessful - */ - public APIResponse httpDelete() throws RESTException { - return httpDelete(null); - } - - /** - * Sends an http DELETE request with a body, using the parameters and headers - * previously set. - * - * @return api response - * - * @throws RESTException if request was unsuccessful - */ - public APIResponse httpDelete(String body) throws RESTException { - HttpResponse response = null; - - try (CloseableHttpClient httpClient = createClient()){ - - String query = ""; - if (!buildQuery().equals("")) { - query = "?" + buildQuery(); - } - HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(this.getURL() + query); - addInternalHeaders(httpDelete); - - if (body != null && !body.equals("")) { - httpEntity = new StringEntity(body); - httpDelete.setEntity(httpEntity); - } - - LOGGER.debug("Executing DELETE to url: " + this.getURL() + query); - - response = httpClient.execute(httpDelete); - - return buildResponse(response); - } catch (IOException ioe) { - throw new RESTException(ioe); - } finally { - if (response != null) { - this.releaseConnection(response); - } - } - } - - public String getURL() { - return url; - } - public Map> getHeaders() { - return headers; - } - public Map> getParameters() { - return parameters; - } - public HttpEntity getHttpEntity() { - return httpEntity; - } - - - /** - * Allows inclusion of a request body with DELETE. - */ - private class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { - public static final String METHOD_NAME = "DELETE"; - - @Override - public String getMethod() { - return METHOD_NAME; - } - - public HttpDeleteWithBody(final String uri) { - super(); - setURI(URI.create(uri)); - } - - public HttpDeleteWithBody(final URI uri) { - super(); - setURI(uri); - } - - public HttpDeleteWithBody() { - super(); - } - } -} diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTConfig.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTConfig.java deleted file mode 100644 index b5fecbdb87..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTConfig.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.rest; - -/** - * Configuration values to be used by the RESTClient. - * - * @version 1.0 - * - */ -public class RESTConfig { - private final String URL; - - private final boolean trustAllCerts; - private final String proxyHost; - private final int proxyPort; - - /** - * Creates a RESTConfig with the specified URL. - *

- * By default, no proxy will be used, and only valid certificates will - * be used. - * - * @param URL url to set - */ - public RESTConfig(final String URL) { - this(URL, null, -1, false); - } - - /** - * Creates a RESTConfig with the specified URL and whether to trust all - * certificates. - *

- * Trusting all certificates is useful for testing self-signed - * certificates. By default, no proxy will be used. - * - * @param URL url to set - * @param trustAllCerts whether to trust all certificates - */ - public RESTConfig(final String URL, final boolean trustAllCerts) { - this(URL, null, -1, trustAllCerts); - } - - /** - * Creates a RESTConfig with the specified URL and proxy. - *

- * By default, only valid certificates will be allowed. - * - * @param URL url to set - * @param proxyHost proxy host to set - * @param proxyPort proxy port to set - */ - public RESTConfig(final String URL, final String proxyHost, - final int proxyPort) { - - this(URL, proxyHost, proxyPort, false); - } - - /** - * Creates a RESTConfig object with the specified URL, proxy host, proxy - * port, and whether to trust all certificates. Allowing all certificates - * is useful for testing self-signed certificates. - * - * @param URL url to set - * @param proxyHost proxy host to set - * @param proxyPort porxy port to set - * @param trustAllCerts whether to trust all certificates - */ - public RESTConfig(final String URL, final String proxyHost, - final int proxyPort, boolean trustAllCerts) { - - this.URL = URL; - this.proxyHost = proxyHost; - this.proxyPort = proxyPort; - this.trustAllCerts = trustAllCerts; - } - - /** - * Gets the URL to use. - * - * @return URL to use - */ - public String getURL() { - return this.URL; - } - - /** - * Gets whether to trust all certificates. - * - * @return true if to trust all certificates, false otherwise - */ - public boolean trustAllCerts() { - return this.trustAllCerts; - } - - /** - * Gets proxy host or null if proxy host has not been set. - * - * @return proxy host - */ - public String getProxyHost() { - return this.proxyHost; - } - - /** - * Gets proxy port or -1 if no proxy port has been set. - * - * @return proxy port - */ - public int getProxyPort() { - return this.proxyPort; - } -} diff --git a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTException.java b/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTException.java deleted file mode 100644 index 579927c2ce..0000000000 --- a/bpmn/MSORESTClient/src/main/java/org/onap/so/rest/RESTException.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.rest; - -/** - * A custom exception class. - * - * @version 1.0 - * - */ -public class RESTException extends Exception { - private static final long serialVersionUID = -6874042744590915838L; - // http status code - private final int statusCode; - - // error message - private final String errorMessage; - - /** - * {@inheritDoc} - * @see Exception#RESTException(String) - */ - public RESTException(final String errorMessage) { - this(-1, errorMessage); - } - - /** - * {@inheritDoc} - * @see Exception#RESTException(Throwable) - */ - public RESTException(final Throwable cause) { - super(cause); - this.statusCode = -1; - this.errorMessage = cause.getMessage(); - } - - /** - * Creates a RESTException with the specified status code and error - * message. - * - * @param statusCode http status code - * @param errorMessage http error message - */ - public RESTException(final int statusCode, final String errorMessage) { - super(statusCode + ":" + errorMessage); - this.statusCode = statusCode; - this.errorMessage = errorMessage; - } - - /** - * Gets the status code or -1 if none has been set. - * - * @return status code - */ - public int getStatusCode() { - return this.statusCode; - } - - /** - * Gets the error message. - * - * @return error message - */ - public String getErrorMessage() { - return this.errorMessage; - } -} diff --git a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/APIResponseTest.java b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/APIResponseTest.java deleted file mode 100644 index 2c81fda32b..0000000000 --- a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/APIResponseTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= -*/ - -package org.onap.so.rest; - -import static org.junit.Assert.assertEquals; - -import org.json.JSONObject; -import org.junit.Test; - -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolVersion; -import org.apache.http.HttpEntity; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.message.BasicHttpResponse; - -public class APIResponseTest { - - @Test - public void test() throws Exception { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("firstName", "firstName1"); - jsonObject.put("lastName", "lastName1"); - String jsonObjectAsString= jsonObject.toString(); - HttpEntity entity = new StringEntity(jsonObjectAsString, ContentType.APPLICATION_JSON); - ProtocolVersion ver = new ProtocolVersion("HTTP", 1, 1); - HttpResponse response = new BasicHttpResponse(ver, 1, "Ok"); - response.setStatusLine(ver, 200); - response.setEntity(entity); - response.setHeader("name", "value"); - response.setStatusCode(200); - APIResponse apiResponse = new APIResponse(response); - assertEquals(200, apiResponse.getStatusCode()); - assertEquals(jsonObject.toString(), apiResponse.getResponseBodyAsString()); - assertEquals("value", apiResponse.getFirstHeader("name")); - assertEquals(1, apiResponse.getAllHeaders().length); - assertEquals(49, apiResponse.getResponseBodyAsByteArray().length); - } -} diff --git a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/HttpHeaderTest.java b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/HttpHeaderTest.java deleted file mode 100644 index bc096687b7..0000000000 --- a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/HttpHeaderTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= -*/ - -package org.onap.so.rest; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class HttpHeaderTest { - - @Test - public void test() { - HttpHeader hth= new HttpHeader("name", "value"); - assertEquals("name", hth.getName()); - assertEquals("value", hth.getValue()); - } - - @Test (expected = IllegalArgumentException.class) - public void testException() { - HttpHeader httpHeader = new HttpHeader(null, "value"); //null - } -} diff --git a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTClientTest.java b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTClientTest.java deleted file mode 100644 index a79f0aa536..0000000000 --- a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTClientTest.java +++ /dev/null @@ -1,184 +0,0 @@ -/* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= -*/ - -package org.onap.so.rest; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.patch; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.put; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; -import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.spy; - -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.springframework.http.HttpStatus; - -import com.github.tomakehurst.wiremock.junit.WireMockRule; - -public class RESTClientTest { - - private RESTClient restClient; - private JSONObject jsonPayload; - private JSONObject jsonResponse; - private String jsonObjectAsString; - private String jsonResponseAsString; - - @Rule - public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort()); - - - @Before - public void before() throws Exception { - jsonPayload = new JSONObject(); - jsonPayload.put("firstName", "firstName1"); - jsonPayload.put("lastName", "lastName1"); - jsonObjectAsString = jsonPayload.toString(); - jsonResponse = new JSONObject(); - jsonResponse.put("response", "responseValue"); - jsonResponseAsString = jsonResponse.toString(); - restClient = new RESTClient("http://localhost:" + wireMockRule.port() + "/example", "localhost", wireMockRule.port()); - } - - @Test - public void testHeadersParameters() throws Exception { - restClient.setHeader("name", "value"); - restClient.setParameter("name", "value"); - assertEquals("[value]", restClient.getParameters().get("name").toString()); - assertEquals("[value]", restClient.getHeaders().get("name").toString()); - restClient.setHeader("name", "value2"); - assertEquals("[value2]", restClient.getHeaders().get("name").toString()); - restClient.setParameter("name", "value2"); - assertEquals("[value2]", restClient.getParameters().get("name").toString()); - restClient.addParameter("name", "value"); - assertEquals(1, restClient.getParameters().size()); - restClient.addAuthorizationHeader("token"); - assertEquals("[token]", restClient.getHeaders().get("Authorization").toString()); - assertEquals("http://localhost:" + wireMockRule.port() + "/example", restClient.getURL()); - restClient = new RESTClient("http://localhost:" + wireMockRule.port() + "/example1"); - assertEquals("http://localhost:" + wireMockRule.port() + "/example1", restClient.getURL()); - } - - @Test - public void testHttpPost() throws Exception { - RESTClient restClientMock = mock(RESTClient.class); - restClientMock = spy(restClient); - wireMockRule.stubFor(post(urlPathMatching("/example/*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); - APIResponse apiResponse = restClientMock.httpPost(jsonObjectAsString); - assertEquals(200, apiResponse.getStatusCode()); - assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); - assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); - verify(restClientMock, times(2)).getURL(); - } - - @Test - public void testPost() throws Exception { - wireMockRule.stubFor(post(urlPathMatching("/example/*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); - APIResponse apiResponse = restClient.post(); - assertEquals(200, apiResponse.getStatusCode()); - assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); - assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); - } - - @Test - public void testHttpPut() throws Exception { - wireMockRule.stubFor(put(urlPathMatching("/example/*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); - restClient.setParameter("name", "value"); - APIResponse apiResponse = restClient.httpPut(jsonObjectAsString); - assertEquals(200, apiResponse.getStatusCode()); - assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); - assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); - - } - - @Test - public void testHttpPatch() throws Exception { - wireMockRule.stubFor(patch(urlPathMatching("/example/*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); - APIResponse apiResponse = restClient.httpPatch(jsonObjectAsString); - assertEquals(200, apiResponse.getStatusCode()); - assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); - assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); - } - - @Test - public void testPatch_withParameter() throws Exception { - wireMockRule.stubFor(patch(urlPathMatching("/example/*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); - restClient.setParameter("name", "value"); - APIResponse apiResponse = restClient.patch(jsonObjectAsString); - assertEquals(200, apiResponse.getStatusCode()); - assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); - assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); - } - - @Test - public void testHttpDelete_withPayload() throws Exception { - wireMockRule.stubFor(delete(urlPathMatching("/example/*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); - APIResponse apiResponse = restClient.httpDelete(jsonObjectAsString); - assertEquals(200, apiResponse.getStatusCode()); - assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); - assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); - } - - @Test - public void testHttpDelete() throws Exception { - wireMockRule.stubFor(delete(urlPathMatching("/example/*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); - APIResponse apiResponse = restClient.httpDelete(); - assertEquals(200, apiResponse.getStatusCode()); - assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); - assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); - } - - @Test - public void testDelete() throws Exception { - wireMockRule.stubFor(delete(urlPathMatching("/example/*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); - APIResponse apiResponse = restClient.delete(); - assertEquals(200, apiResponse.getStatusCode()); - assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); - assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); - } - - @Test - public void testHttpGet() throws Exception { - wireMockRule.stubFor(get(urlPathMatching("/example/*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.OK.value()).withBody(jsonResponseAsString))); - APIResponse apiResponse = restClient.httpGet(); - assertEquals(200, apiResponse.getStatusCode()); - assertEquals(jsonResponseAsString, apiResponse.getResponseBodyAsString()); - assertEquals("application/json", apiResponse.getFirstHeader("Content-Type")); - } - -} diff --git a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTConfigTest.java b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTConfigTest.java deleted file mode 100644 index 82c3c37be0..0000000000 --- a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTConfigTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= -*/ - -package org.onap.so.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import org.junit.Test; - -public class RESTConfigTest { - - @Test - public void test() { - RESTConfig rcfg=mock(RESTConfig.class); - RESTConfig rcf=new RESTConfig("URL"); - RESTConfig rcfi=new RESTConfig("URL", true); - RESTConfig rcfo=new RESTConfig("URL", "10.2.3.101", 5020); - RESTConfig rcfn=new RESTConfig("URL", "10.2.3.101", 5020, true); - assert(rcfo.getProxyHost().equals("10.2.3.101")); - assertEquals(5020,rcfn.getProxyPort()); - assert(rcf.getURL().equals("URL")); - assertTrue(rcfn.trustAllCerts()); - } -} diff --git a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTExceptionTest.java b/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTExceptionTest.java deleted file mode 100644 index 19339a187d..0000000000 --- a/bpmn/MSORESTClient/src/test/java/org/onap/so/rest/RESTExceptionTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= -*/ - -package org.onap.so.rest; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import org.junit.Test; - -public class RESTExceptionTest { - - @Test - public void test() { - RESTException rexm=mock(RESTException.class); - RESTException rex=new RESTException("Error"); - RESTException recpt=new RESTException(200, "Error"); - assert(rex.getErrorMessage().equals("Error")); - assertEquals(200,recpt.getStatusCode()); - Throwable throwable = mock(Throwable.class); - RESTException restException = new RESTException(throwable); - assertEquals(-1, restException.getStatusCode()); - } -} diff --git a/bpmn/mso-infrastructure-bpmn/pom.xml b/bpmn/mso-infrastructure-bpmn/pom.xml index 9f5dabe2f2..e3d611275e 100644 --- a/bpmn/mso-infrastructure-bpmn/pom.xml +++ b/bpmn/mso-infrastructure-bpmn/pom.xml @@ -218,7 +218,7 @@ org.camunda.bpm.extension camunda-bpm-assert - 1.2 + 2.0-alpha2 test diff --git a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java index 489b1a5761..6c174ae537 100644 --- a/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java +++ b/bpmn/mso-infrastructure-bpmn/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CreateAndActivatePnfResourceTest.java @@ -20,7 +20,7 @@ package org.onap.so.bpmn.infrastructure.pnf.delegate; -import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.assertThat; +import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat; import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.CORRELATION_ID; import java.util.HashMap; diff --git a/bpmn/pom.xml b/bpmn/pom.xml index 690440d0fe..a7b49bc52a 100644 --- a/bpmn/pom.xml +++ b/bpmn/pom.xml @@ -28,7 +28,7 @@ MSOCoreBPMN - MSORESTClient + MSOCommonBPMN so-bpmn-infrastructure-common so-bpmn-tasks diff --git a/bpmn/so-bpmn-building-blocks/pom.xml b/bpmn/so-bpmn-building-blocks/pom.xml index 9f1171c7f4..8f1f2bf56e 100644 --- a/bpmn/so-bpmn-building-blocks/pom.xml +++ b/bpmn/so-bpmn-building-blocks/pom.xml @@ -103,7 +103,7 @@ org.camunda.bpm.extension camunda-bpm-assert - 1.2 + 2.0-alpha2 test diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AssignVnfBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AssignVnfBB.bpmn index d2c7f17b19..0991ab5c36 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AssignVnfBB.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AssignVnfBB.bpmn @@ -1,5 +1,5 @@ - + SequenceFlow_0zaz9o2 @@ -38,7 +38,6 @@ - SequenceFlow_1uiok7v SequenceFlow_0v8d14a diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/HomingBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/HomingBB.bpmn index 344b7d8761..1fdf2f3c66 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/HomingBB.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/HomingBB.bpmn @@ -1,72 +1,48 @@ - + - + SequenceFlow_1x9usa6 - - SequenceFlow_1x9usa6 - SequenceFlow_0lc15i7 - import org.onap.so.bpmn.common.scripts.* -if(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")).getVariable("homingService") == "oof"){ - OofHoming oofHoming = new OofHoming() - oofHoming.callOof(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution"))) -}else{ - SniroHomingV2 sniroHoming = new SniroHomingV2() - SniroHoming.callSniro(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution"))) -} - - + - + SequenceFlow_1rf4vs8 - + SequenceFlow_00nlh7l SequenceFlow_00nlh7l SequenceFlow_1rf4vs8 - import org.onap.so.bpmn.common.scripts.* + +ex.processSubflowsBPMNException(execution)]]> - - + + SequenceFlow_0kamg53 SequenceFlow_1o7154s - import org.onap.so.bpmn.common.scripts.* + +ex.processJavaException(execution)]]> - + SequenceFlow_0kamg53 - + SequenceFlow_1o7154s - - + + - - SequenceFlow_1fipbmk - SequenceFlow_01apjvo - import org.onap.so.bpmn.common.scripts.* -if(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")).getVariable("homingService") == "oof"){ - OofHoming oofHoming = new OofHoming() - oofHoming.processHomingSolution(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution"))) -}else{ - SniroHomingV2 sniroHoming = new SniroHomingV2 () - sniroHoming.processSolution(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")), asyncResponse) -} - @@ -74,135 +50,280 @@ if(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecu - + - SequenceFlow_0lc15i7 + SequenceFlow_1qbnm82 SequenceFlow_1fipbmk - - - - SequenceFlow_01apjvo + + + + SequenceFlow_1urt5i6 - + + + + + + + + + + + + + + + SequenceFlow_1dtador + SequenceFlow_0lc15i7 + + + SequenceFlow_08k112s + SequenceFlow_01apjvo + + + SequenceFlow_0m6nhqg + SequenceFlow_0kvax6n + + + SequenceFlow_0oixz4g + SequenceFlow_0ph4paa + + + SequenceFlow_1x9usa6 + SequenceFlow_1dtador + SequenceFlow_0m6nhqg + + + SequenceFlow_0lc15i7 + SequenceFlow_0kvax6n + SequenceFlow_1qbnm82 + + + SequenceFlow_1fipbmk + SequenceFlow_08k112s + SequenceFlow_0oixz4g + + + SequenceFlow_01apjvo + SequenceFlow_0ph4paa + SequenceFlow_1urt5i6 + - - - - - - + + + + + + - - + + - + - + - + - - + + - + - - + + - + - + - + - - + + - + - - + + - + - - + + - + - - - - + + + + - + - - + + - + - - + + - + - - - - + - - + + - + - - + + + - + - - + + - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/SDNCHandler.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/SDNCHandler.bpmn new file mode 100644 index 0000000000..d123153932 --- /dev/null +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/SDNCHandler.bpmn @@ -0,0 +1,259 @@ + + + + + SequenceFlow_1n0j3hz + + + SequenceFlow_0i4u8g4 + SequenceFlow_0puiqga + + + SequenceFlow_0flbj8a + SequenceFlow_07vnhri + + + SequenceFlow_0valp88 + + + + + SequenceFlow_0rh24pq + SequenceFlow_0yve6l6 + SequenceFlow_1ecej8g + + SequenceFlow_1qxm8ot + SequenceFlow_05eggbt + + + + SequenceFlow_1qxm8ot + + + SequenceFlow_0oh3ye4 + + + + + + SequenceFlow_05eggbt + SequenceFlow_0oh3ye4 + + + + SequenceFlow_1yifu46 + + + + + + + SequenceFlow_1ecej8g + SequenceFlow_0rh24pq + SequenceFlow_0i4u8g4 + + + + + + + + SequenceFlow_07vnhri + SequenceFlow_0yve6l6 + SequenceFlow_0puiqga + + + + + + + + + + SequenceFlow_1n0j3hz + SequenceFlow_0flbj8a + + + SequenceFlow_1yifu46 + + + SequenceFlow_0valp88 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/WorkflowActionBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/WorkflowActionBB.bpmn index 8cda1d7c7b..d4330290ea 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/WorkflowActionBB.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/WorkflowActionBB.bpmn @@ -17,6 +17,7 @@ + SequenceFlow_0mew9im SequenceFlow_07h9d4y @@ -98,7 +99,7 @@ - + @@ -562,4 +563,4 @@ - + \ No newline at end of file diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java index f5fc8b091c..f9ff28a023 100644 --- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java +++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/BaseBPMNTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -34,6 +34,7 @@ import org.junit.After; import org.junit.Before; import org.junit.runner.RunWith; import org.onap.so.TestApplication; +import org.onap.so.bpmn.buildingblock.SniroHomingV2; import org.onap.so.bpmn.common.DelegateExecutionImpl; import org.onap.so.bpmn.common.validation.BuildingBlockValidatorRunner; import org.onap.so.bpmn.infrastructure.aai.tasks.AAICommonTasks; @@ -72,6 +73,7 @@ import org.onap.so.bpmn.sdno.tasks.SDNOHealthCheckTasks; import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetup; import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils; import org.onap.so.bpmn.servicedecomposition.tasks.ExecuteBuildingBlockRainyDay; +import org.onap.so.client.sdnc.SDNCClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.web.server.LocalServerPort; @@ -91,9 +93,9 @@ public abstract class BaseBPMNTest { @Autowired private RepositoryService repositoryService; - + protected Map variables = new HashMap<>(); - + protected List mockedSubprocessList = new ArrayList<>(); protected TestRestTemplate restTemplate = new TestRestTemplate(); @@ -111,11 +113,11 @@ public abstract class BaseBPMNTest { @MockBean protected AAIDeleteTasks aaiDeleteTasks; - + @MockBean protected AAIFlagTasks aaiFlagTasks; - - + + @MockBean protected AppcRunTasks appcRunTasks; @@ -154,7 +156,7 @@ public abstract class BaseBPMNTest { @MockBean protected AssignNetworkBBUtils assignNetworkBBUtils; - + @MockBean protected AssignNetwork assignNetwork; @@ -181,37 +183,43 @@ public abstract class BaseBPMNTest { @MockBean protected OrchestrationStatusValidator orchestrationStatusValidator; - + @MockBean protected BBInputSetup bbInputSetup; - + @MockBean protected BBInputSetupUtils bbInputSetupUtils; - + @MockBean protected ExecuteBuildingBlockRainyDay executeBuildingBlockRainyDay; - + @MockBean protected WorkflowAction workflowAction; @MockBean protected WorkflowActionBBTasks workflowActionBBTasks; - + @MockBean protected GenericVnfHealthCheck genericVnfHealthCheck; - + @MockBean protected ConfigurationScaleOut configurationScaleOut; - + @MockBean protected FlowCompletionTasks flowCompletionTasks; - + @MockBean protected BuildingBlockValidatorRunner buildingBlockValidatorRunner; - + @MockBean protected SDNOHealthCheckTasks sdnoHealthCheckTasks; - + + @MockBean + protected SDNCClient sdncClient; + + @MockBean + protected SniroHomingV2 sniroHoming; + @LocalServerPort protected int port; @@ -223,7 +231,7 @@ public abstract class BaseBPMNTest { public void baseBefore() { variables.put("gBuildingBlockExecution", new DelegateExecutionImpl(new HashMap<>())); } - + @After public void baseAfter() { for (String deploymentId : mockedSubprocessList) { @@ -231,7 +239,7 @@ public abstract class BaseBPMNTest { } mockedSubprocessList.clear(); } - + /** * Create and deploy a process model with one logger delegate as service task. * @@ -268,7 +276,7 @@ public abstract class BaseBPMNTest { for (String key : outParam.keySet()) { builder.camundaOutputParameter(key, outParam.get(key)); } - + BpmnModelInstance modelInstance = builder.endEvent().name("End_Event").done(); mockedSubprocessList.add(repositoryService.createDeployment().addModelInstance(fileName + ".bpmn", modelInstance).deploy().getId()); } diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/buildingblock/SniroHomingV2BBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/buildingblock/SniroHomingV2BBTest.java deleted file mode 100644 index a90d309630..0000000000 --- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/buildingblock/SniroHomingV2BBTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.bpmn.buildingblock; - -import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doThrow; - -import org.camunda.bpm.engine.delegate.BpmnError; -import org.camunda.bpm.engine.runtime.ProcessInstance; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.so.bpmn.BaseBPMNTest; -import org.onap.so.bpmn.common.BuildingBlockExecution; -import org.springframework.boot.test.mock.mockito.MockBean; - - - //these test run locally but fail when ran in conjunction with others in jenkins -@Ignore -public class SniroHomingV2BBTest extends BaseBPMNTest{ - - @MockBean - protected SniroHomingV2 sniroHoming; - - @Test - public void testHomingV2_success(){ - mockSubprocess("ReceiveWorkflowMessage", "Mock ReceiveWorkflowMessage", "GenericStub"); - ProcessInstance pi = runtimeService.startProcessInstanceByKey("HomingV2", variables); - assertThat(pi).isNotNull(); - assertThat(pi).isStarted().hasPassedInOrder("start", "callSniro", "callReceiveAsync", "processSolution", "end"); - assertThat(pi).isEnded(); - } - - @Test - public void testHomingV2_error_bpmnError(){ - doThrow(new BpmnError("MSOWorkflowException")).when(sniroHoming).callSniro(any(BuildingBlockExecution.class)); - ProcessInstance pi = runtimeService.startProcessInstanceByKey("HomingV2", variables); - assertThat(pi).isNotNull(); - assertThat(pi).isStarted() - .hasPassedInOrder("start", "catchBpmnError", "processBpmnError", "endBpmnError") - .hasNotPassed("callReceiveAsync"); - assertThat(pi).isEnded(); - } - - @Test - public void testHomingV2_error_javaException(){ - doThrow(new RuntimeException("Test")).when(sniroHoming).callSniro(any(BuildingBlockExecution.class)); - ProcessInstance pi = runtimeService.startProcessInstanceByKey("HomingV2", variables); - assertThat(pi).isNotNull(); - assertThat(pi).isStarted() - .hasPassedInOrder("start", "catchJavaException", "processJavaException", "endJavaException") - .hasNotPassed("callReceiveAsync"); - assertThat(pi).isEnded(); - } - -} diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/HomingBBTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/HomingBBTest.java new file mode 100644 index 0000000000..0dde361b7e --- /dev/null +++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/HomingBBTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.bpmn.subprocess; + +import static org.camunda.bpm.engine.test.assertions.ProcessEngineAssertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; + +import org.camunda.bpm.engine.delegate.BpmnError; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.so.bpmn.BaseBPMNTest; +import org.onap.so.bpmn.buildingblock.SniroHomingV2; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.springframework.boot.test.mock.mockito.MockBean; + + +public class HomingBBTest extends BaseBPMNTest{ + + @Test + public void testHomingV2_success(){ + mockSubprocess("ReceiveWorkflowMessage", "Mock ReceiveWorkflowMessage", "GenericStub"); + ProcessInstance pi = runtimeService.startProcessInstanceByKey("HomingBB", variables); + assertThat(pi).isNotNull(); + assertThat(pi).isStarted().hasPassedInOrder("start", "sniroOofCheck", "callSniro", "ExclusiveGateway_1ckp059", "receiveAsyncCallback", "sniroOofCheck2", "processSniroSolution", "ExclusiveGateway_1kvzxpb", "end"); + assertThat(pi).isEnded(); + } + + @Test + public void testHomingV2_error_bpmnError(){ + doThrow(new BpmnError("MSOWorkflowException")).when(sniroHoming).callSniro(any(BuildingBlockExecution.class)); + ProcessInstance pi = runtimeService.startProcessInstanceByKey("HomingBB", variables); + assertThat(pi).isNotNull(); + assertThat(pi).isStarted() + .hasPassedInOrder("start", "sniroOofCheck", "startBpmnError", "bpmnErrorSubprocess", "processMsoWorkflowException", "endBpmnError") + .hasNotPassed("callReceiveAsync"); + assertThat(pi).isEnded(); + } + +} diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/SDNCHandlerTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/SDNCHandlerTest.java new file mode 100644 index 0000000000..ad9f97f951 --- /dev/null +++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/SDNCHandlerTest.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.bpmn.subprocess; + +import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat; +import static org.mockito.Mockito.doReturn; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.junit.Test; +import org.onap.sdnc.northbound.client.model.GenericResourceApiServiceOperationInformation; +import org.onap.so.bpmn.BaseBPMNTest; +import org.onap.so.client.exception.BadResponseException; +import org.onap.so.client.exception.MapperException; +import org.onap.so.client.sdnc.beans.SDNCRequest; +import org.onap.so.client.sdnc.endpoint.SDNCTopology; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class SDNCHandlerTest extends BaseBPMNTest{ + @Test + public void sunnyDay_SDNCHandler_Sync_Final_Test() throws InterruptedException, MapperException, BadResponseException, IOException { + final String sdncResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/SDNCClientPut200Response.json"))); + doReturn(sdncResponse).when(sdncClient).post(createSDNCRequest().getSDNCPayload(),SDNCTopology.CONFIGURATION); + Map startVariables = new HashMap<>(); + startVariables.put("SDNCRequest", createSDNCRequest()); + ProcessInstance pi = runtimeService.startProcessInstanceByKey("SDNCHandler", startVariables); + assertThat(pi).isNotNull().isStarted().hasPassedInOrder("SDNC_Start","SNDC_SetupCallback","Call_SDNC","isAsync_Gateway","SDNC_End").isEnded(); + } + + + public SDNCRequest createSDNCRequest(){ + SDNCRequest request = new SDNCRequest(); + request.setCorrelationName("correlationName"); + request.setCorrelationValue("correlationValue"); + request.setTopology(SDNCTopology.CONFIGURATION); + ObjectMapper mapper = new ObjectMapper(); + try { + GenericResourceApiServiceOperationInformation sdncReq = + mapper.readValue(Files.readAllBytes(Paths.get("src/test/resources/SDNC_Client_Request.json")), GenericResourceApiServiceOperationInformation.class); + request.setSDNCPayload(sdncReq); + } catch (JsonParseException e) { + + } catch (JsonMappingException e) { + + } catch (IOException e) { + + } + + return request; + } +} diff --git a/bpmn/so-bpmn-building-blocks/src/test/resources/SDNCClientPut200Response.json b/bpmn/so-bpmn-building-blocks/src/test/resources/SDNCClientPut200Response.json new file mode 100644 index 0000000000..286ce4c844 --- /dev/null +++ b/bpmn/so-bpmn-building-blocks/src/test/resources/SDNCClientPut200Response.json @@ -0,0 +1,15 @@ +{ + "output": { + "svc-request-id": "5d24d40e-4c77-4c06-94a3-6d168c47a57c", + "network-response-information": { + "instance-id": "4063e0aa-af13-4872-8473-b40c94f9316b", + "object-path": "restconf/config/GENERIC-RESOURCE-API:services/service/2c9c7996-75a7-4f92-becc-9e13e8bd288a/service-data/networks/network/4063e0aa-af13-4872-8473-b40c94f9316b/network-data/network-topology/" + }, + "response-code": "200", + "service-response-information": { + "instance-id": "2c9c7996-75a7-4f92-becc-9e13e8bd288a" + }, + "response-message": "", + "ack-final-indicator": "Y" + } +} diff --git a/bpmn/so-bpmn-building-blocks/src/test/resources/SDNCClientPut200ResponseNotFinal.json b/bpmn/so-bpmn-building-blocks/src/test/resources/SDNCClientPut200ResponseNotFinal.json new file mode 100644 index 0000000000..deb4de0219 --- /dev/null +++ b/bpmn/so-bpmn-building-blocks/src/test/resources/SDNCClientPut200ResponseNotFinal.json @@ -0,0 +1,15 @@ +{ + "output": { + "svc-request-id": "5d24d40e-4c77-4c06-94a3-6d168c47a57c", + "network-response-information": { + "instance-id": "4063e0aa-af13-4872-8473-b40c94f9316b", + "object-path": "restconf/config/GENERIC-RESOURCE-API:services/service/2c9c7996-75a7-4f92-becc-9e13e8bd288a/service-data/networks/network/4063e0aa-af13-4872-8473-b40c94f9316b/network-data/network-topology/" + }, + "response-code": "200", + "service-response-information": { + "instance-id": "2c9c7996-75a7-4f92-becc-9e13e8bd288a" + }, + "response-message": "", + "ack-final-indicator": "N" + } +} diff --git a/bpmn/so-bpmn-building-blocks/src/test/resources/SDNCFlowRequest.json b/bpmn/so-bpmn-building-blocks/src/test/resources/SDNCFlowRequest.json new file mode 100644 index 0000000000..41fdf98bd0 --- /dev/null +++ b/bpmn/so-bpmn-building-blocks/src/test/resources/SDNCFlowRequest.json @@ -0,0 +1,11 @@ +{ + "timeOut":"PT1H", + "URI": "http:llasdfasdf", + "CorrelationValue": "randomUUID", + "CorrelationName": "MyCallbackVariableName", + "SDNCPayLoad": { + "test":"test", + "test2":"test", + "test3":"test" + } +} \ No newline at end of file diff --git a/bpmn/so-bpmn-building-blocks/src/test/resources/SDNC_Client_Request.json b/bpmn/so-bpmn-building-blocks/src/test/resources/SDNC_Client_Request.json new file mode 100644 index 0000000000..f60767b85e --- /dev/null +++ b/bpmn/so-bpmn-building-blocks/src/test/resources/SDNC_Client_Request.json @@ -0,0 +1,28 @@ +: { + "input": { + "request-information": { + "request-action": "CreateServiceInstance", + "source": "MSO", + "request-id": "5a09ab96-032b-41cd-ad81-4fb9ec5fade7" + }, + "sdnc-request-header": { + "svc-request-id": "5a09ab96-032b-41cd-ad81-4fb9ec5fade7", + "svc-action": "assign" + }, + "service-information": { + "onap-model-information": { + "model-name": "Vf zrdm5bpxmc02092017-Service", + "model-version": "1.0", + "model-uuid": "bad955c3-29b2-4a27-932e-28e942cc6480", + "model-invariant-uuid": "b16a9398-ffa3-4041-b78c-2956b8ad9c7b" + }, + "subscription-service-type": "Robot_Test_Service_Type", + "service-id": "48121c5e-dde0-42a6-a78a-89556ff355d0", + "global-customer-id": "Robot_Test_Subscriber_ID", + "service-instance-id": "48121c5e-dde0-42a6-a78a-89556ff355d0" + }, + "service-request-input": { + "service-instance-name": "Robot_SI_For_VolumeGroup" + } + } +} \ No newline at end of file diff --git a/bpmn/so-bpmn-building-blocks/src/test/resources/application-test.yaml b/bpmn/so-bpmn-building-blocks/src/test/resources/application-test.yaml index 32d6435213..62e2c0a8c2 100644 --- a/bpmn/so-bpmn-building-blocks/src/test/resources/application-test.yaml +++ b/bpmn/so-bpmn-building-blocks/src/test/resources/application-test.yaml @@ -209,4 +209,4 @@ pnf: topicName: pnfReady consumerGroup: consumerGroup consumerId: consumerId - topicListenerDelayInSeconds: 5 \ No newline at end of file + topicListenerDelayInSeconds: 5 diff --git a/bpmn/so-bpmn-infrastructure-common/pom.xml b/bpmn/so-bpmn-infrastructure-common/pom.xml index 7510c20d35..b29017ea8d 100644 --- a/bpmn/so-bpmn-infrastructure-common/pom.xml +++ b/bpmn/so-bpmn-infrastructure-common/pom.xml @@ -7,7 +7,7 @@ 4.0.0 so-bpmn-infrastructure-common - jar + jar @@ -79,7 +79,7 @@ - org.eclipse.m2e @@ -120,10 +120,10 @@ test - + - **/AllTestsTestSuite.java - + **/AllTestsTestSuite.java + @@ -131,10 +131,10 @@ test - + - **/AllTasksTestsTestSuite.java - + **/AllTasksTestsTestSuite.java + @@ -168,7 +168,7 @@ camunda-bpm-spring-boot-starter-webapp ${camunda.springboot.version} test - + org.apache.cxf cxf-spring-boot-starter-jaxws @@ -183,7 +183,7 @@ org.apache.cxf cxf-rt-rs-service-description-swagger ${cxf.version} - + com.h2database h2 @@ -192,7 +192,7 @@ com.google.guava guava - + com.fasterxml.uuid java-uuid-generator @@ -203,7 +203,7 @@ org.apache.commons - commons-lang3 + commons-lang3 org.onap.so @@ -227,11 +227,6 @@ javax.ws.rs-api ${jax.ws.rs} - - org.onap.so - MSORESTClient - ${project.version} - org.camunda.spin camunda-spin-core @@ -259,7 +254,7 @@ javax.annotation - javax.annotation-api + javax.annotation-api org.onap.msb.java-sdk @@ -289,7 +284,7 @@ org.slf4j slf4j-api - + org.mariadb.jdbc mariadb-java-client diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy index cd583f77ef..a0f0e279f6 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -31,16 +31,21 @@ import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.ExternalAPIUtil import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.aai.domain.yang.SpPartner import org.onap.so.bpmn.common.recipe.ResourceInput import org.onap.so.bpmn.common.resource.ResourceRequestBuilder import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder -import org.onap.so.rest.APIResponse +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory import java.util.Map import java.util.UUID +import javax.ws.rs.core.Response import org.onap.so.logger.MsoLogger import org.camunda.bpm.engine.runtime.Execution @@ -49,12 +54,10 @@ import org.camunda.bpm.engine.delegate.DelegateExecution import org.apache.commons.lang3.* import org.apache.commons.codec.binary.Base64 import org.springframework.web.util.UriUtils -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig /** * This groovy class supports the Create3rdONAPE2EServiceInstance.bpmn process. - * flow for Create E2EServiceInstance in 3rdONAP + * flow for Create E2EServiceInstance in 3rdONAP */ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcessor { @@ -82,10 +85,10 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String resourceInputPrameters = resourceInputObj.getResourceParameters() String inputParametersJson = JsonUtils.getJsonValue(resourceInputPrameters, "requestInputs") JSONObject inputParameters = new JSONObject(inputParametersJson) - + // set local resourceInput execution.setVariable(Prefix + "ResourceInput", resourceInputObj) - + boolean is3rdONAPExist = false if(inputParameters.has("sppartner_url")) @@ -123,7 +126,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String msg = "sppartner providingServiceInvarianteUuid is blank." msoLogger.debug(msg) } - + if(inputParameters.has("sppartner_handoverMode")) { String handoverMode = inputParameters.get("sppartner_handoverMode") @@ -153,9 +156,9 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso public void checkLocallCall (DelegateExecution execution) { msoLogger.info(" ***** Started checkLocallCall *****") try { - + //Get ResourceInput Object - ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") + ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") //uuiRequest String incomingRequest = resourceInputObj.getRequestsInputs() @@ -163,7 +166,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs") JSONObject inputParameters = new JSONObject(requestInputs) execution.setVariable(Prefix + "ServiceParameters", inputParameters) - + // CallSource is added only when ONAP SO calling 3rdONAP(External API) SO(Remote call) boolean isLocalCall = true String callSource = "UUI" @@ -174,11 +177,11 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String sppartnerId = inputParameters.get("SppartnerServiceId") execution.setVariable(Prefix + "SppartnerServiceId", sppartnerId) isLocalCall = false - } + } } execution.setVariable(Prefix + "CallSource", callSource) msoLogger.debug("callSource is: " + callSource ) - + execution.setVariable("IsLocalCall", isLocalCall) } catch (Exception ex){ @@ -211,7 +214,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable("serviceType", serviceType) msoLogger.info("serviceType:" + serviceType) - + String resourceName = resourceInputObj.getResourceInstanceName() if (isBlank(resourceName)) { msg = "Input resourceName is null" @@ -219,11 +222,11 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable("resourceName", resourceName) msoLogger.info("resourceName:" + resourceName) - + int beginIndex = resourceName.indexOf("_") + 1 String serviceInstanceName = resourceName.substring(beginIndex) execution.setVariable("serviceInstanceName", serviceInstanceName) - + String serviceInstanceId = resourceInputObj.getServiceInstanceId() if (isBlank(serviceInstanceId)) { msg = "Input serviceInstanceId is null" @@ -239,7 +242,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable(Prefix + "ResourceModelInvariantUuid", resourceModelInvariantUuid) msoLogger.info("resourceModelInvariantUuid:" + resourceModelInvariantUuid) - + String resourceModelUuid = resourceInputObj.getResourceModelInfo().getModelUuid() if (isBlank(resourceModelUuid)) { msg = "Input resourceModelUuid is null" @@ -247,7 +250,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable(Prefix + "ResourceModelUuid", resourceModelUuid) msoLogger.info("resourceModelUuid:" + resourceModelUuid) - + String resourceModelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() if (isBlank(resourceModelCustomizationUuid)) { msg = "Input resourceModelCustomizationUuid is null" @@ -300,7 +303,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso public void allocateCrossONAPResource(DelegateExecution execution) { msoLogger.info(" ***** Started allocateCrossONAPResource *****") - + //get TP links from AAI for SOTN handoverMode only String handoverMode = execution.getVariable(Prefix + "HandoverMode") if("SOTN".equalsIgnoreCase(handoverMode)) { @@ -318,7 +321,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso crossTPs.put("remote-access-topology-id", inputParameters.get("local-access-topology-id")); crossTPs.put("remote-access-node-id", inputParameters.get("local-access-node-id")); crossTPs.put("remote-access-ltp-id", inputParameters.get("local-access-ltp-id")); - + inputParameters.put("local-access-provider-id", crossTPs.get("local-access-provider-id")); inputParameters.put("local-access-client-id", crossTPs.get("local-access-client-id")); inputParameters.put("local-access-topology-id", crossTPs.get("local-access-topology-id")); @@ -336,17 +339,17 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso msoLogger.error("No allocated CrossONAPResource found in ServiceParameters") } } - + msoLogger.info("Exit " + allocateCrossONAPResource) } public void prepare3rdONAPRequest(DelegateExecution execution) { msoLogger.info(" ***** Started prepare3rdONAPRequest *****") - + String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") String extAPIPath = sppartnerUrl + '/serviceOrder' execution.setVariable("ExternalAPIURL", extAPIPath) - + // ExternalAPI message format String externalId = execution.getVariable("resourceName") String category = "E2E Service" @@ -363,7 +366,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String serviceState = "active" String serviceName = execution.getVariable("serviceInstanceName") String serviceUuId = execution.getVariable(Prefix + "SppartnerUUID") - + Map valueMap = new HashMap<>() valueMap.put("externalId", '"' + externalId + '"') valueMap.put("category", '"' + category + '"') @@ -381,30 +384,30 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso valueMap.put("serviceId", "null") //null for add valueMap.put("serviceName", '"' + serviceName + '"') valueMap.put("serviceUuId", '"' + serviceUuId + '"') - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - - // insert CallSource='ExternalAPI' to uuiRequest + + // insert CallSource='ExternalAPI' to uuiRequest Map requestInputsMap = new HashMap<>() requestInputsMap.put("inputName", '"CallSource"') requestInputsMap.put("inputValue", '"ExternalAPI"') String _requestInputs_ = externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap) - + requestInputsMap.clear() String serviceInstanceId = execution.getVariable(Prefix + "ServiceInstanceId") requestInputsMap.put("inputName", '"SppartnerServiceId"') requestInputsMap.put("inputValue", '"' + serviceInstanceId + '"') _requestInputs_ += ",\n" + externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap) - + requestInputsMap.clear() String serviceType = execution.getVariable("serviceType") requestInputsMap.put("inputName", '"serviceType"') requestInputsMap.put("inputValue", '"' + serviceType + '"') _requestInputs_ += ",\n" + externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap) - + // Transfer all uuiRequest incomeParameters to ExternalAPI format JSONObject inputParameters = execution.getVariable(Prefix + "ServiceParameters") - for(String key : inputParameters.keySet()) { + for(String key : inputParameters.keySet()) { String inputName = key String inputValue = inputParameters.opt(key) requestInputsMap.clear() @@ -413,7 +416,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso _requestInputs_ += ",\n" + externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap) } valueMap.put("_requestInputs_", _requestInputs_) - + String payload = externalAPIUtil.setTemplate(ExternalAPIUtil.PostServiceOrderRequestsTemplate, valueMap) execution.setVariable(Prefix + "Payload", payload) msoLogger.info("Exit " + prepare3rdONAPRequest) @@ -421,26 +424,26 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso public void doCreateE2ESIin3rdONAP(DelegateExecution execution) { msoLogger.info(" ***** Started doCreateE2ESIin3rdONAP *****") - + String extAPIPath = execution.getVariable("ExternalAPIURL") String payload = execution.getVariable(Prefix + "Payload") msoLogger.debug("doCreateE2ESIin3rdONAP externalAPIURL is: " + extAPIPath) msoLogger.debug("doCreateE2ESIin3rdONAP payload is: " + payload) - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - APIResponse response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) + Response response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) - int responseCode = response.getStatusCode() + int responseCode = response.getStatus() execution.setVariable(Prefix + "PostServiceOrderResponseCode", responseCode) msoLogger.debug("Post ServiceOrder response code is: " + responseCode) - String extApiResponse = response.getResponseBodyAsString() + String extApiResponse = response.readEntity(String.class) JSONObject responseObj = new JSONObject(extApiResponse) execution.setVariable(Prefix + "PostServiceOrderResponse", extApiResponse) - + msoLogger.debug("doCreateE2ESIin3rdONAP response body is: " + extApiResponse) - + //Process Response if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) //200 OK 201 CREATED 202 ACCEPTED @@ -455,32 +458,32 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso msoLogger.error("Post ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode) // exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Post ServiceOrder Received a bad response from 3rdONAP External API") } - + msoLogger.info("Exit " + doCreateE2ESIin3rdONAP) } - + public void getE2ESIProgressin3rdONAP(DelegateExecution execution) { msoLogger.info(" ***** Started getE2ESIProgressin3rdONAP *****") - + String extAPIPath = execution.getVariable("ExternalAPIURL") extAPIPath += "/" + execution.getVariable("ServiceOrderId") utils.log("DEBUG", "getE2ESIProgressin3rdONAP create externalAPIURL is: " + extAPIPath, isDebugEnabled) - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - APIResponse response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) + Response response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) - int responseCode = response.getStatusCode() + int responseCode = response.getStatus() execution.setVariable(Prefix + "GetServiceOrderResponseCode", responseCode) msoLogger.debug("Get ServiceOrder response code is: " + responseCode) - String extApiResponse = response.getResponseBodyAsString() + String extApiResponse = response.readEntity(String.class) JSONObject responseObj = new JSONObject(extApiResponse) execution.setVariable(Prefix + "GetServiceOrderResponse", extApiResponse) - + msoLogger.debug("getE2ESIProgressin3rdONAP create response body is: " + extApiResponse) - + //Process Response //200 OK 201 CREATED 202 ACCEPTED if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) { @@ -511,7 +514,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String serviceOrderState = item.get("state") execution.setVariable(Prefix + "SuccessIndicator", true) execution.setVariable("ServiceOrderState", serviceOrderState) - + // Get serviceOrder State and process progress if("ACKNOWLEDGED".equalsIgnoreCase(serviceOrderState)) { execution.setVariable("progress", 15) @@ -539,17 +542,17 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso execution.setVariable("statusDescription", "Create Service Order Status is unknown") } } - else{ + else{ msoLogger.debug("Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode) execution.setVariable("progress", 100) execution.setVariable("status", "error") execution.setVariable("statusDescription", "Get Create ServiceOrder Received a bad response") exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Get Create ServiceOrder Received a bad response from 3rdONAP External API") - } - + } + msoLogger.info("Exit " + getE2ESIProgressin3rdONAP) } - + /** * delay 5 sec */ @@ -562,8 +565,8 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } public void saveSPPartnerInAAI(DelegateExecution execution) { - msoLogger.info(" ***** Started saveSPPartnerInAAI *****") - + msoLogger.info(" ***** Started saveSPPartnerInAAI *****") + String sppartnerId = execution.getVariable(Prefix + "SppartnerServiceId") String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") String callSource = execution.getVariable(Prefix + "CallSource") @@ -574,57 +577,21 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String resourceModelUuid = execution.getVariable(Prefix + "ResourceModelUuid") String resourceModelCustomizationUuid = execution.getVariable(Prefix + "ResourceModelCustomizationUuid") - AaiUtil aaiUriUtil = new AaiUtil() - String aai_uri = aaiUriUtil.getBusinessSPPartnerUri(execution) - String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) - - String payload = - """ - ${sppartnerId} - ${sppartnerUrl} - ${callSource} - ${resourceModelInvariantUuid} - ${resourceModelUuid} - ${resourceModelCustomizationUuid} - - - service-instance - /aai/v14/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${serviceInstanceId} - - service-instance.service-instance-id - ${serviceInstanceId} - - - - """.trim() - utils.logAudit(payload) - - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - String serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(sppartnerId,"UTF-8") - - APIResponse response = aaiUriUtil.executeAAIPutCall(execution, serviceAaiPath, payload) - int responseCode = response.getStatusCode() - execution.setVariable(Prefix + "PutSppartnerResponseCode", responseCode) - msoLogger.debug("Put sppartner response code is: " + responseCode) + SpPartner partner = new SpPartner() + partner.setSpPartnerId(sppartnerId) + partner.setUrl(sppartnerUrl) + partner.setCallsource(callSource) + partner.setModelInvariantId(resourceModelInvariantUuid) + partner.setModelVersionId(resourceModelUuid) + partner.setModelCustomizationId(resourceModelCustomizationUuid) - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable(Prefix + "PutSppartnerResponse", aaiResponse) + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SP_PARTNER, sppartnerId) + client.create(uri, partner) + + AAIResourceUri siUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceInstanceId) + client.connect(uri, siUri) - //Process Response - if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) - //200 OK 201 CREATED 202 ACCEPTED - { - msoLogger.debug("PUT sppartner Received a Good Response") - execution.setVariable(Prefix + "SuccessIndicator", true) - } - else - { - msoLogger.debug("Put sppartner Received a Bad Response Code. Response Code is: " + responseCode) - exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) - throw new BpmnError("MSOWorkflowException") - } - msoLogger.info("Exit " + saveSPPartnerInAAI) } @@ -632,7 +599,7 @@ public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) execution.setVariable("CVFMI_updateResOperStatusRequest", body) - } + } public void postProcess(DelegateExecution execution){ msoLogger.info(" ***** Started postProcess *****") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateDeviceResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateDeviceResource.groovy index 89a6239be7..8fc9ce0883 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateDeviceResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateDeviceResource.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,27 +26,23 @@ import org.json.XML; import static org.apache.commons.lang3.StringUtils.*; import groovy.xml.XmlUtil import groovy.json.* -import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.recipe.ResourceInput; -import org.onap.so.bpmn.common.resource.ResourceRequestBuilder -import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import java.util.UUID; -import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.apache.commons.lang3.* import org.apache.commons.codec.binary.Base64; -import org.springframework.web.util.UriUtils -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig -import org.onap.so.rest.APIResponse; +import org.springframework.web.util.UriUtils import org.onap.so.bpmn.common.scripts.AaiUtil /** @@ -56,18 +52,18 @@ import org.onap.so.bpmn.common.scripts.AaiUtil public class CreateDeviceResource extends AbstractServiceTaskProcessor { String Prefix="CREDEVRES_" - + ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() - + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateDeviceResource.class) public void preProcessRequest(DelegateExecution execution){ msoLogger.info(" ***** Started preProcessRequest *****") String msg = "" - try { - + try { + //get bpmn inputs from resource request. String requestId = execution.getVariable("mso-request-id") String requestAction = execution.getVariable("requestAction") @@ -90,10 +86,10 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { // String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs") // JSONObject serviceInputParameters = new JSONObject(requestInputs) // execution.setVariable(Prefix + "ServiceParameters", serviceInputParameters) - + //Deal with recipeParams String recipeParamsFromWf = execution.getVariable("recipeParamXsd") - String resourceName = resourceInputObj.getResourceInstanceName() + String resourceName = resourceInputObj.getResourceInstanceName() if (isBlank(resourceName)) { msg = "Input resourceName is null" msoLogger.error(msg) @@ -108,7 +104,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { } execution.setVariable(Prefix + "ResourceModelInvariantUuid", resourceModelInvariantUuid) msoLogger.info("resourceModelInvariantUuid:" + resourceModelInvariantUuid) - + String resourceModelUuid = resourceInputObj.getResourceModelInfo().getModelUuid() if (isBlank(resourceModelUuid)) { msg = "Input resourceModelUuid is null" @@ -116,7 +112,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { } execution.setVariable(Prefix + "ResourceModelUuid", resourceModelUuid) msoLogger.info("resourceModelUuid:" + resourceModelUuid) - + String resourceModelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() if (isBlank(resourceModelCustomizationUuid)) { msg = "Input resourceModelCustomizationUuid is null" @@ -127,7 +123,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { execution.setVariable(Prefix + "serviceInstanceId", resourceInputObj.getServiceInstanceId()) execution.setVariable("mso-request-id", requestId) - + } catch (BpmnError e) { throw e; } catch (Exception ex){ @@ -136,22 +132,22 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } } - + public void checkDevType(DelegateExecution execution){ msoLogger.info(" ***** Started checkDevType *****") try { JSONObject resourceInputParameters = execution.getVariable(Prefix + "ResourceRequestInputs") String devType = resourceInputParameters.get("device_class") - + if(StringUtils.isBlank(devType)) { devType = "OTHER" } - // support VNF as PNF, to modify + // support VNF as PNF, to modify else if(StringUtils.equalsIgnoreCase(devType, "VNF")) { devType = "PNF" - } - + } + execution.setVariable("device_class", devType) } catch (Exception ex){ @@ -160,13 +156,13 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } } - + private void setProgressUpdateVariables(DelegateExecution execution, String body) { def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) execution.setVariable("CVFMI_updateResOperStatusRequest", body) } - + public void prepareUpdateProgress(DelegateExecution execution) { msoLogger.info(" ***** Started prepareUpdateProgress *****") ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") @@ -199,7 +195,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { setProgressUpdateVariables(execution, body) msoLogger.info(" ***** Exit prepareUpdateProgress *****") } - + public void getVNFTemplatefromSDC(DelegateExecution execution){ msoLogger.info(" ***** Started getVNFTemplatefromSDC *****") try { @@ -212,7 +208,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } } - + public void postVNFInfoProcess(DelegateExecution execution){ msoLogger.info(" ***** Started postVNFInfoProcess *****") try { @@ -225,7 +221,7 @@ public class CreateDeviceResource extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } } - + public void sendSyncResponse (DelegateExecution execution) { msoLogger.debug(" *** sendSyncResponse *** ") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy index 47b3cc351f..4b5737c776 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,14 +25,19 @@ import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.json.JSONObject import org.json.XML +import org.onap.aai.domain.yang.ServiceInstance +import org.onap.aai.domain.yang.ServiceInstances import org.onap.so.bpmn.common.recipe.ResourceInput import org.onap.so.bpmn.common.resource.ResourceRequestBuilder import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.AAIObjectPlurals +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse import static org.apache.commons.lang3.StringUtils.* @@ -50,7 +55,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { JsonUtils jsonUtil = new JsonUtils() public void preProcessRequest(DelegateExecution execution){ - + msoLogger.info(" ***** Started preProcessRequest *****") try { @@ -208,27 +213,20 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { def vpnName = StringUtils.containsIgnoreCase(modelName, "sotnvpnattachment") ? "sotnvpnattachmentvf_sotncondition_sotnVpnName" : "sdwanvpnattachmentvf_sdwancondition_sdwanVpnName" String parentServiceName = jsonUtil.getJsonValueForKey(resourceInputObj.getRequestsInputs(), vpnName) - AaiUtil aaiUtil = new AaiUtil(this) - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - String customerUri = aaiUtil.getBusinessCustomerUri(execution) + "/" + customer - String aai_service_query_url = aai_endpoint + customerUri + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances?service-instance-name=" + parentServiceName + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.SERVICE_INSTANCE, customer, serviceType).queryParam("service-instance-name", parentServiceName) + ServiceInstances sis = client.get(uri).asBean(ServiceInstances.class).get() + ServiceInstance si = sis.getServiceInstance().get(0) - APIResponse aaiResponse = aaiUtil.executeAAIGetCall(execution, aai_service_query_url) - def parentServiceInstanceId = getParentServiceInstnaceId(aaiResponse) - execution.setVariable("parentServiceInstanceId", parentServiceInstanceId) - break + def parentServiceInstanceId = si.getServiceInstanceId() + execution.setVariable("parentServiceInstanceId", parentServiceInstanceId) + break default: break } } - private String getParentServiceInstnaceId(APIResponse aaiResponse) { - String response = aaiResponse.getResponseBodyAsString() - def xmlResp = new XmlParser().parseText(response) - return "${xmlResp?."service-instance"[0]?."service-instance-id"[0]?.text()}" - } - /** * Pre Process the BPMN Flow Request * Includes: @@ -388,7 +386,7 @@ public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { // for SDWANConnectivity and SOTNConnectivity: default: sdncTopologyCreateRequest = """ ${hdrRequestId} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy index 409b8dfd1c..e3702f1014 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,17 +25,16 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor -import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.client.HttpClient import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import groovy.json.* +import javax.ws.rs.core.Response +import org.onap.so.utils.TargetEntity /** * This groovy class supports the DoCreateVFCNetworkServiceInstance.bpmn process. @@ -46,9 +45,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { String vfcUrl = "/vfc/rest/v1/vfcadapter" - + String host = "http://mso.mso.testlab.openecomp.org:8080" - + ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -116,7 +115,7 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { execution.setVariable("nsOperationKey", nsOperationKey); execution.setVariable("nsParameters", nsParameters) execution.setVariable("nsServiceModelUUID", nsServiceModelUUID); - + } catch (BpmnError e) { throw e; @@ -150,9 +149,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { "additionalParamForNs":${requestInputs} } }""" - APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String nsInstanceId = ""; if(returnCode== "200" || returnCode == "201"){ nsInstanceId = jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId") @@ -178,9 +177,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { }""" String nsInstanceId = execution.getVariable("nsInstanceId") String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate" - APIResponse apiResponse = postRequest(execution, url, reqBody) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, url, reqBody) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String jobId = ""; if(returnCode== "200"|| returnCode == "201"){ jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId") @@ -197,9 +196,9 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { String jobId = execution.getVariable("jobId") String nsOperationKey = execution.getVariable("nsOperationKey"); String url = host + vfcUrl + "/jobs/" + jobId - APIResponse apiResponse = postRequest(execution, url, nsOperationKey) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String operationStatus = "error" if(returnCode== "200"|| returnCode == "201"){ operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status") @@ -209,12 +208,12 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { } /** - * delay 5 sec + * delay 5 sec */ public void timeDelay(DelegateExecution execution) { try { Thread.sleep(5000); - } catch(InterruptedException e) { + } catch(InterruptedException e) { msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Time Delay exception" + e , "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); } } @@ -250,23 +249,29 @@ public class CreateVFCNSResource extends AbstractServiceTaskProcessor { * url: the url of the request * requestBody: the body of the request */ - private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){ + private Response postRequest(DelegateExecution execution, String urlString, String requestBody){ msoLogger.trace("Started Execute VFC adapter Post Process ") msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null + Response apiResponse = null try{ - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk"); - apiResponse = client.httpPost(requestBody) - msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) + + URL url = new URL(urlString); + + HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk") + + apiResponse = httpClient.post(requestBody) + + msoLogger.info("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class)) msoLogger.trace("Completed Execute VF-C adapter Post Process ") }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); throw new BpmnError("MSOWorkflowException") - } + } return apiResponse } - + public void sendSyncResponse (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy index 56e5be04a5..46c0c4bfa0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,39 +20,31 @@ package org.onap.so.bpmn.infrastructure.scripts +import javax.ws.rs.NotFoundException +import javax.ws.rs.core.Response + +import org.apache.commons.lang3.StringUtils +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution import org.json.JSONArray import org.json.JSONObject -import org.json.XML - -import static org.apache.commons.lang3.StringUtils.* -import groovy.xml.XmlUtil +import org.onap.aai.domain.yang.SpPartner +import org.onap.so.bpmn.common.recipe.ResourceInput +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.ExternalAPIUtil -import org.onap.so.bpmn.common.scripts.AaiUtil -import org.onap.so.bpmn.common.scripts.MsoUtils -import org.onap.so.bpmn.common.recipe.ResourceInput -import org.onap.so.bpmn.common.resource.ResourceRequestBuilder -import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder -import org.onap.so.rest.APIResponse -import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory -import java.util.UUID +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MsoLogger -import org.camunda.bpm.engine.runtime.Execution -import org.camunda.bpm.engine.delegate.BpmnError -import org.camunda.bpm.engine.delegate.DelegateExecution -import org.apache.commons.lang3.* -import org.apache.commons.codec.binary.Base64 -import org.springframework.web.util.UriUtils -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig - /** * This groovy class supports the Delete3rdONAPE2EServiceInstance.bpmn process. - * flow for Delete 3rdONAPE2EServiceInstance in 3rdONAP + * flow for Delete 3rdONAPE2EServiceInstance in 3rdONAP */ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcessor { @@ -79,33 +71,31 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) // set local resourceInput execution.setVariable(Prefix + "ResourceInput", resourceInputObj) - + String resourceInstanceId = resourceInputObj.getResourceInstancenUuid() String sppartnerId = resourceInstanceId execution.setVariable(Prefix + "SppartnerId", sppartnerId) - + // Get Sppartner from AAI - AaiUtil aaiUriUtil = new AaiUtil() - String aai_uri = aaiUriUtil.getBusinessSPPartnerUri(execution) - String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) - String aai_endpoint = execution.getVariable("URN_aai_endpoint") - String serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(sppartnerId,"UTF-8") - execution.setVariable(Prefix + "ServiceAaiPath", serviceAaiPath) - + AaiUtil aaiUriUtil = new AaiUtil(this) + AAIResourceUri spPartner = AAIUriFactory.createResourceUri(AAIObjectType.SP_PARTNER, sppartnerId) + String spPartnerUri = aaiUriUtil.createAaiUri(spPartner) + execution.setVariable(Prefix + "ServiceAaiPath", spPartnerUri) + getSPPartnerInAAI(execution) - + String callSource = "UUI" String sppartnerUrl = "" if(execution.hasVariable(Prefix + "CallSource")) { callSource = execution.getVariable(Prefix + "CallSource") sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") } - - boolean is3rdONAPExist = false - if(!isBlank(sppartnerUrl)) { + + boolean is3rdONAPExist = false + if(!isBlank(sppartnerUrl)) { is3rdONAPExist = true } - + execution.setVariable("Is3rdONAPExist", is3rdONAPExist) execution.setVariable(Prefix + "ServiceInstanceId", resourceInputObj.getServiceInstanceId()) execution.setVariable("mso-request-id", requestId) @@ -122,7 +112,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso public void checkLocallCall (DelegateExecution execution) { msoLogger.info(" ***** Started checkLocallCall *****") - + boolean isLocalCall = true String callSource = execution.getVariable(Prefix + "CallSource") if("ExternalAPI".equalsIgnoreCase(callSource)) { @@ -136,7 +126,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String msg = "" try { - ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") + ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") String globalSubscriberId = resourceInputObj.getGlobalSubscriberId() if (isBlank(globalSubscriberId)) { @@ -154,15 +144,15 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable("serviceType", serviceType) msoLogger.info( "serviceType:" + serviceType) - - String operationId = resourceInputObj.getOperationId() + + String operationId = resourceInputObj.getOperationId() if (isBlank(operationId)) { msg = "Input operationId is null" msoLogger.error( msg) } execution.setVariable("operationId", operationId) msoLogger.info( "operationId:" + operationId) - + String resourceName = resourceInputObj.getResourceInstanceName() if (isBlank(resourceName)) { msg = "Input resourceName is null" @@ -170,7 +160,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } execution.setVariable("resourceName", resourceName) msoLogger.info("resourceName:" + resourceName) - + String resourceTemplateId = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() if (isBlank(resourceTemplateId)) { msg = "Input resourceTemplateId is null" @@ -223,11 +213,11 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso public void prepare3rdONAPRequest(DelegateExecution execution) { msoLogger.info(" ***** Started prepare3rdONAPRequest *****") - + String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") String extAPIPath = sppartnerUrl + '/serviceOrder' execution.setVariable("ExternalAPIURL", extAPIPath) - + // ExternalAPI message format String externalId = execution.getVariable("resourceName") String category = "E2E Service" @@ -245,10 +235,10 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso String serviceName = "" String serviceType = execution.getVariable("serviceType") String serviceId = execution.getVariable(Prefix + "SppartnerId") - + queryServicefrom3rdONAP(execution) - String serviceSpecificationId = execution.getVariable(Prefix + "ServiceSpecificationId") - + String serviceSpecificationId = execution.getVariable(Prefix + "ServiceSpecificationId") + Map valueMap = new HashMap<>() valueMap.put("externalId", '"' + externalId + '"') valueMap.put("category", '"' + category + '"') @@ -266,20 +256,20 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso valueMap.put("serviceId", '"' + serviceId + '"') valueMap.put("serviceName", "null") valueMap.put("serviceUuId", '"' + serviceSpecificationId + '"') - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - + valueMap.put("_requestInputs_", "") - + String payload = externalAPIUtil.setTemplate(ExternalAPIUtil.PostServiceOrderRequestsTemplate, valueMap) execution.setVariable(Prefix + "Payload", payload) msoLogger.info( "Exit " + prepare3rdONAPRequest) } - + private void queryServicefrom3rdONAP(DelegateExecution execution) { msoLogger.info(" ***** Started queryServicefrom3rdONAP *****") - + String globalSubscriberId = execution.getVariable("globalSubscriberId") String SppartnerServiceId = execution.getVariable(Prefix + "SppartnerId") @@ -290,17 +280,17 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - APIResponse response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) + Response response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) - int responseCode = response.getStatusCode() + int responseCode = response.getStatus() execution.setVariable(Prefix + "GetServiceResponseCode", responseCode) msoLogger.debug("Get Service response code is: " + responseCode) - String extApiResponse = response.getResponseBodyAsString() + String extApiResponse = response.readEntity(String.class) - execution.setVariable(Prefix + "GetServiceResponse", extApiResponse) + execution.setVariable(Prefix + "GetServiceResponse", extApiResponse) msoLogger.debug("queryServicefrom3rdONAP response body is: " + extApiResponse) - + //Process Response //200 OK 201 CREATED 202 ACCEPTED if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) { @@ -320,27 +310,27 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso msoLogger.error("Get Service Received a Bad Response Code. Response Code is: " + responseCode) // exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Get Service Received a bad response from 3rdONAP External API") } - + msoLogger.info( "Exit " + queryServicefrom3rdONAP) } public void doDeleteE2ESIin3rdONAP(DelegateExecution execution) { msoLogger.info(" ***** Started doDeleteE2ESIin3rdONAP *****") - + String extAPIPath = execution.getVariable("ExternalAPIURL") String payload = execution.getVariable(Prefix + "Payload") msoLogger.debug("doDeleteE2ESIin3rdONAP externalAPIURL is: " + extAPIPath) msoLogger.debug("doDeleteE2ESIin3rdONAP payload is: " + payload) - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - APIResponse response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) + Response response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) - int responseCode = response.getStatusCode() + int responseCode = response.getStatus() execution.setVariable(Prefix + "PostServiceOrderResponseCode", responseCode) msoLogger.debug("Post ServiceOrder response code is: " + responseCode) - String extApiResponse = response.getResponseBodyAsString() + String extApiResponse = response.readEntity(String.class) JSONObject responseObj = new JSONObject(extApiResponse) execution.setVariable(Prefix + "PostServiceOrderResponse", extApiResponse) @@ -360,31 +350,31 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso msoLogger.error("Post ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode) exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Post ServiceOrder Received a bad response from 3rdONAP External API") } - + msoLogger.info( "Exit " + doDeleteE2ESIin3rdONAP) } - + public void getE2ESIProgressin3rdONAP(DelegateExecution execution) { msoLogger.info(" ***** Started getE2ESIProgressin3rdONAP *****") - + String extAPIPath = execution.getVariable("ExternalAPIURL") extAPIPath += "/" + execution.getVariable("ServiceOrderId") msoLogger.debug("getE2ESIProgressin3rdONAP delete externalAPIURL is: " + extAPIPath) - + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil() - APIResponse response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) + Response response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) - int responseCode = response.getStatusCode() + int responseCode = response.getStatus() execution.setVariable(Prefix + "GetServiceOrderResponseCode", responseCode) msoLogger.debug("Get ServiceOrder response code is: " + responseCode) - String extApiResponse = response.getResponseBodyAsString() + String extApiResponse = response.readEntity(String.class) JSONObject responseObj = new JSONObject(extApiResponse) execution.setVariable(Prefix + "GetServiceOrderResponse", extApiResponse) - - utils.log("DEBUG", "getE2ESIProgressin3rdONAP delete response body is: " + extApiResponse, isDebugEnabled) + + utils.log("DEBUG", "getE2ESIProgressin3rdONAP delete response body is: " + extApiResponse) //Process Response //200 OK 201 CREATED 202 ACCEPTED if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) @@ -443,17 +433,17 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso execution.setVariable("statusDescription", "Delete Service Order Status is unknown") } } - else{ + else{ msoLogger.debug("Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode) execution.setVariable("progress", 100) execution.setVariable("status", "error") execution.setVariable("statusDescription", "Get Delete ServiceOrder Received a bad response") exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Get Delete ServiceOrder Received a bad response from 3rdONAP External API") - } - + } + msoLogger.info( "Exit " + getE2ESIProgressin3rdONAP) } - + /** * delay 5 sec */ @@ -466,86 +456,53 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso } private void getSPPartnerInAAI(DelegateExecution execution) { - msoLogger.info(" ***** Started getSPPartnerInAAI *****") - - AaiUtil aaiUriUtil = new AaiUtil() - String serviceAaiPath = execution.getVariable(Prefix + "ServiceAaiPath") - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceAaiPath) - int responseCode = response.getStatusCode() - execution.setVariable(Prefix + "GetSppartnerResponseCode", responseCode) - msoLogger.debug(" Get sppartner response code is: " + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - aaiResponse = aaiResponse.replaceAll("&", "&") - execution.setVariable(Prefix + "GetSppartnerResponse", aaiResponse) + msoLogger.info(" ***** Started getSPPartnerInAAI *****") + String id = execution.getVariable(Prefix + "SppartnerId") + + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SP_PARTNER, id) + SpPartner sp = client.get(uri).asBean(SpPartner.class).get() + + msoLogger.debug("GET sppartner Received a Good Response") + execution.setVariable(Prefix + "SuccessIndicator", true) + execution.setVariable(Prefix + "FoundIndicator", true) + + String sppartnerId = sp.getSpPartnerId() + execution.setVariable(Prefix + "SppartnerId", sppartnerId) + msoLogger.debug(" SppartnerId is: " + sppartnerId) + String sppartnerUrl = sp.getUrl() + execution.setVariable(Prefix + "SppartnerUrl", sppartnerUrl) + msoLogger.debug(" SppartnerUrl is: " + sppartnerUrl) + String callSource = sp.getCallsource() + execution.setVariable(Prefix + "CallSource", callSource) + msoLogger.debug(" CallSource is: " + callSource) + String sppartnerVersion = sp.getResourceVersion() + execution.setVariable(Prefix + "SppartnerVersion", sppartnerVersion) + msoLogger.debug(" Resource Version is: " + sppartnerVersion) + - //Process Response - if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) - //200 OK 201 CREATED 202 ACCEPTED - { - msoLogger.debug("GET sppartner Received a Good Response") - execution.setVariable(Prefix + "SuccessIndicator", true) - execution.setVariable(Prefix + "FoundIndicator", true) - - String sppartnerId = utils.getNodeText1(aaiResponse, "sp-partner-id") - execution.setVariable(Prefix + "SppartnerId", sppartnerId) - msoLogger.debug(" SppartnerId is: " + sppartnerId) - String sppartnerUrl = utils.getNodeText1(aaiResponse, "url") - execution.setVariable(Prefix + "SppartnerUrl", sppartnerUrl) - msoLogger.debug(" SppartnerUrl is: " + sppartnerUrl) - String callSource = utils.getNodeText1(aaiResponse, "callsource") - execution.setVariable(Prefix + "CallSource", callSource) - msoLogger.debug(" CallSource is: " + callSource) - String sppartnerVersion = utils.getNodeText1(aaiResponse, "resource-version") - execution.setVariable(Prefix + "SppartnerVersion", sppartnerVersion) - msoLogger.debug(" Resource Version is: " + sppartnerVersion) - } - else - { - msoLogger.debug("Get sppartner Received a Bad Response Code. Response Code is: " + responseCode) -// exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) -// throw new BpmnError("MSOWorkflowException") - } - msoLogger.info( "Exit " + getSPPartnerInAAI) } - + public void deleteSPPartnerInAAI(DelegateExecution execution) { msoLogger.info(" ***** Started deleteSPPartnerInAAI *****") - + String sppartnerId = execution.getVariable(Prefix + "SppartnerId") String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") String sppartnerVersion = execution.getVariable(Prefix + "SppartnerVersion") - - AaiUtil aaiUriUtil = new AaiUtil() - String serviceAaiPath = execution.getVariable(Prefix + "ServiceAaiPath") + "?resource-version=${sppartnerVersion}" - APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, serviceAaiPath) - int responseCode = response.getStatusCode() - execution.setVariable(Prefix + "DeleteSppartnerResponseCode", responseCode) - msoLogger.debug(" Get sppartner response code is: " + responseCode) - - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - execution.setVariable(Prefix + "DeleteSppartnerResponse", aaiResponse) - //Process Response - if(responseCode == 200 || responseCode == 204 ) - { + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SP_PARTNER, sppartnerId) + try { + client.delete(uri) msoLogger.debug("Delete sppartner Received a Good Response") execution.setVariable(Prefix + "SuccessIndicator", true) - } - else if(responseCode == 404){ + } catch (NotFoundException e) { msoLogger.debug(" Delete sppartner Received a Not Found (404) Response") execution.setVariable(Prefix + "FoundIndicator", false) } - else - { - msoLogger.debug("Delete sppartner Received a Bad Response Code. Response Code is: " + responseCode) -// exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) -// throw new BpmnError("MSOWorkflowException") - } - + msoLogger.debug("Delete sppartner Received a Good Response") + msoLogger.info( "Exit " + deleteSPPartnerInAAI) } @@ -553,7 +510,7 @@ public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcesso def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) execution.setVariable("CVFMI_updateResOperStatusRequest", body) - } + } public void postProcess(DelegateExecution execution){ msoLogger.info(" ***** Started postProcess *****") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteDeviceResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteDeviceResource.groovy index 71ce28d7d3..82be3e6a0c 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteDeviceResource.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteDeviceResource.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -29,23 +29,23 @@ import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.recipe.ResourceInput; import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder +import org.onap.so.client.HttpClient import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import java.util.UUID; - +import javax.ws.rs.core.Response import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.apache.commons.lang3.* +import javax.ws.rs.core.MediaType import org.apache.commons.codec.binary.Base64; import org.springframework.web.util.UriUtils -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig -import org.onap.so.rest.APIResponse; +import org.onap.so.utils.TargetEntity import org.onap.so.bpmn.common.scripts.AaiUtil /** @@ -106,20 +106,29 @@ public class DeleteDeviceResource extends AbstractServiceTaskProcessor { private void getDeviceInAAI(DelegateExecution execution) { msoLogger.info(" ***** Started getDeviceInAAI *****") - + String deviceId = execution.getVariable(Prefix + "DeviceId") AaiUtil aaiUriUtil = new AaiUtil() String aai_uri = aaiUriUtil.getNetworkDeviceUri(execution) String aai_endpoint = execution.getVariable("URN_aai_endpoint") String serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(deviceId,"UTF-8") execution.setVariable(Prefix + "ServiceAaiPath", serviceAaiPath) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceAaiPath) - int responseCode = response.getStatusCode() + + URL url = new URL(serviceAaiPath) + HttpClient client = new HttpClient(url, MediaType.APPLICATION_XML, TargetEntity.AAI) + client.addBasicAuthHeader(UrnPropertiesReader.getVariable("aai.auth", execution), UrnPropertiesReader.getVariable("mso.msoKey", execution)) + client.addAdditionalHeader("X-FromAppId", "MSO") + client.addAdditionalHeader("X-TransactionId", utils.getRequestID()) + client.addAdditionalHeader("Accept", MediaType.APPLICATION_XML) + Response response = client.get() + + + + int responseCode = response.getStatus() execution.setVariable(Prefix + "GetDeviceResponseCode", responseCode) msoLogger.debug(" Get device response code is: " + responseCode) - String aaiResponse = response.getResponseBodyAsString() + String aaiResponse = response.readEntity(String.class) aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) aaiResponse = aaiResponse.replaceAll("&", "&") execution.setVariable(Prefix + "GetDeviceResponse", aaiResponse) @@ -131,8 +140,8 @@ public class DeleteDeviceResource extends AbstractServiceTaskProcessor { msoLogger.debug("GET Device Received a Good Response") execution.setVariable(Prefix + "SuccessIndicator", true) execution.setVariable(Prefix + "FoundIndicator", true) - - String devClass = utils.getNodeText1(aaiResponse, "device_class") + + String devClass = utils.getNodeText(aaiResponse, "device_class") execution.setVariable(Prefix + "DeviceClass", devClass) msoLogger.debug(" DeviceClass is: " + devClass) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy index 7cbbac5fbf..8c9ab3fe45 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy @@ -39,7 +39,6 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.constants.Defaults import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse import org.springframework.web.util.UriUtils diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy index 98605fea8b..9c9ed933e0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ - * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -40,9 +40,6 @@ import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import org.onap.so.bpmn.common.scripts.CatalogDbUtils; import org.onap.so.bpmn.core.RollbackData import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import java.util.List; import java.util.UUID; @@ -88,48 +85,48 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { try { execution.setVariable("prefix", Prefix) - + //Inputs String modelInvariantUuid_target = execution.getVariable("model-invariant-id-target") if (isBlank(modelInvariantUuid_target)) { msg = "Input model-invariant-id-target is null" utils.log("INFO", msg, isDebugEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - + } + String modelUuid_target = execution.getVariable("model-version-id-target") if (isBlank(modelUuid_target)) { msg = "Input model-version-id-target is null" utils.log("INFO", msg, isDebugEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) } - + String modelInvariantUuid_original = execution.getVariable("model-invariant-id-original") if (isBlank(modelInvariantUuid_original)) { msg = "Input model-invariant-id-original is null" utils.log("INFO", msg, isDebugEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) } - + String modelUuid_original = execution.getVariable("model-version-id-original") if (isBlank(modelUuid_original)) { msg = "Input model-version-id-original is null" utils.log("INFO", msg, isDebugEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) - } - + } + // Target and original modelInvariantUuid must to be the same if(modelInvariantUuid_target != modelInvariantUuid_original){ msg = "Input model-invariant-id-target and model-invariant-id-original must to be the same" utils.log("INFO", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) } - + // Target and original modelUuid must not to be the same if(modelUuid_target == modelUuid_original){ msg = "Input model-version-id-target and model-version-id-original must not to be the same" utils.log("INFO", msg, isDebugEnabled) - exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) } } catch (Exception ex){ @@ -139,7 +136,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { } utils.log("INFO"," ***** Exit preProcessRequest *****", isDebugEnabled) } - + public void prepareDecomposeService_Target(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") @@ -153,7 +150,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { "modelUuid":"${modelUuid}", "modelVersion":"" }""" - + execution.setVariable("serviceModelInfo_Target", serviceModelInfo) utils.log("DEBUG", " ***** Completed prepareDecomposeService_Target of update generic e2e service ***** ", isDebugEnabled) @@ -166,8 +163,8 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { public void processDecomposition_Target(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("DEBUG", " ***** Inside processDecomposition_Target() of update generic e2e service flow ***** ", isDebugEnabled) + + utils.log("DEBUG", " ***** Inside processDecomposition_Target() of update generic e2e service flow ***** ", isDebugEnabled) try { ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") execution.setVariable("serviceDecomposition_Target", serviceDecomposition) @@ -177,7 +174,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) } } - + public void prepareDecomposeService_Original(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") @@ -191,7 +188,7 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { "modelUuid":"${modelUuid}", "modelVersion":"" }""" - + execution.setVariable("serviceModelInfo_Original", serviceModelInfo) utils.log("DEBUG", " ***** Completed prepareDecomposeService_Original of update generic e2e service ***** ", isDebugEnabled) @@ -204,8 +201,8 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { public void processDecomposition_Original(DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - - utils.log("DEBUG", " ***** Inside processDecomposition_Original() of update generic e2e service flow ***** ", isDebugEnabled) + + utils.log("DEBUG", " ***** Inside processDecomposition_Original() of update generic e2e service flow ***** ", isDebugEnabled) try { ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") execution.setVariable("serviceDecomposition_Original", serviceDecomposition) @@ -214,45 +211,45 @@ public class DoCompareModelVersions extends AbstractServiceTaskProcessor { utils.log("DEBUG", exceptionMessage, isDebugEnabled) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) } - } + } public void doCompareModelVersions(DelegateExecution execution){ def isDebugEnabled=execution.getVariable("isDebugLogEnabled") - utils.log("INFO", "======== Start doCompareModelVersions Process ======== ", isDebugEnabled) + utils.log("INFO", "======== Start doCompareModelVersions Process ======== ", isDebugEnabled) ServiceDecomposition serviceDecomposition_Target = execution.getVariable("serviceDecomposition_Target") ServiceDecomposition serviceDecomposition_Original = execution.getVariable("serviceDecomposition_Original") - + List allSR_target = serviceDecomposition_Target.getServiceResources(); List allSR_original = serviceDecomposition_Original.getServiceResources(); - + List addResourceList = new ArrayList() List delResourceList = new ArrayList() - + addResourceList.addAll(allSR_target) delResourceList.addAll(allSR_original) - + //Compare for (Resource rc_t : allSR_target){ String muuid = rc_t.getModelInfo().getModelUuid() String mIuuid = rc_t.getModelInfo().getModelInvariantUuid() String mCuuid = rc_t.getModelInfo().getModelCustomizationUuid() for (Resource rc_o : allSR_original){ - if(rc_o.getModelInfo().getModelUuid() == muuid - && rc_o.getModelInfo().getModelInvariantUuid() == mIuuid + if(rc_o.getModelInfo().getModelUuid() == muuid + && rc_o.getModelInfo().getModelInvariantUuid() == mIuuid && rc_o.getModelInfo().getModelCustomizationUuid() == mCuuid) { addResourceList.remove(rc_t); delResourceList.remove(rc_o); } - } + } } execution.setVariable("addResourceList", addResourceList) execution.setVariable("delResourceList", delResourceList) - utils.log("INFO", "addResourceList: " + addResourceList, isDebugEnabled) + utils.log("INFO", "addResourceList: " + addResourceList, isDebugEnabled) utils.log("INFO", "delResourceList: " + delResourceList, isDebugEnabled) - - utils.log("INFO", "======== COMPLETED doCompareModelVersions Process ======== ", isDebugEnabled) + + utils.log("INFO", "======== COMPLETED doCompareModelVersions Process ======== ", isDebugEnabled) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy index d43a19624e..5b7d38dfb6 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy @@ -46,7 +46,7 @@ import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse + import org.springframework.web.util.UriUtils import org.onap.so.bpmn.core.UrnPropertiesReader @@ -461,10 +461,10 @@ public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { uuiRequest = ServicePluginFactory.getInstance().doProcessSiteLocation(serviceDecomposition, uuiRequest); execution.setVariable("uuiRequest", uuiRequest) execution.setVariable("serviceDecomposition", serviceDecomposition) - + msoLogger.trace("======== COMPLETED doProcessSiteLocation Process ======== ") } - + // Allocate cross link TPs(terminal points) for sotn network only public void doTPResourcesAllocation(DelegateExecution execution){ msoLogger.trace("======== Start doTPResourcesAllocation Process ======== ") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy index 82355beed2..4f00a64ecb 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy @@ -32,9 +32,6 @@ import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import org.onap.so.bpmn.core.RollbackData import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.onap.so.logger.MsoLogger import org.onap.so.logger.MessageEnum import org.onap.so.bpmn.common.scripts.ExceptionUtil; diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy index 51574f63f8..c9497165c4 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy @@ -21,7 +21,8 @@ package org.onap.so.bpmn.infrastructure.scripts; import javax.ws.rs.core.UriBuilder - +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory import org.apache.commons.lang3.* import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution @@ -41,14 +42,24 @@ import org.onap.so.client.aai.AAIResourcesClient import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.Relationships import org.onap.so.client.graphinventory.entities.uri.Depth import org.onap.so.constants.Defaults import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse; import org.springframework.web.util.UriUtils +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.NamedNodeMap +import org.w3c.dom.Node +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource import org.onap.aai.domain.yang.VpnBinding +import org.onap.aai.domain.yang.L3Network +import org.onap.aai.domain.yang.L3Networks +import org.onap.aai.domain.yang.NetworkPolicy +import org.onap.aai.domain.yang.RouteTableReference import org.onap.aai.domain.yang.RouteTarget - +import org.onap.aai.domain.yang.Subnet import com.fasterxml.jackson.jaxrs.util.EndpointAsBeanProperty import javax.ws.rs.NotFoundException @@ -359,66 +370,26 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { msoLogger.debug(" ***** Inside callRESTQueryAAINetworkName() of DoCreateNetworkInstance ***** " ) - // get variables - String networkInputs = execution.getVariable(Prefix + "networkInputs") - String networkName = utils.getNodeText(networkInputs, "network-name") - networkName = UriUtils.encode(networkName,"UTF-8") - - // Prepare AA&I url with network-name - String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) - AaiUtil aaiUriUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.L3_NETWORK) - uri.queryParam("network-name", networkName) - String queryAAINameRequest = aaiUriUtil.createAaiUri(uri) - - execution.setVariable(Prefix + "queryNameAAIRequest", queryAAINameRequest) - msoLogger.debug(Prefix + "queryNameAAIRequest - " + "\n" + queryAAINameRequest) - - try { - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryAAINameRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiNameReturnCode", returnCode) - msoLogger.debug(" ***** AAI Query Name Response Code : " + returnCode) - - String aaiResponseAsString = response.getResponseBodyAsString() - msoLogger.debug(" ***** AAI Query Name Response : " +'\n'+ aaiResponseAsString) - - if (returnCode=='200') { - execution.setVariable(Prefix + "queryNameAAIResponse", aaiResponseAsString) - execution.setVariable(Prefix + "isAAIqueryNameGood", true) - String orchestrationStatus = "" - try { - // response is NOT empty - orchestrationStatus = utils.getNodeText(aaiResponseAsString, "orchestration-status") - execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus.toUpperCase()) - msoLogger.debug(Prefix + "orchestrationStatus - " + orchestrationStatus.toUpperCase()) - execution.setVariable("orchestrationStatus", orchestrationStatus) - - } catch (Exception ex) { - // response is empty - execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus) - msoLogger.debug(Prefix + "orchestrationStatus - " + orchestrationStatus) - } - - } else { - if (returnCode=='404') { - msoLogger.debug(" QueryAAINetworkName return code = '404' (Not Found). Proceed with the Create !!! ") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Error Response from QueryAAINetworkName - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildWorkflowException(execution, 2500, dataErrorMessage) + try{ + // get variables + String networkInputs = execution.getVariable(Prefix + "networkInputs") + String networkName = utils.getNodeText(networkInputs, "network-name") - } + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.L3_NETWORK).queryParam("network-name", networkName) + L3Networks networks = client.get(uri, NotFoundException.class).asBean(L3Networks.class).get() + L3Network network = networks.getL3Network().get(0) - } + execution.setVariable(Prefix + "isAAIqueryNameGood", true) + String orchestrationStatus = network.getOrchestrationStatus() + execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus.toUpperCase()) + msoLogger.debug(Prefix + "orchestrationStatus - " + orchestrationStatus.toUpperCase()) + execution.setVariable("orchestrationStatus", orchestrationStatus) msoLogger.debug(Prefix + "isAAIqueryNameGood? : " + execution.getVariable(Prefix + "isAAIqueryNameGood")) - } catch (BpmnError e) { - throw e; + } catch (NotFoundException e) { + msoLogger.debug(" QueryAAINetworkName return code = '404' (Not Found). Proceed with the Create !!! ") } catch (Exception ex) { // try error @@ -515,57 +486,21 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { String networkName = utils.getNodeText(assignSDNCResponse, "network-name") execution.setVariable(Prefix + "networkName", networkName) - networkId = UriUtils.encode(networkId,"UTF-8") - - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) - uri.depth(Depth.ALL) - String queryIdAAIRequest = aaiUriUtil.createAaiUri(uri) - - execution.setVariable(Prefix + "queryIdAAIRequest", queryIdAAIRequest) - msoLogger.debug(Prefix + "queryIdAAIRequest - " + "\n" + queryIdAAIRequest) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryIdAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiIdReturnCode", returnCode) - - msoLogger.debug(" ***** AAI Response Code : " + returnCode) + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ONE) + L3Network network = client.get(uri, NotFoundException.class).asBean(L3Network.class).get() - String aaiResponseAsString = response.getResponseBodyAsString() + execution.setVariable(Prefix + "queryIdAAIResponse", network) - if (returnCode=='200') { - execution.setVariable(Prefix + "queryIdAAIResponse", aaiResponseAsString) - msoLogger.debug(" QueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString) - - String netId = utils.getNodeText(aaiResponseAsString, "network-id") - execution.setVariable(Prefix + "networkId", netId) - String netName = utils.getNodeText(aaiResponseAsString, "network-name") - execution.setVariable(Prefix + "networkName", netName) - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from QueryAAINetworkId is 404 (Not Found)." - msoLogger.debug(" AAI Query Failed. " + dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from QueryAAINetworkId - " + returnCode - msoLogger.debug("Unexpected Response from QueryAAINetworkId - " + dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } + String netId = network.getNetworkId() + execution.setVariable(Prefix + "networkId", netId) + String netName = network.getNetworkName() + execution.setVariable(Prefix + "networkName", netName) - } catch (BpmnError e) { - throw e; + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from QueryAAINetworkId is 404 (Not Found)." + msoLogger.debug(" AAI Query Failed. " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkId() - " + ex.getMessage() @@ -586,61 +521,27 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { // get variables String networkId = execution.getVariable(Prefix + "networkId") String netId = networkId - networkId = UriUtils.encode(networkId,"UTF-8") - - // Prepare AA&I url - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) - uri.depth(Depth.ALL) - String requeryIdAAIRequest = aaiUriUtil.createAaiUri(uri) - - execution.setVariable(Prefix + "requeryIdAAIRequest", requeryIdAAIRequest) - msoLogger.debug(Prefix + "requeryIdAAIRequest - " + "\n" + requeryIdAAIRequest) - - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, requeryIdAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiRequeryIdReturnCode", returnCode) - msoLogger.debug(" ***** AAI ReQuery Response Code : " + returnCode) - String aaiResponseAsString = response.getResponseBodyAsString() + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId).depth(Depth.ONE) + L3Network network = client.get(uri, NotFoundException.class).asBean(L3Network.class).get() - if (returnCode=='200') { - execution.setVariable(Prefix + "requeryIdAAIResponse", aaiResponseAsString) - msoLogger.debug(" ReQueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString) + execution.setVariable(Prefix + "aaiRequeryIdReturnCode", "200") - String netName = utils.getNodeText(aaiResponseAsString, "network-name") - String networkOutputs = - """ + String netName = network.getNetworkName() + String networkOutputs = + """ ${MsoUtils.xmlEscape(netId)} ${MsoUtils.xmlEscape(netName)} """ - execution.setVariable(Prefix + "networkOutputs", networkOutputs) - msoLogger.debug(" networkOutputs - " + '\n' + networkOutputs) - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)." - msoLogger.debug(" AAI ReQuery Failed. - " + dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from ReQueryAAINetworkId - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + execution.setVariable(Prefix + "networkOutputs", networkOutputs) + msoLogger.debug(" networkOutputs - " + '\n' + networkOutputs) - } - } - } - } catch (BpmnError e) { - throw e; + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)." + msoLogger.debug(" AAI ReQuery Failed. - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTReQueryAAINetworkId() - " + ex.getMessage() @@ -659,72 +560,57 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { try { - // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse").replace('', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) - - // Check if Vnf Binding is present, then build a List of vnfBinding - List vpnBindingUri = networkUtils.getVnfBindingObject(relationship) - int vpnCount = vpnBindingUri.size() - execution.setVariable(Prefix + "vpnCount", vpnCount) - msoLogger.debug(Prefix + "vpnCount - " + vpnCount) - - if (vpnCount > 0) { - execution.setVariable(Prefix + "vpnBindings", vpnBindingUri) - msoLogger.debug(" vpnBindingUri List - " + vpnBindingUri) - - String routeTargets = "" - // AII loop call using list vpnBindings - for(i in 0..vpnBindingUri.size()-1) { - int counting = i+1 - - String vpnBindingId = vpnBindingUri[i].substring(vpnBindingUri[i].indexOf("/vpn-binding/")+13, vpnBindingUri[i].length()) - if (vpnBindingId.charAt(vpnBindingId.length()-1) == '/') { - vpnBindingId = vpnBindingId.substring(0, vpnBindingId.length()-1) - } - - AAIResourcesClient resourceClient = new AAIResourcesClient() - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, vpnBindingId) - AAIResultWrapper wrapper = resourceClient.get(uri.depth(Depth.TWO), NotFoundException.class) - - Optional binding = wrapper.asBean(VpnBinding.class) - - String routeTarget = "" - String routeRole = "" - if(binding.get().getRouteTargets() != null) { - List targets = binding.get().getRouteTargets().getRouteTarget() - for(RouteTarget target : targets) { - routeTarget = target.getGlobalRouteTarget() - routeRole = target.getRouteTargetRole() - routeTargets += "" + '\n' + - " " + routeTarget + "" + '\n' + - " " + routeRole + "" + '\n' + - "" + '\n' + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, execution.getVariable(Prefix + "networkId")) + Optional relationships = client.get(uri, NotFoundException.class).getRelationships() + if(relationships.isPresent()){ + List uris = relationships.get().getRelatedAAIUris(AAIObjectType.VPN_BINDING) + + msoLogger.debug(Prefix + "vpnCount - " + uris.size()) + + if (uris.size() > 0) { + String routeTargets = "" + for(AAIResourceUri u : uris) { + + AAIResultWrapper wrapper = client.get(u.depth(Depth.TWO), NotFoundException.class) + Optional binding = wrapper.asBean(VpnBinding.class) + + String routeTarget = "" + String routeRole = "" + if(binding.get().getRouteTargets() != null) { + List targets = binding.get().getRouteTargets().getRouteTarget() + for(RouteTarget target : targets) { + routeTarget = target.getGlobalRouteTarget() + routeRole = target.getRouteTargetRole() + routeTargets += "" + '\n' + + " " + routeTarget + "" + '\n' + + " " + routeRole + "" + '\n' + + "" + '\n' + } } - } - } // end loop + } // end loop - execution.setVariable(Prefix + "routeCollection", routeTargets) - msoLogger.debug(Prefix + "routeCollection - " + '\n' + routeTargets) + execution.setVariable(Prefix + "routeCollection", routeTargets) + msoLogger.debug(Prefix + "routeCollection - " + '\n' + routeTargets) - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") - AaiUtil aaiUriUtil = new AaiUtil(this) - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ """ - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "routeCollection", "") - msoLogger.debug(" No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "routeCollection", "") + msoLogger.debug(" No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } } catch (NotFoundException e) { @@ -746,111 +632,62 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { msoLogger.debug(" ***** Inside callRESTQueryAAINetworkPolicy() of DoCreateNetworkInstance ***** " ) try { - // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse").replace('', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) - - // Check if Network Policy is present, then build a List of network policy - List networkPolicyUriList = networkUtils.getNetworkPolicyObject(relationship) - int networkPolicyCount = networkPolicyUriList.size() - execution.setVariable(Prefix + "networkPolicyCount", networkPolicyCount) - msoLogger.debug(Prefix + "networkPolicyCount - " + networkPolicyCount) + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, execution.getVariable(Prefix + "networkId")) + Optional relationships = client.get(uri, NotFoundException.class).getRelationships() + if(relationships.isPresent()){ + List uris = relationships.get().getRelatedAAIUris(AAIObjectType.NETWORK_POLICY) - AaiUtil aaiUriUtil = new AaiUtil(this) + execution.setVariable(Prefix + "networkPolicyCount", uris.size()) + msoLogger.debug(Prefix + "networkPolicyCount - " + uris.size()) - if (networkPolicyCount > 0) { - execution.setVariable(Prefix + "networkPolicyUriList", networkPolicyUriList) - msoLogger.debug(" networkPolicyUri List - " + networkPolicyUriList) + if (uris.size() > 0) { - String networkPolicies = "" - // AII loop call using list vpnBindings - for (i in 0..networkPolicyUriList.size()-1) { + String networkPolicies = "" + // AII loop call using list vpnBindings + for(AAIResourceUri u : uris) { - int counting = i+1 + NetworkPolicy p = client.get(u, NotFoundException.class).asBean(NetworkPolicy.class).get() - // Note: By default, the network policy url is found in 'related-link' of the response, - // so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping. + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") - URI uri = UriBuilder.fromUri(networkPolicyUriList[i]).build() + String networkPolicy = p.getNetworkPolicyFqdn() + networkPolicies += "" + networkPolicy + "" + '\n' - AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.NETWORK_POLICY, uri) - aaiUri.depth(Depth.ALL) - String queryNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(aaiUri) + } // end loop - execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest", queryNetworkPolicyAAIRequest) - msoLogger.debug(Prefix + "queryNetworkPolicyAAIRequest, , NetworkPolicy #" + counting + " : " + "\n" + queryNetworkPolicyAAIRequest) + execution.setVariable(Prefix + "networkCollection", networkPolicies) + msoLogger.debug(Prefix + "networkCollection - " + '\n' + networkPolicies) - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", returnCode) - msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) - - String aaiResponseAsString = response.getResponseBodyAsString() - - if (returnCode=='200') { - execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiResponseAsString) - msoLogger.debug(" QueryAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) - - String networkPolicy = "" - if (utils.nodeExists(aaiResponseAsString, "network-policy-fqdn")) { - networkPolicy = utils.getNodeText(aaiResponseAsString, "network-policy-fqdn") - networkPolicies += "" + networkPolicy + "" + '\n' - } - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from QueryAAINetworkPolicy - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } - - } // end loop - - execution.setVariable(Prefix + "networkCollection", networkPolicies) - msoLogger.debug(Prefix + "networkCollection - " + '\n' + networkPolicies) - - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ """ - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "networkCollection", "") - msoLogger.debug(" No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "networkCollection", "") + msoLogger.debug(" No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - } catch (BpmnError e) { - throw e; - - } catch (Exception ex) { - String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkPolicy() - " + ex.getMessage() - msoLogger.debug(exceptionMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkPolicy() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } + } } @@ -861,103 +698,57 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { msoLogger.debug(" ***** Inside callRESTQueryAAINetworkTableRef() of DoCreateNetworkInstance ***** " ) try { - // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse").replace('', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) - - // Check if Network TableREf is present, then build a List of network policy - List networkTableRefUriList = networkUtils.getNetworkTableRefObject(relationship) - int networkTableRefCount = networkTableRefUriList.size() - execution.setVariable(Prefix + "networkTableRefCount", networkTableRefCount) - msoLogger.debug(Prefix + "networkTableRefCount - " + networkTableRefCount) - String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) - AaiUtil aaiUriUtil = new AaiUtil(this) + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, execution.getVariable(Prefix + "networkId")) + Optional relationships = client.get(uri, NotFoundException.class).getRelationships() + if(relationships.isPresent()){ + List uris = relationships.get().getRelatedAAIUris(AAIObjectType.ROUTE_TABLE_REFERENCE) - if (networkTableRefCount > 0) { - execution.setVariable(Prefix + "networkTableRefUriList", networkTableRefUriList) - msoLogger.debug(" networkTableRefUri List - " + networkTableRefUriList) + execution.setVariable(Prefix + "networkTableRefCount", uris.size()) + msoLogger.debug(Prefix + "networkTableRefCount - " + uris.size()) - // AII loop call using list vpnBindings - String networkTableRefs = "" - for (i in 0..networkTableRefUriList.size()-1) { - int counting = i+1 + if (uris.size() > 0) { - // prepare url using tableRef - URI uri = UriBuilder.fromUri(networkTableRefUriList[i]).build() + // AII loop call using list vpnBindings + String networkTableRefs = "" + for(AAIResourceUri u : uris) { - AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ROUTE_TABLE_REFERENCE, uri) - aaiUri.depth(Depth.ALL) - String queryNetworkTableRefAAIRequest = aaiUriUtil.createAaiUri(aaiUri) + RouteTableReference rt = client.get(u, NotFoundException.class).asBean(RouteTableReference.class).get() - execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest", queryNetworkTableRefAAIRequest) - msoLogger.debug(Prefix + "queryNetworkTableRefAAIRequest, , NetworkTableRef #" + counting + " : " + "\n" + queryNetworkTableRefAAIRequest) + String networkTableRef = rt.getRouteTableReferenceFqdn() + networkTableRefs += "" + networkTableRef + "" + '\n' - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkTableRefAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", returnCode) - msoLogger.debug(" ***** AAI query network Table Reference Response Code, NetworkTableRef #" + counting + " : " + returnCode) - - String aaiResponseAsString = response.getResponseBodyAsString() - - if (returnCode=='200') { - execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiResponseAsString) - msoLogger.debug(" QueryAAINetworkTableRef Success REST Response, , NetworkTableRef #" + counting + " : " + "\n" + aaiResponseAsString) - - String networkTableRef = "" - if (utils.nodeExists(aaiResponseAsString, "route-table-reference-fqdn")) { - networkTableRef = utils.getNodeText(aaiResponseAsString, "route-table-reference-fqdn") - networkTableRefs += "" + networkTableRef + "" + '\n' - } - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from QueryAAINetworkTableRef - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } - } // end loop + } // end loop - execution.setVariable(Prefix + "tableRefCollection", networkTableRefs) - msoLogger.debug(Prefix + "tableRefCollection - " + '\n' + networkTableRefs) + execution.setVariable(Prefix + "tableRefCollection", networkTableRefs) + msoLogger.debug(Prefix + "tableRefCollection - " + '\n' + networkTableRefs) - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ """ - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "tableRefCollection", "") - msoLogger.debug(" No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "tableRefCollection", "") + msoLogger.debug(" No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } - } catch (BpmnError e) { - throw e; + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkTableRef() - " + ex.getMessage() @@ -978,75 +769,86 @@ public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { try { // get variables String networkId = execution.getVariable(Prefix + "networkId") - networkId = UriUtils.encode(networkId,"UTF-8") String requeryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") String createNetworkResponse = execution.getVariable(Prefix + "createNetworkResponse") - // Prepare url - AaiUtil aaiUriUtil = new AaiUtil(this) - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) - uri.depth(Depth.ALL) - String updateContrailAAIUrlRequest = aaiUriUtil.createAaiUri(uri) - - execution.setVariable(Prefix + "updateContrailAAIUrlRequest", updateContrailAAIUrlRequest) - msoLogger.debug(Prefix + "updateContrailAAIUrlRequest - " + "\n" + updateContrailAAIUrlRequest) - - //Prepare payload (PUT) - String schemaVersion = aaiUriUtil.getNamespaceFromUri(updateContrailAAIUrlRequest) - String payload = networkUtils.ContrailNetworkCreatedUpdate(requeryIdAAIResponse, createNetworkResponse, schemaVersion) - String payloadXml = utils.formatXml(payload) - execution.setVariable(Prefix + "updateContrailAAIPayloadRequest", payloadXml) - msoLogger.debug(" 'payload' to Update Contrail - " + "\n" + payloadXml) - - APIResponse response = aaiUriUtil.executeAAIPutCall(execution, updateContrailAAIUrlRequest, payloadXml) - - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", returnCode) - msoLogger.debug(" ***** AAI Update Contrail Response Code : " + returnCode) - String aaiUpdateContrailResponseAsString = response.getResponseBodyAsString() - if (returnCode=='200') { - execution.setVariable(Prefix + "updateContrailAAIResponse", aaiUpdateContrailResponseAsString) - msoLogger.debug(" AAI Update Contrail Success REST Response - " + "\n" + aaiUpdateContrailResponseAsString) - // Point-of-no-return is set to false, rollback not needed. - String rollbackEnabled = execution.getVariable(Prefix + "rollbackEnabled") - if (rollbackEnabled == "true") { - execution.setVariable(Prefix + "isPONR", false) - } else { - execution.setVariable(Prefix + "isPONR", true) + L3Network l3Network = new L3Network() + if (utils.nodeExists(requeryIdAAIResponse, 'heat-stack-id')) { + } else { + if (utils.nodeExists(createNetworkResponse, 'networkStackId')) { + l3Network.setHeatStackId(utils.getNodeText(createNetworkResponse, 'networkStackId')) } - msoLogger.debug(Prefix + "isPONR" + ": " + execution.getVariable(Prefix + "isPONR")) + } + if (utils.nodeExists(requeryIdAAIResponse, 'neutron-network-id')) { } else { - if (returnCode=='404') { - String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + if (utils.nodeExists(createNetworkResponse, 'neutronNetworkId')) { + l3Network.setNeutronNetworkId(utils.getNodeText(createNetworkResponse, 'neutronNetworkId')) + } + } + if (utils.nodeExists(requeryIdAAIResponse, 'contrail-network-fqdn')) { + } else { + if (utils.nodeExists(createNetworkResponse, 'networkFqdn')) { + l3Network.setContrailNetworkFqdn(utils.getNodeText(createNetworkResponse, 'networkFqdn')) + } + } - } else { - if (aaiUpdateContrailResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiUpdateContrailResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String errorMessage = "Unexpected Response from UpdateContrailAAINetwork - " + returnCode - msoLogger.debug(errorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) - } + String status = utils.getNodeText(createNetworkResponse, 'orchestration-status') + if(status.equals("pending-create") || status.equals("PendingCreate")){ + l3Network.setOperationalStatus("Created") + }else{ + l3Network.setOperationalStatus("Active") + } + + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) + client.update(uri, l3Network) + + String subnetsXml = utils.getNodeXml(requeryIdAAIResponse, "subnets") + InputSource source = new InputSource(new StringReader(subnetsXml)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true) + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document xml = docBuilder.parse(source) + NodeList nodeList = xml.getElementsByTagNameNS("*", "subnet") + for (int x = 0; x < nodeList.getLength(); x++) { + Node node = nodeList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + String subnetOrchStatus = eElement.getElementsByTagNameNS("*", "orchestration-status").item(0).getTextContent() + String subnetId = eElement.getElementsByTagNameNS("*", "subnet-id").item(0).getTextContent() + Subnet subnet = new Subnet() + String neutronSubnetId = networkUtils.extractNeutSubId(createNetworkResponse, subnetId) + subnet.setNeutronSubnetId(neutronSubnetId) + if(subnetOrchStatus.equals("pending-create") || subnetOrchStatus.equals("PendingCreate") ){ + subnet.setOrchestrationStatus("Created") + }else{ + subnet.setOrchestrationStatus("Active") + } + + AAIResourceUri subUri = AAIUriFactory.createResourceUri(AAIObjectType.SUBNET, networkId, subnetId) + client.update(subUri, subnet) } } + String rollbackEnabled = execution.getVariable(Prefix + "rollbackEnabled") + if (rollbackEnabled == "true") { + execution.setVariable(Prefix + "isPONR", false) + } else { + execution.setVariable(Prefix + "isPONR", true) + } + msoLogger.debug(Prefix + "isPONR" + ": " + execution.getVariable(Prefix + "isPONR")) + } catch (BpmnError e) { throw e; - + } catch (NotFoundException e) { + String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTUpdateContrailAAINetwork() - " + ex.getMessage() msoLogger.debug(exceptionMessage) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } - } public void prepareCreateNetworkRequest (DelegateExecution execution) { diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy index 7e00f05b90..1d75d399ee 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,6 +25,7 @@ import groovy.xml.XmlUtil import groovy.json.* import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient import org.onap.so.logger.MsoLogger import org.onap.so.logger.MessageEnum @@ -34,12 +35,10 @@ import org.onap.so.bpmn.common.scripts.NetworkUtils import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import org.onap.so.bpmn.common.scripts.VidUtils import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.utils.TargetEntity import java.util.UUID; - +import javax.ws.rs.core.Response import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution import org.apache.commons.lang3.* @@ -61,7 +60,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() def className = getClass().getSimpleName() - + /** * This method is executed during the preProcessRequest task of the DoCreateNetworkInstanceRollback.bpmn process. * @param execution @@ -73,7 +72,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso execution.setVariable(Prefix + "rollbackSDNCRequest", null) execution.setVariable(Prefix + "rollbackActivateSDNCRequest", null) execution.setVariable(Prefix + "WorkflowException", null) - + execution.setVariable(Prefix + "rollbackNetworkRequest", "") execution.setVariable(Prefix + "rollbackNetworkResponse", "") execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") @@ -81,7 +80,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso execution.setVariable(Prefix + "rollbackSDNCRequest", "") execution.setVariable(Prefix + "rollbackSDNCResponse", "") execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") - + execution.setVariable(Prefix + "rollbackActivateSDNCRequest", "") execution.setVariable(Prefix + "rollbackActivateSDNCResponse", "") execution.setVariable(Prefix + "rollbackActivateSDNCReturnCode", "") @@ -103,18 +102,18 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso public void preProcessRequest (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") execution.setVariable("prefix",Prefix) - + msoLogger.trace("Inside preProcessRequest() of " + className + ".groovy") try { // initialize flow variables InitializeProcessVariables(execution) - + // GET Incoming request/variables String rollbackNetworkRequest = null String rollbackSDNCRequest = null String rollbackActivateSDNCRequest = null - + // Partial Rollback Map rollbackData = execution.getVariable("rollbackData") if (rollbackData != null && rollbackData instanceof Map) { @@ -122,7 +121,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso if(rollbackData.containsKey("rollbackSDNCRequest")) { rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] } - + if(rollbackData.containsKey("rollbackNetworkRequest")) { rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] } @@ -130,14 +129,14 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso if(rollbackData.containsKey("rollbackActivateSDNCRequest")) { rollbackActivateSDNCRequest = rollbackData["rollbackActivateSDNCRequest"] } - + } - + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) execution.setVariable(Prefix + "rollbackActivateSDNCRequest", rollbackActivateSDNCRequest) msoLogger.debug("'rollbackData': " + '\n' + execution.getVariable("rollbackData")) - + String sdncVersion = execution.getVariable("sdncVersion") msoLogger.debug("sdncVersion? : " + sdncVersion) @@ -147,7 +146,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution)) execution.setVariable("BasicAuthHeaderValuePO",encodedString) execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) - + } catch (IOException ex) { String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() @@ -168,88 +167,80 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso } else { // called by: Macro - Full Rollback, WorkflowException = null execution.setVariable(Prefix + "fullRollback", true) - + } msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) - - + + } catch (BpmnError e) { throw e; - + } catch (Exception ex) { // caught exception String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() msoLogger.debug(exceptionMessage) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - + } } - + public void callPONetworkAdapter (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") execution.setVariable("prefix",Prefix) msoLogger.trace("Inside callPONetworkAdapter() of " + className + "") - + try { String poUrl = UrnPropertiesReader.getVariable("mso.adapters.network.rest.endpoint",execution) String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") String networkId = utils.getNodeText(rollbackSDNCRequest, "network-id") - + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") String urlRollbackPoNetwork = poUrl+ "/" + networkId + "/rollback" msoLogger.debug("'urlRollbackPoNetwork': " + urlRollbackPoNetwork) execution.setVariable(Prefix + "urlRollbackPoNetwork", urlRollbackPoNetwork) - RESTConfig config = new RESTConfig(urlRollbackPoNetwork) - RESTClient client = new RESTClient(config). - addHeader("Content-Type", "application/xml"). - addAuthorizationHeader(execution.getVariable("BasicAuthHeaderValuePO")); - - APIResponse response = client.httpDelete(rollbackNetworkRequest) - String responseCode = response.getStatusCode() - String responseBody = response.getResponseBodyAsString() - - execution.setVariable(Prefix + "rollbackNetworkReturnCode", responseCode) - execution.setVariable(Prefix + "rollbackNetworkResponse", responseBody) - - msoLogger.debug(" Network Adapter rollback responseCode: " + responseCode) - msoLogger.debug(" Network Adapter rollback responseBody: " + responseBody) - - + URL url = new URL(urlRollbackPoNetwork) + HttpClient httpClient = new HttpClient(url, "application/xml", TargetEntity.OPENSTACK_ADAPTER) + httpClient.addAdditionalHeader("Authorization", execution.getVariable("BasicAuthHeaderValuePO")) + Response response = httpClient.delete(rollbackNetworkRequest) + + execution.setVariable(Prefix + "rollbackNetworkReturnCode", response.getStatus()) + + msoLogger.debug(" Network Adapter rollback responseCode: " + response.getStatus()) + + } catch (Exception ex) { String exceptionMessage = "Exception Encountered in callPONetworkAdapter() of DoCreateNetworkInstanceRollback flow - " + ex.getMessage() msoLogger.debug(exceptionMessage) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) } - + } - - + + public void validateRollbackResponses (DelegateExecution execution) { def isDebugEnabled=execution.getVariable("isDebugLogEnabled") execution.setVariable("prefix",Prefix) msoLogger.trace("Inside validateRollbackResponses() of DoCreateNetworkInstanceRollback") - + try { // validate PO network rollback response String rollbackNetworkErrorMessages = "" String rollbackNetworkReturnCode = "200" if (execution.getVariable(Prefix + "rollbackNetworkRequest") != null) { rollbackNetworkReturnCode = execution.getVariable(Prefix + "rollbackNetworkReturnCode") - String rollbackNetworkResponse = execution.getVariable(Prefix + "rollbackNetworkResponse") msoLogger.debug(" NetworkRollback Code - " + rollbackNetworkReturnCode) - msoLogger.debug(" NetworkRollback Response - " + rollbackNetworkResponse) if (rollbackNetworkReturnCode != "200") { rollbackNetworkErrorMessages = " + PO Network rollback failed. " } else { rollbackNetworkErrorMessages = " + PO Network rollback completed." } } - + // validate SDNC rollback response String rollbackSdncErrorMessages = "" String rollbackSDNCReturnCode = "200" @@ -270,13 +261,13 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso } } else { rollbackSdncErrorMessages = " + SNDC assign rollback completed." - } + } } else { rollbackSdncErrorMessages = " + SDNC assign rollback failed. " } msoLogger.debug(" SDNC assign rollback Code - " + rollbackSDNCReturnCode) msoLogger.debug(" SDNC assign rollback Response - " + rollbackSDNCResponse) - } + } // validate SDNC activate rollback response String rollbackActivateSdncErrorMessages = "" @@ -303,15 +294,15 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso } msoLogger.debug(" SDNC activate rollback Code - " + rollbackActivateSDNCReturnCode) msoLogger.debug(" SDNC activate rollback Response - " + rollbackActivateSDNCResponse) - } + } String statusMessage = "" int errorCode = 7000 msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) - if (execution.getVariable(Prefix + "fullRollback") == false) { - // original WorkflowException, - WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") + if (execution.getVariable(Prefix + "fullRollback") == false) { + // original WorkflowException, + WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") if (wfe != null) { // rollback due to failure in DoCreate - Partial rollback statusMessage = wfe.getErrorMessage() @@ -325,7 +316,7 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200" && rollbackActivateSDNCReturnCode == "200") { execution.setVariable("rolledBack", true) execution.setVariable("wasDeleted", true) - + } else { execution.setVariable("rolledBack", false) execution.setVariable("wasDeleted", true) @@ -336,8 +327,8 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso String processKey = getProcessKey(execution); WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); execution.setVariable("workflowException", exception); - - } else { + + } else { // rollback due to failures in Main flow (Macro) - Full rollback // WorkflowException = null if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200" && rollbackActivateSDNCReturnCode == "200") { @@ -351,9 +342,9 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) throw new BpmnError("MSOWorkflowException") } - - } - + + } + } catch (Exception ex) { String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." @@ -370,18 +361,18 @@ public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcesso // ******************************* - + public void processJavaException(DelegateExecution execution){ def isDebugEnabled=execution.getVariable("isDebugLogEnabled") execution.setVariable("prefix",Prefix) - + try{ msoLogger.debug("Caught a Java Exception in " + Prefix) msoLogger.debug("Started processJavaException Method") msoLogger.debug("Variables List: " + execution.getVariables()) execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") - + }catch(Exception e){ msoLogger.debug("Caught Exception during processJavaException Method: " + e) execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy index 08dc38cd2a..4bda803da0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy @@ -48,7 +48,7 @@ import org.onap.so.client.aai.entities.uri.AAIUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse + import groovy.json.* @@ -278,7 +278,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { if (siParamsXml == null) siParamsXml = "" execution.setVariable("siParamsXml", siParamsXml) - + } catch (BpmnError e) { throw e; } catch (Exception ex){ @@ -323,7 +323,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { { oStatus = "Created" } - + //QUERY CATALOG DB AND GET WORKLOAD / ENVIRONMENT CONTEXT String environmentContext = "" String workloadContext ="" @@ -345,7 +345,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { msoLogger.debug(msg) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) } - + org.onap.aai.domain.yang.ServiceInstance si = new org.onap.aai.domain.yang.ServiceInstance() si.setServiceInstanceName(execution.getVariable("serviceInstanceName")) si.setServiceType(serviceType) @@ -354,7 +354,7 @@ public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { si.setModelInvariantId(modelInvariantUuid) si.setModelVersionId(execution.getVariable("modelUuid")) si.setEnvironmentContext(environmentContext) - si.setWorkloadContext(workloadContext) + si.setWorkloadContext(workloadContext) AAIResourcesClient client = new AAIResourcesClient() AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("subscriptionServiceType"), serviceInstanceId) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy index dd56b8f2cc..e80941e212 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,9 +30,6 @@ import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import org.onap.so.bpmn.core.RollbackData import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.onap.so.logger.MsoLogger import org.onap.so.logger.MessageEnum @@ -57,7 +54,7 @@ import org.springframework.web.util.UriUtils; * rollbackAAI * rollbackSDNC * sdncRollbackRequest - * + * * * Outputs: * @param - rollbackError @@ -66,7 +63,7 @@ import org.springframework.web.util.UriUtils; */ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcessor{ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateServiceInstanceRollback.class); - + String Prefix="DCRESIRB_" @@ -141,7 +138,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso } public void validateSDNCResponse(DelegateExecution execution, String response, String method) { - + msoLogger.trace("validateSDNCResponse") String msg = "" try { @@ -149,7 +146,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") msoLogger.debug("SDNCResponse: " + response) msoLogger.debug("workflowException: " + workflowException) - + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) @@ -174,7 +171,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso } public void postProcessRequest(DelegateExecution execution) { - + msoLogger.trace("postProcessRequest") String msg = "" try { @@ -208,7 +205,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso } public void processRollbackException(DelegateExecution execution){ - + msoLogger.trace("processRollbackException") try{ msoLogger.debug("Caught an Exception in DoCreateServiceInstanceRollback") @@ -226,7 +223,7 @@ public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcesso } public void processRollbackJavaException(DelegateExecution execution){ - + msoLogger.trace("processRollbackJavaException") try{ execution.setVariable("rollbackData", null) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy index 2663ba7aa7..a3c30dcb50 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,19 +23,19 @@ package org.onap.so.bpmn.infrastructure.scripts import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory; -import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil -import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.client.HttpClient import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig + +import org.onap.so.utils.TargetEntity import groovy.json.* +import javax.ws.rs.core.Response /** * This groovy class supports the DoCreateVFCNetworkServiceInstance.bpmn process. @@ -45,9 +45,9 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVFCNetworkServiceInstance.class); String vfcUrl = "/vfc/rest/v1/vfcadapter" - + String host = "http://mso.mso.testlab.openecomp.org:8080" - + ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -99,7 +99,7 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces }""" execution.setVariable("nsOperationKey", nsOperationKey); execution.setVariable("nsParameters", nsParameters) - + } catch (BpmnError e) { throw e; @@ -126,9 +126,9 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces "nsOperationKey":${nsOperationKey}, "nsParameters":${nsParameters} }""" - APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String nsInstanceId = ""; if(returnCode== "200" || returnCode == "201"){ nsInstanceId = jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId") @@ -154,9 +154,9 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces }""" String nsInstanceId = execution.getVariable("nsInstanceId") String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate" - APIResponse apiResponse = postRequest(execution, url, reqBody) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, url, reqBody) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String jobId = ""; if(returnCode== "200"|| returnCode == "201"){ jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId") @@ -173,9 +173,9 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces String jobId = execution.getVariable("jobId") String nsOperationKey = execution.getVariable("nsOperationKey"); String url = host + vfcUrl + "/jobs/" + jobId - APIResponse apiResponse = postRequest(execution, url, nsOperationKey) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String operationStatus = "error" if(returnCode== "200"|| returnCode == "201"){ operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status") @@ -185,12 +185,12 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces } /** - * delay 5 sec + * delay 5 sec */ public void timeDelay(DelegateExecution execution) { try { Thread.sleep(5000); - } catch(InterruptedException e) { + } catch(InterruptedException e) { msoLogger.debug("Time Delay exception" + e ) } } @@ -226,20 +226,26 @@ public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProces * url: the url of the request * requestBody: the body of the request */ - private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){ + private Response postRequest(DelegateExecution execution, String urlString, String requestBody){ msoLogger.trace("Started Execute VFC adapter Post Process") - msoLogger.debug("url:"+url +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null + msoLogger.debug("url:"+urlString +"\nrequestBody:"+ requestBody) + Response apiResponse = null try{ - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk"); - apiResponse = client.httpPost(requestBody) - msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) + + URL url = new URL(urlString); + + HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk") + + apiResponse = httpClient.post(requestBody) + + msoLogger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class)) msoLogger.trace("Completed Execute VF-C adapter Post Process") }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); throw new BpmnError("MSOWorkflowException") - } + } return apiResponse } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy index 6917a97887..50fe75e3df 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy @@ -20,6 +20,8 @@ package org.onap.so.bpmn.infrastructure.scripts +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory @@ -42,6 +44,8 @@ import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.DecomposeJsonUtil import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.graphinventory.entities.uri.Depth +import org.onap.so.client.HttpClient import org.onap.so.client.aai.AAIObjectPlurals import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient @@ -53,9 +57,9 @@ import org.onap.so.client.graphinventory.entities.uri.Depth import org.onap.so.constants.Defaults import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig + +import org.onap.so.utils.TargetEntity +import org.springframework.web.util.UriUtils import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.NamedNodeMap @@ -638,28 +642,26 @@ public class DoCreateVfModule extends VfModuleBase { String endPoint = aaiUriUtil.createAaiUri(uri) try { - RESTConfig config = new RESTConfig(endPoint); - def responseData = '' - def aaiRequestId = UUID.randomUUID().toString() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', aaiRequestId). - addHeader('X-FromAppId', 'MSO'). - addHeader('Content-Type', 'application/xml'). - addHeader('Accept','application/xml'); + HttpClient client = new HttpClient(new URL(endPoint), MediaType.APPLICATION_XML, TargetEntity.AAI) + client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString()) + client.addAdditionalHeader('X-FromAppId', 'MSO') + client.addAdditionalHeader('Content-Type', MediaType.APPLICATION_XML) + client.addAdditionalHeader('Accept', MediaType.APPLICATION_XML) + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - APIResponse response = client.httpGet() + Response response = client.get() - responseData = response.getResponseBodyAsString() + String responseData = response.readEntity(String.class) if (responseData != null) { msoLogger.debug("Received generic VNF data: " + responseData) } - execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatus()) execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response code:' + response.getStatus()) msoLogger.debug('Response:' + System.lineSeparator() + responseData) - if (response.getStatusCode() == 200) { + if (response.getStatus() == 200) { // Parse the VNF record from A&AI to find base module info msoLogger.debug('Parsing the VNF data to find base module info') if (responseData != null) { @@ -722,31 +724,31 @@ public class DoCreateVfModule extends VfModuleBase { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, vnfId).queryParam("vf-module-name",vfModuleName) String endPoint = aaiUriUtil.createAaiUri(uri) + HttpClient client = new HttpClient(new URL(endPoint), MediaType.APPLICATION_XML, TargetEntity.AAI) + client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString()) + client.addAdditionalHeader('X-FromAppId', 'MSO') + client.addAdditionalHeader('Content-Type', MediaType.APPLICATION_XML) + client.addAdditionalHeader('Accept', MediaType.APPLICATION_XML) + try { - RESTConfig config = new RESTConfig(endPoint); def responseData = '' - def aaiRequestId = UUID.randomUUID().toString() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', aaiRequestId). - addHeader('X-FromAppId', 'MSO'). - addHeader('Content-Type', 'application/xml'). - addHeader('Accept','application/xml'); + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - APIResponse response = client.httpGet() + Response response = client.get() msoLogger.debug("createVfModule - invoking httpGet() to AAI") - responseData = response.getResponseBodyAsString() + responseData = response.readEntity(String.class) if (responseData != null) { msoLogger.debug("Received generic VNF data: " + responseData) } - execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponseCode', response.getStatusCode()) + execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponseCode', response.getStatus()) execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response code:' + response.getStatus()) msoLogger.debug('Response:' + System.lineSeparator() + responseData) // Retrieve VF Module info and its orchestration status; if not found, do nothing - if (response.getStatusCode() == 200) { + if (response.getStatus() == 200) { // Parse the VNF record from A&AI to find base module info msoLogger.debug('Parsing the VNF data to find orchestration status') if (responseData != null) { @@ -1883,7 +1885,6 @@ public class DoCreateVfModule extends VfModuleBase { } catch (BpmnError e) { throw e; - } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoCreateVfModule flow. createNetworkPoliciesInAAI() - " + ex.getMessage() msoLogger.debug(exceptionMessage) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy index 38858d20f7..55a84575f4 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -36,7 +36,7 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse + import org.springframework.web.util.UriUtils import javax.ws.rs.NotFoundException @@ -44,7 +44,7 @@ import javax.ws.rs.NotFoundException public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVfModuleRollback.class); - + def Prefix="DCVFMR_" ExceptionUtil exceptionUtil = new ExceptionUtil() @@ -55,7 +55,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // parse the incoming DELETE_VF_MODULE request for the Generic Vnf and Vf Module Ids // and formulate the outgoing request for PrepareUpdateAAIVfModuleRequest public void preProcessRequest(DelegateExecution execution) { - + initProcessVariables(execution) @@ -63,10 +63,10 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ execution.setVariable("rolledBack", null) execution.setVariable("rollbackError", null) - + def rollbackData = execution.getVariable("rollbackData") msoLogger.debug("RollbackData:" + rollbackData) - + if (rollbackData != null) { String vnfId = rollbackData.get("VFMODULE", "vnfid") execution.setVariable("DCVFMR_vnfId", vnfId) @@ -106,9 +106,9 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ createdNetworkPolicyFqdnList.add(fqdn) msoLogger.debug("got fqdn # " + i + ": " + fqdn) i = i + 1 - + } - + execution.setVariable("DCVFMR_createdNetworkPolicyFqdnList", createdNetworkPolicyFqdnList) String oamManagementV4Address = rollbackData.get("VFMODULE", "oamManagementV4Address") execution.setVariable("DCVFMR_oamManagementV4Address", oamManagementV4Address) @@ -124,7 +124,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ execution.setVariable("DCVFMR_rollbackCreateAAIVfModule", rollbackData.get("VFMODULE", "rollbackCreateAAIVfModule")) execution.setVariable("DCVFMR_rollbackCreateNetworkPoliciesAAI", rollbackData.get("VFMODULE", "rollbackCreateNetworkPoliciesAAI")) execution.setVariable("DCVFMR_rollbackUpdateVnfAAI", rollbackData.get("VFMODULE", "rollbackUpdateVnfAAI")) - + // formulate the request for PrepareUpdateAAIVfModule String request = """ ${MsoUtils.xmlEscape(vnfId)} @@ -136,11 +136,11 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ } else { execution.setVariable("skipRollback", true) } - + if (execution.getVariable("disableRollback").equals("true" )) { execution.setVariable("skipRollback", true) } - + } catch (BpmnError e) { throw e; } catch (Exception ex){ @@ -153,14 +153,14 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // build a SDNC vnf-topology-operation request for the specified action // (note: the action passed is expected to be 'changedelete' or 'delete') public void prepSDNCAdapterRequest(DelegateExecution execution) { - + String srvInstId = execution.getVariable("DCVFMR_serviceInstanceId") String uuid = execution.getVariable('testReqId') // for junits if(uuid==null){ uuid = execution.getVariable("DCVFMR_requestId") + "-" + System.currentTimeMillis() } - + def callbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) String source = execution.getVariable("DCVFMR_source") @@ -243,21 +243,21 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ } public void preProcessSDNCDeactivateRequest(DelegateExecution execution){ - + execution.setVariable("prefix", Prefix) msoLogger.trace("STARTED preProcessSDNCDeactivateRequest") - + def serviceInstanceId = execution.getVariable("DCVFMR_serviceInstanceId") - + try{ //Build SDNC Request - + String deactivateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "deactivate") - + deactivateSDNCRequest = utils.formatXml(deactivateSDNCRequest) execution.setVariable("DCVFMR_deactivateSDNCRequest", deactivateSDNCRequest) msoLogger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) - + }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessSDNCDeactivateRequest.", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) @@ -275,12 +275,12 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ msoLogger.trace("STARTED preProcessSDNCUnassignRequest Process") try{ String serviceInstanceId = execution.getVariable("DCVFMR_serviceInstanceId") - + String unassignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "unassign") - + execution.setVariable("DCVFMR_unassignSDNCRequest", unassignSDNCRequest) msoLogger.debug("Outgoing UnassignSDNCRequest is: \n" + unassignSDNCRequest) - + }catch(Exception e){ msoLogger.debug("Exception Occured Processing preProcessSDNCUnassignRequest. Exception is:\n" + e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCUnassignRequest Method:\n" + e.getMessage()) @@ -289,7 +289,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ } public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){ - + String uuid = execution.getVariable('testReqId') // for junits if(uuid==null){ uuid = execution.getVariable("DCVFMR_requestId") + "-" + System.currentTimeMillis() @@ -301,9 +301,9 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ def vfModuleId = execution.getVariable("DCVFMR_vfModuleId") def source = execution.getVariable("DCVFMR_source") def vnfId = execution.getVariable("DCVFMR_vnfId") - + def sdncVersion = execution.getVariable("sdncVersion") - + String sdncRequest = """ - + ${MsoUtils.xmlEscape(serviceInstanceId)} ${MsoUtils.xmlEscape(vnfId)} - + ${MsoUtils.xmlEscape(vfModuleId)} - + """ - + msoLogger.debug("sdncRequest: " + sdncRequest) return sdncRequest } - + // parse the incoming DELETE_VF_MODULE request // and formulate the outgoing VnfAdapterDeleteV1 request public void prepVNFAdapterRequest(DelegateExecution execution) { - + String requestId = UUID.randomUUID().toString() String origRequestId = execution.getVariable("DCVFMR_requestId") String srvInstId = execution.getVariable("DCVFMR_serviceInstanceId") @@ -390,7 +390,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // parse the incoming DELETE_VF_MODULE request // and formulate the outgoing UpdateAAIVfModuleRequest request public void prepUpdateAAIVfModule(DelegateExecution execution) { - + String vnfId = execution.getVariable("DCVFMR_vnfId") String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") // formulate the request for UpdateAAIVfModule @@ -403,11 +403,11 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ msoLogger.debug("UpdateAAIVfModuleRequest :" + request) execution.setVariable("UpdateAAIVfModuleRequest", request) } - + // parse the incoming DELETE_VF_MODULE request // and formulate the outgoing UpdateAAIVfModuleRequest request public void prepUpdateAAIVfModuleToAssigned(DelegateExecution execution) { - + String vnfId = execution.getVariable("DCVFMR_vnfId") String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") // formulate the request for UpdateAAIVfModule @@ -424,7 +424,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // parse the incoming DELETE_VF_MODULE request // and formulate the outgoing DeleteAAIVfModuleRequest request public void prepDeleteAAIVfModule(DelegateExecution execution) { - + String vnfId = execution.getVariable("DCVFMR_vnfId") String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") // formulate the request for UpdateAAIVfModule @@ -439,7 +439,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ // generates a WorkflowException if // - public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { - + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "AAI error occurred deleting the Generic Vnf"+ execution.getVariable("DoDVfMod_deleteGenericVnfResponse"), "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError); String processKey = getProcessKey(execution); exceptionUtil.buildWorkflowException(execution, 5000, "Failure in DoDeleteVfModule") @@ -447,7 +447,7 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ } public void sdncValidateResponse(DelegateExecution execution, String response){ - + execution.setVariable("prefix",Prefix) WorkflowException workflowException = execution.getVariable("WorkflowException") @@ -603,35 +603,35 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessUpdateAAIGenericVnf((): ' + e.getMessage()) } } - + public void setSuccessfulRollbackStatus (DelegateExecution execution){ - + execution.setVariable("prefix", Prefix) msoLogger.trace("STARTED setSuccessfulRollbackStatus") - + try{ // Set rolledBack to true, rollbackError to null execution.setVariable("rolledBack", true) execution.setVariable("rollbackError", null) - + }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing setSuccessfulRollbackStatus.", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setSuccessfulRollbackStatus Method:\n" + e.getMessage()) } msoLogger.trace("COMPLETED setSuccessfulRollbackStatus") } - + public void setFailedRollbackStatus (DelegateExecution execution){ - + execution.setVariable("prefix", Prefix) msoLogger.trace("STARTED setFailedRollbackStatus") - + try{ // Set rolledBack to false, rollbackError to actual value, rollbackData to null execution.setVariable("rolledBack", false) execution.setVariable("rollbackError", 'Caught exception in DoCreateVfModuleRollback') execution.setVariable("rollbackData", null) - + }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing setFailedRollbackStatus.", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setFailedRollbackStatus Method:\n" + e.getMessage()) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy index 7e9b4f47ab..eab6fe05e7 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy @@ -37,7 +37,7 @@ import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse; + import org.springframework.web.util.UriUtils; import org.onap.so.client.aai.AAIResourcesClient import org.onap.so.client.aai.AAIObjectType diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy index 66bd1ece90..3630df00f4 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy @@ -21,6 +21,7 @@ package org.onap.so.bpmn.infrastructure.scripts import static org.apache.commons.lang3.StringUtils.*; +import javax.ws.rs.core.Response import javax.xml.parsers.DocumentBuilder import javax.xml.parsers.DocumentBuilderFactory @@ -36,8 +37,10 @@ import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.domain.Resource import org.onap.so.bpmn.core.domain.ServiceDecomposition -import org.onap.so.rest.APIResponse + +import org.onap.so.utils.TargetEntity import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient import org.springframework.web.util.UriUtils; import org.w3c.dom.Document import org.w3c.dom.Element @@ -207,7 +210,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { } execution.setVariable("serviceRelationShip", jArray.toString()) - + // //test(siData) // NodeList nodeList = serviceXml.getElementsByTagName("relationship") // JSONArray jArray = new JSONArray() @@ -276,8 +279,8 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { // } // // for SP-Partner // }else if (e.equals("sp-partner")){ -// -// } +// +// } // } // } // execution.setVariable("serviceRelationShip", jArray.toString()) @@ -311,16 +314,16 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { } utils.log("INFO"," *** Exit postProcessAAIGET *** ", isDebugEnabled) } - + private JSONObject getRelationShipData(node, isDebugEnabled){ JSONObject jObj = new JSONObject() - + def relation = utils.nodeToString(node) def rt = utils.getNodeText(relation, "related-to") - + def rl = utils.getNodeText(relation, "related-link") utils.log("INFO", "ServiceInstance Related NS/Configuration :" + rl, isDebugEnabled) - + def rl_datas = utils.getIdenticalChildren(node, "relationship-data") for(def rl_data : rl_datas) { def eKey = utils.getChildNodeText(rl_data, "relationship-key") @@ -398,7 +401,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { } private void generateRelatedResourceInfo(String response, JSONObject jObj){ - + def xml = new XmlSlurper().parseText(response) def rtn = xml.childNodes() while (rtn.hasNext()) { @@ -408,26 +411,29 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { jObj.put(key, value) } } - + private JSONObject getRelatedResourceInAAI (DelegateExecution execution, JSONObject jObj) { def isDebugEnabled = execution.getVariable("isDebugLogEnabled") - utils.log("INFO"," ***** Started getRelatedResourceInAAI *****", isDebugEnabled) - + utils.log("INFO"," ***** Started getRelatedResourceInAAI *****", isDebugEnabled) + AaiUtil aaiUriUtil = new AaiUtil() String aai_endpoint = execution.getVariable("URN_aai_endpoint") String urlLink = jObj.get("resourceLinkUrl") String serviceAaiPath = "${aai_endpoint}${urlLink}" - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceAaiPath) - int responseCode = response.getStatusCode() + + URL url = new URL(serviceAaiPath) + HttpClient client = new HttpClient(url, "application/xml", TargetEntity.AAI) + + + Response response = client.get() + int responseCode = response.getStatus() execution.setVariable(Prefix + "GeRelatedResourceResponseCode", responseCode) utils.log("DEBUG", " Get RelatedResource code is: " + responseCode, isDebugEnabled) - String aaiResponse = response.getResponseBodyAsString() - aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) - aaiResponse = aaiResponse.replaceAll("&", "&") + String aaiResponse = response.readEntity(String.class) execution.setVariable(Prefix + "GetRelatedResourceResponse", aaiResponse) - + //Process Response if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) //200 OK 201 CREATED 202 ACCEPTED @@ -435,9 +441,9 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { utils.log("DEBUG", "GET RelatedResource Received a Good Response", isDebugEnabled) execution.setVariable(Prefix + "SuccessIndicator", true) execution.setVariable(Prefix + "FoundIndicator", true) - + generateRelatedResourceInfo(aaiResponse, jObj) - + //get model-invariant-uuid and model-uuid String modelInvariantId = "" String modelUuid = "" @@ -447,19 +453,19 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { modelUuid = jObj.get("model-version-id") modelCustomizationId = jObj.get("model-customization-id") } - - jObj.put("modelInvariantId", modelInvariantId) - jObj.put("modelVersionId", modelUuid) + + jObj.put("modelInvariantId", modelInvariantId) + jObj.put("modelVersionId", modelUuid) jObj.put("modelCustomizationId", modelCustomizationId) } else { - utils.log("ERROR", "Get RelatedResource Received a Bad Response Code. Response Code is: " + responseCode, isDebugEnabled) + utils.log("ERROR", "Get RelatedResource Received a Bad Response Code. Response Code is: " + responseCode, isDebugEnabled) } - + utils.log("INFO", " ***** Exit getRelatedResourceInAAI *****", isDebugEnabled) - return jObj; - + return jObj; + } public void postDecomposeService(DelegateExecution execution) { @@ -491,7 +497,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { relationShipList.each { JSONObject obj = getRelatedResourceInAAI(execution, (JSONObject)it) - + for (Resource resource : deleteResourceList) { String modelName = resource.getModelInfo().getModelName() @@ -508,7 +514,7 @@ public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { } } } - } + } // only delete real existing resources execution.setVariable("deleteResourceList", deleteRealResourceList) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy index 1333c1f4c4..ca4643dea0 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy @@ -33,6 +33,7 @@ import org.onap.so.bpmn.common.scripts.VidUtils import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.AAIResultWrapper import org.onap.so.client.aai.entities.Relationships @@ -42,12 +43,12 @@ import org.onap.so.client.graphinventory.entities.uri.Depth import org.onap.so.constants.Defaults import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig + import org.springframework.web.util.UriUtils +import org.onap.so.utils.TargetEntity import groovy.json.JsonOutput +import javax.ws.rs.core.Response public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteNetworkInstance.class); @@ -447,17 +448,13 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { String vnfAdapterUrl = UrnPropertiesReader.getVariable("mso.adapters.network.rest.endpoint",execution) String vnfAdapterRequest = execution.getVariable(Prefix + "deleteNetworkRequest") - RESTConfig config = new RESTConfig(vnfAdapterUrl) - RESTClient client = new RESTClient(config). - addHeader("Content-Type", "application/xml"). - addAuthorizationHeader(execution.getVariable("BasicAuthHeaderValuePO")); - - APIResponse response; + URL url = new URL(vnfAdapterUrl) + HttpClient httpClient = new HttpClient(url, "application/xml", TargetEntity.OPENSTACK_ADAPTER) + httpClient.addAdditionalHeader("Authorization", execution.getVariable("BasicAuthHeaderValuePO")) + Response response = httpClient.delete(vnfAdapterRequest) - response = client.httpDelete(vnfAdapterRequest) - execution.setVariable(Prefix + "networkReturnCode", response.getStatusCode()) - execution.setVariable(Prefix + "deleteNetworkResponse", response.getResponseBodyAsString()) + execution.setVariable(Prefix + "networkReturnCode", response.getStatus()) } catch (Exception ex) { // caught exception @@ -499,7 +496,7 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { execution.setVariable(Prefix + "requestId", requestId) msoLogger.debug(Prefix + "requestId " + requestId) L3Network queryAAIResponse = execution.getVariable(Prefix + "queryAAIResponse") - + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") // 1. prepare delete topology via SDNC Adapter SUBFLOW call @@ -972,9 +969,9 @@ public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { requestId = execution.getVariable("mso-request-id") } execution.setVariable(Prefix + "requestId", requestId) - + L3Network queryAAIResponse = execution.getVariable(Prefix + "queryAAIResponse") - + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") // 1. prepare delete topology via SDNC Adapter SUBFLOW call diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy index ca6e21eedc..1db7475cba 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,9 +30,7 @@ import org.onap.so.bpmn.common.scripts.NetworkUtils import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils import org.onap.so.bpmn.common.scripts.VidUtils import org.onap.so.bpmn.core.WorkflowException -import org.onap.so.rest.APIResponse; -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig + import java.util.UUID; @@ -51,7 +49,7 @@ import org.onap.so.logger.MsoLogger */ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteNetworkInstanceRollback.class); - + String Prefix="DELNWKIR_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -60,16 +58,16 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() def className = getClass().getSimpleName() - + /** * This method is executed during the preProcessRequest task of the DoDeleteNetworkInstanceRollback.bpmn process. * @param execution */ public InitializeProcessVariables(DelegateExecution execution){ /* Initialize all the process variables in this block */ - + execution.setVariable(Prefix + "WorkflowException", null) - + execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", null) execution.setVariable(Prefix + "rollbackDeactivateSDNCResponse", "") execution.setVariable(Prefix + "rollbackDeactivateSDNCReturnCode", "") @@ -77,11 +75,11 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso execution.setVariable(Prefix + "rollbackSDNCRequest", "") execution.setVariable(Prefix + "rollbackSDNCResponse", "") execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") - + execution.setVariable(Prefix + "rollbackNetworkRequest", null) execution.setVariable(Prefix + "rollbackNetworkResponse", "") execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") - + execution.setVariable(Prefix + "Success", false) execution.setVariable(Prefix + "fullRollback", false) @@ -97,13 +95,13 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso public void preProcessRequest (DelegateExecution execution) { execution.setVariable("prefix",Prefix) - + msoLogger.trace("Inside preProcessRequest() of " + className + ".groovy ") try { // initialize flow variables InitializeProcessVariables(execution) - + // GET Incoming request/variables String rollbackDeactivateSDNCRequest = null String rollbackSDNCRequest = null @@ -111,20 +109,20 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso Map rollbackData = execution.getVariable("rollbackData") if (rollbackData != null && rollbackData instanceof Map) { - + if(rollbackData.containsKey("rollbackDeactivateSDNCRequest")) { rollbackDeactivateSDNCRequest = rollbackData["rollbackDeactivateSDNCRequest"] } - + if(rollbackData.containsKey("rollbackSDNCRequest")) { rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] } - + if(rollbackData.containsKey("rollbackNetworkRequest")) { rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] } } - + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", rollbackDeactivateSDNCRequest) @@ -132,14 +130,14 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso String sdncVersion = execution.getVariable("sdncVersion") msoLogger.debug("sdncVersion? : " + sdncVersion) - + // PO Authorization Info / headers Authorization= String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution) try { def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution)) execution.setVariable("BasicAuthHeaderValuePO",encodedString) execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) - + } catch (IOException ex) { String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() @@ -160,31 +158,31 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso } else { // called by: Macro - Full Rollback, WorkflowException = null execution.setVariable(Prefix + "fullRollback", true) - + } - + msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) - + } catch (BpmnError e) { throw e; - + } catch (Exception ex) { sendSyncError(execution) // caught exception String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() msoLogger.debug(exceptionMessage) exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - + } } - + public void validateRollbackResponses (DelegateExecution execution) { execution.setVariable("prefix",Prefix) msoLogger.trace("Inside validateRollbackResponses() of DoDeleteNetworkInstanceRollback ") - + try { // validate SDNC activate response @@ -212,7 +210,7 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso msoLogger.debug(" SDNC deactivate rollback Code - " + rollbackDeactivateSDNCReturnCode) msoLogger.debug(" SDNC deactivate rollback Response - " + rollbackDeactivateSDNCResponse) } - + // validate SDNC rollback response String rollbackSdncErrorMessages = "" String rollbackSDNCReturnCode = "200" @@ -239,7 +237,7 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso msoLogger.debug(" SDNC assign rollback Code - " + rollbackSDNCReturnCode) msoLogger.debug(" SDNC assign rollback Response - " + rollbackSDNCResponse) } - + // validate PO network rollback response String rollbackNetworkErrorMessages = "" String rollbackNetworkReturnCode = "200" @@ -251,11 +249,11 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso } else { rollbackNetworkErrorMessages = " + PO Network rollback completed." } - + msoLogger.debug(" NetworkRollback Code - " + rollbackNetworkReturnCode) msoLogger.debug(" NetworkRollback Response - " + rollbackNetworkResponse) } - + String statusMessage = "" int errorCode = 7000 msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) @@ -273,7 +271,7 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso if (rollbackDeactivateSDNCReturnCode == "200" && rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { execution.setVariable("rolledBack", true) execution.setVariable("wasDeleted", true) - + } else { execution.setVariable("rolledBack", false) execution.setVariable("wasDeleted", true) @@ -284,12 +282,12 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso String processKey = getProcessKey(execution); WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); execution.setVariable("workflowException", exception); - + } else { // rollback due to failures in Main flow (Macro or a-ala-carte) - Full rollback if (rollbackDeactivateSDNCReturnCode == "200" && rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { execution.setVariable("rollbackSuccessful", true) - execution.setVariable("rollbackError", false) + execution.setVariable("rollbackError", false) } else { String exceptionMessage = "Network Delete Rollback was not Successful. " msoLogger.debug(exceptionMessage) @@ -297,9 +295,9 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso execution.setVariable("rollbackError", true) exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) throw new BpmnError("MSOWorkflowException") - } - } - + } + } + } catch (Exception ex) { String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." String exceptionMessage = " Bpmn error encountered in DoDeleteNetworkInstanceRollback flow. validateRollbackResponses() - " + errorMessage + ": " + ex.getMessage() @@ -315,18 +313,18 @@ public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcesso // ******************************* - + public void processJavaException(DelegateExecution execution){ execution.setVariable("prefix",Prefix) - + try{ msoLogger.debug("Caught a Java Exception in " + Prefix) msoLogger.debug("Started processJavaException Method") msoLogger.debug("Variables List: " + execution.getVariables()) execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") - + }catch(Exception e){ msoLogger.debug("Caught Exception during processJavaException Method: " + e) execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy index da2d14f060..d855479694 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,15 +25,15 @@ import org.camunda.bpm.engine.delegate.DelegateExecution import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.HttpClient import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.utils.TargetEntity +import javax.ws.rs.core.Response /** * This groovy class supports the DoDeleteVFCNetworkServiceInstance.bpmn process. * flow for E2E ServiceInstance Delete @@ -41,11 +41,11 @@ import org.onap.so.rest.RESTConfig public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVFCNetworkServiceInstance.class); - + String vfcUrl = "/vfc/rest/v1/vfcadapter" - + String host = "http://mso.mso.testlab.openecomp.org:8080" - + ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -124,16 +124,15 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces msoLogger.trace("deleteNetworkService start ") String nsOperationKey = execution.getVariable("nsOperationKey"); - String url = host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") - APIResponse apiResponse = deleteRequest(execution, url, nsOperationKey) - String returnCode = apiResponse.getStatusCode() - String apiResponseAsString = apiResponse.getResponseBodyAsString() + String url = host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") + Response apiResponse = deleteRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatus() String operationStatus = "error"; if(returnCode== "200" || returnCode== "202"){ operationStatus = "finished" } execution.setVariable("operationStatus", operationStatus) - + msoLogger.trace("deleteNetworkService end ") } @@ -143,16 +142,16 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces public void terminateNetworkService(DelegateExecution execution) { msoLogger.trace("terminateNetworkService start ") - String nsOperationKey = execution.getVariable("nsOperationKey") + String nsOperationKey = execution.getVariable("nsOperationKey") String url = host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") + "/terminate" - APIResponse apiResponse = postRequest(execution, url, nsOperationKey) - String returnCode = apiResponse.getStatusCode() - String aaiResponseAsString = apiResponse.getResponseBodyAsString() + Response apiResponse = postRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatus() + String aaiResponseAsString = apiResponse.readEntity(String.class) String jobId = ""; if(returnCode== "200" || returnCode== "202"){ jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId") } - execution.setVariable("jobId", jobId) + execution.setVariable("jobId", jobId) msoLogger.trace("terminateNetworkService end ") } @@ -164,10 +163,10 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces msoLogger.trace("queryNSProgress start ") String jobId = execution.getVariable("jobId") String nsOperationKey = execution.getVariable("nsOperationKey"); - String url = host + vfcUrl + "/jobs/" + execution.getVariable("jobId") - APIResponse apiResponse = postRequest(execution, url, nsOperationKey) - String returnCode = apiResponse.getStatusCode() - String apiResponseAsString = apiResponse.getResponseBodyAsString() + String url = host + vfcUrl + "/jobs/" + execution.getVariable("jobId") + Response apiResponse = postRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatus() + String apiResponseAsString = apiResponse.readEntity(String.class) String operationProgress = "100" if(returnCode== "200"){ operationProgress = jsonUtil.getJsonValue(apiResponseAsString, "responseDescriptor.progress") @@ -177,12 +176,12 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces } /** - * delay 5 sec + * delay 5 sec */ public void timeDelay(DelegateExecution execution) { try { Thread.sleep(5000); - } catch(InterruptedException e) { + } catch(InterruptedException e) { msoLogger.info("Time Delay exception" + e) } } @@ -199,21 +198,27 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces * url: the url of the request * requestBody: the body of the request */ - private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){ + private Response postRequest(DelegateExecution execution, String urlString, String requestBody){ - msoLogger.trace("Started Execute VFC adapter Post Process ") - msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null - try{ - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");; - apiResponse = client.httpPost(requestBody) - msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) - msoLogger.trace("Completed Execute VF-C adapter Post Process ") - }catch(Exception e){ + msoLogger.trace("Started Execute VFC adapter Post Process ") + msoLogger.info("url:"+urlString +"\nrequestBody:"+ requestBody) + Response apiResponse = null + try{ + URL url = new URL(urlString); + + HttpClient httpClient = new HttpClient(url, "application/json", TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk") + + apiResponse = httpClient.post(requestBody) + + msoLogger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class)) + + msoLogger.trace("Completed Execute VF-C adapter Post Process ") + }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); throw new BpmnError("MSOWorkflowException") - } + } return apiResponse } /** @@ -221,21 +226,24 @@ public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProces * url: the url of the request * requestBody: the body of the request */ - private APIResponse deleteRequest(DelegateExecution execution, String url, String requestBody){ + private Response deleteRequest(DelegateExecution execution, String url, String requestBody){ - msoLogger.trace("Started Execute VFC adapter Delete Process ") + msoLogger.trace("Started Execute VFC adapter Delete Process ") msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) - APIResponse apiResponse = null + Response r try{ - RESTConfig config = new RESTConfig(url); - RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk"); - apiResponse = client.httpDelete(requestBody) - msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) - msoLogger.trace("Completed Execute VF-C adapter Delete Process ") + + URL Url = new URL(url) + HttpClient httpClient = new HttpClient(Url, "application/json", TargetEntity.VNF_ADAPTER) + httpClient.addAdditionalHeader("Accept", "application/json") + httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk") + r = httpClient.delete(requestBody) + + msoLogger.trace("Completed Execute VF-C adapter Delete Process ") }catch(Exception e){ - msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); throw new BpmnError("MSOWorkflowException") - } - return apiResponse + } + return r } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy index d6ca08d816..3bc481ab01 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -43,9 +43,6 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig import org.springframework.web.util.UriUtils import org.w3c.dom.Document import org.w3c.dom.Element @@ -66,7 +63,7 @@ import org.xml.sax.InputSource * @param - vfModuleModelInfo * @param - cloudConfiguration* * @param - sdncVersion ("1610") -* @param - retainResources +* @param - retainResources * @param - aLaCarte * * Outputs: @@ -133,11 +130,11 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName") execution.setVariable("vfModuleModelName", vfModuleModelName) // retainResources - def retainResources = execution.getVariable("retainResources") + def retainResources = execution.getVariable("retainResources") if (retainResources == null) { retainResources = false } - execution.setVariable("retainResources", retainResources) + execution.setVariable("retainResources", retainResources) } else { @@ -206,7 +203,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ if(uuid==null){ uuid = execution.getVariable("requestId") + "-" + System.currentTimeMillis() } - + def srvInstId = execution.getVariable("srvInstId") def callbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) String requestId = execution.getVariable("requestId") @@ -229,7 +226,7 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ boolean retainResources = execution.getVariable("retainResources") String requestSubActionString = "" if (retainResources) { - requestSubActionString = "RetainResource" + requestSubActionString = "RetainResource" } String request = """ + L3Network net = network.asBean(L3Network.class).get() + String netId = net.getNetworkId() + String netName = net.getNetworkName() + String networkOutputs = + """ ${MsoUtils.xmlEscape(netId)} ${MsoUtils.xmlEscape(netName)} """ - execution.setVariable(Prefix + "networkOutputs", networkOutputs) - msoLogger.debug(" networkOutputs - " + '\n' + networkOutputs) - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)." - msoLogger.debug(" AAI ReQuery Failed. - " + dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from ReQueryAAINetworkId - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } - - } catch (BpmnError e) { - throw e; + execution.setVariable(Prefix + "networkOutputs", networkOutputs) + msoLogger.debug(" networkOutputs - " + '\n' + networkOutputs) + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)." + msoLogger.debug(" AAI ReQuery Failed. - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTReQueryAAINetworkId() - " + ex.getMessage() msoLogger.debug(exceptionMessage) @@ -551,71 +491,56 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { try { // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) - - // Check if Vnf Binding is present, then build a List of vnfBinding - List vpnBindingUri = networkUtils.getVnfBindingObject(relationship) - int vpnCount = vpnBindingUri.size() - execution.setVariable(Prefix + "vpnCount", vpnCount) - msoLogger.debug(" UPDNETI_vpnCount - " + vpnCount) - - if (vpnCount > 0) { - execution.setVariable(Prefix + "vpnBindings", vpnBindingUri) - msoLogger.debug(" vpnBindingUri List - " + vpnBindingUri) - - String routeTargets = "" - // AII loop call using list vpnBindings - for(i in 0..vpnBindingUri.size()-1) { - int counting = i+1 - - String vpnBindingId = vpnBindingUri[i].substring(vpnBindingUri[i].indexOf("/vpn-binding/")+13, vpnBindingUri[i].length()) - if (vpnBindingId.charAt(vpnBindingId.length()-1) == '/') { - vpnBindingId = vpnBindingId.substring(0, vpnBindingId.length()-1) - } - - AAIResourcesClient resourceClient = new AAIResourcesClient() - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VPN_BINDING, vpnBindingId) - AAIResultWrapper wrapper = resourceClient.get(uri.depth(Depth.TWO), NotFoundException.class) - - Optional binding = wrapper.asBean(VpnBinding.class) - - String routeTarget = "" - String routeRole = "" - if(binding.get().getRouteTargets() != null) { - List targets = binding.get().getRouteTargets().getRouteTarget() - for(RouteTarget target : targets) { - routeTarget = target.getGlobalRouteTarget() - routeRole = target.getRouteTargetRole() - routeTargets += "" + '\n' + - " " + routeTarget + "" + '\n' + - " " + routeRole + "" + '\n' + - "" + '\n' + AAIResultWrapper queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + if(queryIdAAIResponse.getRelationships().isPresent()){ + List uris = queryIdAAIResponse.getRelationships().get().getRelatedAAIUris(AAIObjectType.VPN_BINDING) + + msoLogger.debug(Prefix + "vpnCount - " + uris.size()) + + if (uris.size() > 0) { + String routeTargets = "" + for(AAIResourceUri u : uris) { + + AAIResourcesClient client = new AAIResourcesClient() + AAIResultWrapper wrapper = client.get(u.depth(Depth.TWO), NotFoundException.class) + Optional binding = wrapper.asBean(VpnBinding.class) + + String routeTarget = "" + String routeRole = "" + if(binding.get().getRouteTargets() != null) { + List targets = binding.get().getRouteTargets().getRouteTarget() + for(RouteTarget target : targets) { + routeTarget = target.getGlobalRouteTarget() + routeRole = target.getRouteTargetRole() + routeTargets += "" + '\n' + + " " + routeTarget + "" + '\n' + + " " + routeRole + "" + '\n' + + "" + '\n' + } } - } - } // end loop + } // end loop - execution.setVariable(Prefix + "routeCollection", routeTargets) - msoLogger.debug(" UPDNETI_routeCollection - " + '\n' + routeTargets) + execution.setVariable(Prefix + "routeCollection", routeTargets) + msoLogger.debug(" UPDNETI_routeCollection - " + '\n' + routeTargets) - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") - AaiUtil aaiUriUtil = new AaiUtil(this) - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ """ - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "routeCollection", "") - msoLogger.debug(" No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "routeCollection", "") + msoLogger.debug(" No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } } catch (NotFoundException e) { @@ -638,103 +563,55 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { try { // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) - - // Check if Network Policy is present, then build a List of network policy - List networkPolicyUriList = networkUtils.getNetworkPolicyObject(relationship) - int networkPolicyCount = networkPolicyUriList.size() - execution.setVariable(Prefix + "networkPolicyCount", networkPolicyCount) - msoLogger.debug(" UPDNETI_networkPolicyCount - " + networkPolicyCount) - - AaiUtil aaiUriUtil = new AaiUtil(this) + AAIResultWrapper queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + if(queryIdAAIResponse.getRelationships().isPresent()){ + List uris = queryIdAAIResponse.getRelationships().get().getRelatedAAIUris(AAIObjectType.NETWORK_POLICY) - if (networkPolicyCount > 0) { - execution.setVariable(Prefix + "networkPolicyUriList", networkPolicyUriList) - msoLogger.debug(" networkPolicyUri List - " + networkPolicyUriList) + execution.setVariable(Prefix + "networkPolicyCount", uris.size()) + msoLogger.debug(Prefix + "networkPolicyCount - " + uris.size()) - String networkPolicies = "" - // AII loop call using list vpnBindings - for (i in 0..networkPolicyUriList.size()-1) { + if (uris.size() > 0) { - int counting = i+1 + String networkPolicies = "" + // AII loop call using list vpnBindings + for(AAIResourceUri u : uris) { - URI uri = UriBuilder.fromUri(networkPolicyUriList[i]).build() + AAIResourcesClient client = new AAIResourcesClient() + NetworkPolicy p = client.get(u, NotFoundException.class).asBean(NetworkPolicy.class).get() - AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.NETWORK_POLICY, uri) - aaiUri.depth(Depth.ALL) - String queryNetworkPolicyAAIRequest = aaiUriUtil.createAaiUri(aaiUri) + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") - msoLogger.debug(queryNetworkPolicyAAIRequest) - execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest", queryNetworkPolicyAAIRequest) - msoLogger.debug(" UPDNETI_queryNetworkPolicyAAIRequest, , NetworkPolicy #" + counting + " : " + "\n" + queryNetworkPolicyAAIRequest) + String networkPolicy = p.getNetworkPolicyFqdn() + networkPolicies += "" + networkPolicy + "" + '\n' - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", returnCode) - msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) + } // end loop - String aaiResponseAsString = response.getResponseBodyAsString() - - if (returnCode=='200') { - msoLogger.debug(aaiResponseAsString) - execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiResponseAsString) - msoLogger.debug(" QueryAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) - - String networkPolicy = "" - if (utils.nodeExists(aaiResponseAsString, "network-policy-fqdn")) { - networkPolicy = utils.getNodeText(aaiResponseAsString, "network-policy-fqdn") - networkPolicies += "" + networkPolicy + "" + '\n' - } + execution.setVariable(Prefix + "networkCollection", networkPolicies) + msoLogger.debug(" UPDNETI_networkCollection - " + '\n' + networkPolicies) - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from QueryAAINetworkPolicy - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } - - } // end loop - - execution.setVariable(Prefix + "networkCollection", networkPolicies) - msoLogger.debug(" UPDNETI_networkCollection - " + '\n' + networkPolicies) - - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ """ - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "networkCollection", "") - msoLogger.debug(" No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "networkCollection", "") + msoLogger.debug(" No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } - } catch (BpmnError e) { - throw e; - + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkPolicy() - " + ex.getMessage() msoLogger.debug(exceptionMessage) @@ -751,105 +628,56 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { msoLogger.debug(" ***** Inside callRESTQueryAAINetworkTableRef of DoUpdateNetworkInstance ***** " ) try { - // get variables - String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('', "") - String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") - msoLogger.debug(" relationship - " + relationship) + AAIResultWrapper queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + if(queryIdAAIResponse.getRelationships().isPresent()){ + List uris = queryIdAAIResponse.getRelationships().get().getRelatedAAIUris(AAIObjectType.ROUTE_TABLE_REFERENCE) - // Check if Network TableREf is present, then build a List of network policy - List networkTableRefUriList = networkUtils.getNetworkTableRefObject(relationship) - int networkTableRefCount = networkTableRefUriList.size() - execution.setVariable(Prefix + "networkTableRefCount", networkTableRefCount) - msoLogger.debug(" UPDNETI_networkTableRefCount - " + networkTableRefCount) + execution.setVariable(Prefix + "networkTableRefCount", uris.size()) + msoLogger.debug(Prefix + "networkTableRefCount - " + uris.size()) - String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) - AaiUtil aaiUriUtil = new AaiUtil(this) - - if (networkTableRefCount > 0) { - execution.setVariable(Prefix + "networkTableRefUriList", networkTableRefUriList) - msoLogger.debug(" networkTableRefUri List - " + networkTableRefUriList) - - // AII loop call using list vpnBindings - String networkTableRefs = "" - for (i in 0..networkTableRefUriList.size()-1) { - - int counting = i+1 + msoLogger.debug(" UPDNETI_networkTableRefCount - " + uris.size()) + if (uris.size() > 0) { - // prepare url using tableRef - URI uri = UriBuilder.fromUri(networkTableRefUriList[i]).build() + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") - AAIResourceUri aaiUri = AAIUriFactory.createResourceFromExistingURI(AAIObjectType.ROUTE_TABLE_REFERENCE, uri) - aaiUri.depth(Depth.ALL) - String queryNetworkTableRefAAIRequest = aaiUriUtil.createAaiUri(aaiUri) + // AII loop call using list vpnBindings + String networkTableRefs = "" + for(AAIResourceUri u : uris) { - msoLogger.debug(queryNetworkTableRefAAIRequest) - execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest", queryNetworkTableRefAAIRequest) - msoLogger.debug(" UPDNETI_queryNetworkTableRefAAIRequest, , NetworkTableRef #" + counting + " : " + "\n" + queryNetworkTableRefAAIRequest) + AAIResourcesClient client = new AAIResourcesClient() + RouteTableReference rt = client.get(u, NotFoundException.class).asBean(RouteTableReference.class).get() - APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkTableRefAAIRequest) - String returnCode = response.getStatusCode() - execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", returnCode) - msoLogger.debug(" ***** AAI query network Table Reference Response Code, NetworkTableRef #" + counting + " : " + returnCode) + String networkTableRef = rt.getRouteTableReferenceFqdn() + networkTableRefs += "" + networkTableRef + "" + '\n' - String aaiResponseAsString = response.getResponseBodyAsString() + } // end loop - if (returnCode=='200') { - msoLogger.debug(aaiResponseAsString) - execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiResponseAsString) - msoLogger.debug(" QueryAAINetworkTableRef Success REST Response, , NetworkTableRef #" + counting + " : " + "\n" + aaiResponseAsString) + execution.setVariable(Prefix + "tableRefCollection", networkTableRefs) + msoLogger.debug(" UPDNETI_tableRefCollection - " + '\n' + networkTableRefs) - String networkTableRef = "" - if (utils.nodeExists(aaiResponseAsString, "route-table-reference-fqdn")) { - networkTableRef = utils.getNodeText(aaiResponseAsString, "route-table-reference-fqdn") - networkTableRefs += "" + networkTableRef + "" + '\n' - } - - } else { - if (returnCode=='404') { - String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } else { - if (aaiResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String dataErrorMessage = "Unexpected Response from QueryAAINetworkTableRef - " + returnCode - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) - - } - } - } - - } // end loop - - execution.setVariable(Prefix + "tableRefCollection", networkTableRefs) - msoLogger.debug(" UPDNETI_tableRefCollection - " + '\n' + networkTableRefs) - - } else { - // reset return code to success - execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") - String schemaVersion = aaiUriUtil.getNamespace() - String aaiStubResponse = - """ + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") + AaiUtil aaiUriUtil = new AaiUtil(this) + String schemaVersion = aaiUriUtil.getNamespace() + String aaiStubResponse = + """ """ - String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) - execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml) - execution.setVariable(Prefix + "tableRefCollection", "") - msoLogger.debug(" No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml) + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "tableRefCollection", "") + msoLogger.debug(" No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml) + } } - } catch (BpmnError e) { - throw e; + } catch (NotFoundException e) { + String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkTableRef() - " + ex.getMessage() @@ -861,76 +689,73 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { } public void callRESTUpdateContrailAAINetwork(DelegateExecution execution) { - execution.setVariable("prefix", Prefix) - msoLogger.debug(" ***** Inside callRESTUpdateContrailAAINetwork of DoUpdateNetworkInstance ***** " ) - try { // get variables String networkRequest = execution.getVariable(Prefix + "networkRequest") String networkId = utils.getNodeText(networkRequest, "network-id") - networkId = UriUtils.encode(networkId,"UTF-8") - String requeryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + AAIResultWrapper requeryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") String updateNetworkResponse = execution.getVariable(Prefix + "updateNetworkResponse") - // Prepare url - AaiUtil aaiUriUtil = new AaiUtil(this) - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) - uri.depth(Depth.ALL) - String updateContrailAAIUrlRequest = aaiUriUtil.createAaiUri(uri) - - msoLogger.debug(updateContrailAAIUrlRequest) - execution.setVariable(Prefix + "updateContrailAAIUrlRequest", updateContrailAAIUrlRequest) - msoLogger.debug(" UPDNETI_updateContrailAAIUrlRequest - " + "\n" + updateContrailAAIUrlRequest) - - //Prepare payload (PUT) - String schemaVersion = aaiUriUtil.getNamespaceFromUri(updateContrailAAIUrlRequest) - String payload = networkUtils.ContrailNetworkCreatedUpdate(requeryIdAAIResponse, updateNetworkResponse, schemaVersion) - String payloadXml = utils.formatXml(payload) - msoLogger.debug(payloadXml) - execution.setVariable(Prefix + "updateContrailAAIPayloadRequest", payloadXml) - msoLogger.debug(" 'payload' to Update Contrail - " + "\n" + payloadXml) - - APIResponse response = aaiUriUtil.executeAAIPutCall(execution, updateContrailAAIUrlRequest, payload) - String returnCode = response.getStatusCode() - String aaiUpdateContrailResponseAsString = response.getResponseBodyAsString() - - execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", returnCode) - msoLogger.debug(" ***** AAI Update Contrail Response Code : " + returnCode) - - - if (returnCode=='200') { - msoLogger.debug(aaiUpdateContrailResponseAsString) - execution.setVariable(Prefix + "updateContrailAAIResponse", aaiUpdateContrailResponseAsString) - msoLogger.debug(" AAI Update Contrail Success REST Response - " + "\n" + aaiUpdateContrailResponseAsString) - // Point-of-no-return is set to false, rollback not needed. - execution.setVariable(Prefix + "isPONR", true) - + L3Network oldL3Network = requeryIdAAIResponse.asBean(L3Network.class).get() + L3Network l3Network = new L3Network() + if (oldL3Network.getHeatStackId() != null) { } else { - if (returnCode=='404') { - String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." - msoLogger.debug(dataErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + if (utils.nodeExists(updateNetworkResponse, 'networkStackId')) { + l3Network.setHeatStackId(utils.getNodeText(updateNetworkResponse, 'networkStackId')) + } + } + if (oldL3Network.getNeutronNetworkId() != null) { + } else { + if (utils.nodeExists(updateNetworkResponse, 'neutronNetworkId')) { + l3Network.setNeutronNetworkId(utils.getNodeText(updateNetworkResponse, 'neutronNetworkId')) + } + } + if (oldL3Network.getContrailNetworkFqdn() != null) { + } else { + if (utils.nodeExists(updateNetworkResponse, 'networkFqdn')) { + l3Network.setContrailNetworkFqdn(utils.getNodeText(updateNetworkResponse, 'networkFqdn')) + } + } - } else { - if (aaiUpdateContrailResponseAsString.contains("RESTFault")) { - WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiUpdateContrailResponseAsString, execution) - execution.setVariable("WorkflowException", exceptionObject) - throw new BpmnError("MSOWorkflowException") - - } else { - // aai all errors - String errorMessage = "Unexpected Response from UpdateContrailAAINetwork - " + returnCode - msoLogger.debug(errorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) - } + String status = utils.getNodeText(updateNetworkResponse, 'orchestration-status') + if(status.equals("pending-create") || status.equals("PendingCreate")){ + l3Network.setOperationalStatus("Created") + }else{ + l3Network.setOperationalStatus("Active") + } + + AAIResourcesClient client = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.L3_NETWORK, networkId) + client.update(uri, l3Network) + + List subnets = oldL3Network.getSubnets().getSubnet() + for(Subnet s:subnets){ + String subnetOrchStatus = s.getOrchestrationStatus() + String subnetId = s.getSubnetId() + + Subnet subnet = new Subnet() + String neutronSubnetId = networkUtils.extractNeutSubId(updateNetworkResponse, subnetId) + subnet.setNeutronSubnetId(neutronSubnetId) + if(subnetOrchStatus.equals("pending-create") || subnetOrchStatus.equals("PendingCreate") ){ + subnet.setOrchestrationStatus("Created") + }else{ + subnet.setOrchestrationStatus("Active") } + + AAIResourceUri subUri = AAIUriFactory.createResourceUri(AAIObjectType.SUBNET, networkId, subnetId) + client.update(subUri, subnet) } + execution.setVariable(Prefix + "isPONR", true) + } catch (BpmnError e) { throw e; - + } catch (NotFoundException e) { + String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } catch (Exception ex) { String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTUpdateContrailAAINetwork() - " + ex.getMessage() msoLogger.debug(exceptionMessage) @@ -1000,7 +825,8 @@ public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { String serviceInstanceId = utils.getNodeText(updateNetworkInput, "service-instance-id") - String queryAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse") + AAIResultWrapper wrapper = execution.getVariable(Prefix + "queryIdAAIResponse") + L3Network queryAAIResponse = wrapper.asBean(L3Network.class).get() // 1. prepare assign topology via SDNC Adapter SUBFLOW call String sndcTopologyCreateRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, updateNetworkInput, serviceInstanceId, sdncCallback, "changeassign", "NetworkActivateRequest", cloudRegionId, networkId, queryAAIResponse, null) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy index 8a13b3c392..eaba51ac6f 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,7 +32,7 @@ import org.onap.so.bpmn.common.scripts.VidUtils import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.json.JsonUtils -import org.onap.so.rest.APIResponse + import java.util.UUID; @@ -51,7 +51,7 @@ import org.onap.so.logger.MsoLogger */ public class DoUpdateNetworkInstanceRollback extends AbstractServiceTaskProcessor { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoUpdateNetworkInstanceRollback.class); - + String Prefix="UPDNETIR_" ExceptionUtil exceptionUtil = new ExceptionUtil() JsonUtils jsonUtil = new JsonUtils() @@ -128,7 +128,7 @@ public class DoUpdateNetworkInstanceRollback extends AbstractServiceTaskProcesso // PO Authorization Info / headers Authorization= String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution) - + try { def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution)) execution.setVariable("BasicAuthHeaderValuePO",encodedString) diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy index c4711411d3..f6a8a1558c 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy @@ -45,7 +45,7 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.constants.Defaults import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse + import org.springframework.web.util.UriUtils public class DoUpdateVfModule extends VfModuleBase { diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy index afe01b9243..7fdbb5cb89 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,6 +22,8 @@ package org.onap.so.bpmn.infrastructure.scripts import static org.apache.commons.lang3.StringUtils.*; +import javax.ws.rs.core.MediaType +import javax.ws.rs.core.Response import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.delegate.DelegateExecution; import org.onap.so.bpmn.common.scripts.AaiUtil @@ -34,15 +36,14 @@ import org.onap.so.bpmn.core.domain.ModuleResource import org.onap.so.bpmn.core.domain.VnfResource import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.client.graphinventory.entities.uri.Depth +import org.onap.so.client.HttpClient import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient import org.onap.so.client.aai.entities.uri.AAIResourceUri import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig +import org.onap.so.utils.TargetEntity import org.springframework.web.util.UriUtils; /** @@ -54,14 +55,14 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { String Prefix="DUVAM_" ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtil = new JsonUtils() + JsonUtils jsonUtil = new JsonUtils() /** * This method gets and validates the incoming * request. * * @param - execution - * + * */ public void preProcessRequest(DelegateExecution execution) { @@ -69,66 +70,66 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { msoLogger.trace("STARTED DoUpdateVnfAndModules PreProcessRequest Process") try{ - // Get Variables - + // Get Variables + String requestId = execution.getVariable("msoRequestId") - execution.setVariable("requestId", requestId) + execution.setVariable("requestId", requestId) execution.setVariable("mso-request-id", requestId) msoLogger.debug("Incoming Request Id is: " + requestId) - String serviceInstanceId = execution.getVariable("serviceInstanceId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId) - String vnfId = execution.getVariable("vnfId") - msoLogger.debug("Incoming Vnf Id is: " + vnfId) - + String vnfId = execution.getVariable("vnfId") + msoLogger.debug("Incoming Vnf Id is: " + vnfId) + String source = "VID" execution.setVariable("DUVAM_source", source) msoLogger.debug("Incoming Source is: " + source) - + String sdncVersion = execution.getVariable("sdncVersion") if (sdncVersion == null) { sdncVersion = "1702" } execution.setVariable("DUVAM_sdncVersion", sdncVersion) msoLogger.debug("Incoming Sdnc Version is: " + sdncVersion) - - VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition") - + + VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition") + String vnfModelInfo = execution.getVariable("vnfModelInfo") String serviceModelInfo = execution.getVariable("serviceModelInfo") - + String serviceId = execution.getVariable("productFamilyId") execution.setVariable("DUVAM_serviceId", serviceId) - msoLogger.debug("Incoming Service Id is: " + serviceId) - - String modelUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelUuid") + msoLogger.debug("Incoming Service Id is: " + serviceId) + + String modelUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelUuid") execution.setVariable("DUVAM_modelUuid", modelUuid) - msoLogger.debug("Incoming modelUuid is: " + modelUuid) - - String modelCustomizationUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationUuid") + msoLogger.debug("Incoming modelUuid is: " + modelUuid) + + String modelCustomizationUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationUuid") execution.setVariable("DUVAM_modelCustomizationUuid", modelCustomizationUuid) msoLogger.debug("Incoming Model Customization Uuid is: " + modelCustomizationUuid) - + String cloudSiteId = execution.getVariable("lcpCloudRegionId") execution.setVariable("DUVAM_cloudSiteId", cloudSiteId) msoLogger.debug("Incoming Cloud Site Id is: " + cloudSiteId) - + String tenantId = execution.getVariable("tenantId") execution.setVariable("DUVAM_tenantId", tenantId) msoLogger.debug("Incoming Tenant Id is: " + tenantId) - + String globalSubscriberId = execution.getVariable("globalSubscriberId") if (globalSubscriberId == null) { globalSubscriberId = "" } execution.setVariable("DUVAM_globalSubscriberId", globalSubscriberId) msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId) - + execution.setVariable("DUVAM_moduleCount", 0) execution.setVariable("DUVAM_nextModule", 0) - - + + }catch(BpmnError b){ msoLogger.debug("Rethrowing MSOWorkflowException") throw b @@ -138,8 +139,8 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { } msoLogger.trace("COMPLETED DoUpdateVnfAndModules PreProcessRequest Process ") - } - + } + /** * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info. * A 200 response is expected with the VNF info in the response body. Will find out the base module info. @@ -155,43 +156,43 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { try { def vnfId = execution.getVariable('vnfId') - + AaiUtil aaiUriUtil = new AaiUtil(this) AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE) String endPoint = aaiUriUtil.createAaiUri(uri) msoLogger.debug("AAI endPoint: " + endPoint) try { - RESTConfig config = new RESTConfig(endPoint); + HttpClient client = new HttpClient(new URL(endPoint), MediaType.APPLICATION_XML, TargetEntity.AAI) + client.addAdditionalHeader('X-TransactionId', UUID.randomUUID().toString()) + client.addAdditionalHeader('X-FromAppId', 'MSO') + client.addAdditionalHeader('Content-Type', 'application/xml') + client.addAdditionalHeader('Accept','application/xml') + def responseData = '' - def aaiRequestId = UUID.randomUUID().toString() - RESTClient client = new RESTClient(config). - addHeader('X-TransactionId', aaiRequestId). - addHeader('X-FromAppId', 'MSO'). - addHeader('Content-Type', 'application/xml'). - addHeader('Accept','application/xml'); + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') - APIResponse response = client.httpGet() + Response response = client.get() msoLogger.debug("createVfModule - invoking httpGet() to AAI") - responseData = response.getResponseBodyAsString() + responseData = response.readEntity(String.class) if (responseData != null) { msoLogger.debug("Received generic VNF data: " + responseData) } msoLogger.debug("createVfModule - queryAAIVfModule Response: " + responseData) - msoLogger.debug("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) + msoLogger.debug("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatus()) - execution.setVariable('DUVAM_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('DUVAM_queryAAIVfModuleResponseCode', response.getStatus()) execution.setVariable('DUVAM_queryAAIVfModuleResponse', responseData) - msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response code:' + response.getStatus()) msoLogger.debug('Response:' + System.lineSeparator() + responseData) //Map[] vfModules = new HashMap[] def vfModulesList = new ArrayList>() def vfModules = null def vfModuleBaseEntry = null - if (response.getStatusCode() == 200) { + if (response.getStatus() == 200) { // Parse the VNF record from A&AI to find base module info msoLogger.debug('Parsing the VNF data to find base module info') if (responseData != null) { @@ -204,7 +205,7 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { int vfModulesSize = 0 for (i in 0..vfModules.size()-1) { def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) - + Map vfModuleEntry = new HashMap() def vfModuleId = utils.getNodeText(vfModuleXml, "vf-module-id") vfModuleEntry.put("vfModuleId", vfModuleId) @@ -216,20 +217,20 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { vfModuleEntry.put("modelUuid", modelUuid) def modelCustomizationUuid = utils.getNodeText(vfModuleXml, "model-customization-id") vfModuleEntry.put("modelCustomizationUuid", modelCustomizationUuid) - + def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module") vfModuleEntry.put("isBaseVfModule", isBaseVfModule) - + String volumeGroupId = '' - + msoLogger.debug("Next module!") def vfModuleRelationships = vfModules[i].'**'.findAll {it.name() == 'relationship-data'} if (vfModuleRelationships.size() > 0) { - for (j in 0..vfModuleRelationships.size()-1) { + for (j in 0..vfModuleRelationships.size()-1) { if (vfModuleRelationships[j] != null) { - - def relationshipKey = vfModuleRelationships[j].'**'.findAll {it.name() == 'relationship-key'} - + + def relationshipKey = vfModuleRelationships[j].'**'.findAll {it.name() == 'relationship-key'} + if (relationshipKey[0] == 'volume-group.volume-group-id') { def relationshipValue = vfModuleRelationships[j].'**'.findAll {it.name() == 'relationship-value'} volumeGroupId = relationshipValue[0] @@ -238,25 +239,25 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { } } } - + vfModuleEntry.put("volumeGroupId", volumeGroupId) msoLogger.debug("volumeGroupId is: " + volumeGroupId) // Save base vf module to add it to the start of the list later - if (isBaseVfModule == "true") { + if (isBaseVfModule == "true") { vfModuleBaseEntry = vfModuleEntry } - else { + else { vfModulesList.add(vfModuleEntry) } } // Start the list with the base module if any if (vfModuleBaseEntry != null) { vfModulesList.add(0, vfModuleBaseEntry) - } + } } - - } + + } } else { msoLogger.debug('Response code from AAI GET is: ' + response.getStatusCode()) @@ -276,44 +277,44 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) } } - + public void prepareNextModuleToUpdate(DelegateExecution execution){ execution.setVariable("prefix", Prefix) msoLogger.trace("STARTED prepareNextModuleToUpdate ") - + try { int i = execution.getVariable("DUVAM_nextModule") def vfModules = execution.getVariable("DUVAM_vfModules") def vfModule = vfModules[i] - + def vfModuleId = vfModule.get("vfModuleId") execution.setVariable("DUVAM_vfModuleId", vfModuleId) - + def vfModuleName = vfModule.get("vfModuleName") execution.setVariable("DUVAM_vfModuleName", vfModuleName) - + def isBaseVfModule = vfModule.get("isBaseVfModule") execution.setVariable("DUVAM_isBaseVfModule", isBaseVfModule) - + String modelInvariantUuid = vfModule.get("modelInvariantUuid") - msoLogger.debug("ModelInvariantUuid: " + modelInvariantUuid) - + msoLogger.debug("ModelInvariantUuid: " + modelInvariantUuid) + def volumeGroupId = vfModule.get("volumeGroupId") execution.setVariable("DUVAM_volumeGroupId", volumeGroupId) execution.setVariable("DUVAM_volumeGroupName", "") - + VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition") List moduleResources = vnfResource.getVfModules() - + if (moduleResources != null && !moduleResources.isEmpty()) { - - for (j in 0..moduleResources.size()-1) { + + for (j in 0..moduleResources.size()-1) { ModelInfo modelInfo = moduleResources[j].getModelInfo() String modelInvariantUuidFromDecomposition = modelInfo.getModelInvariantUuid() msoLogger.debug("modelInvariantUuidFromDecomposition: " + modelInvariantUuidFromDecomposition) - + if (modelInvariantUuid.equals(modelInvariantUuidFromDecomposition)) { String vfModuleModelInfo = modelInfo.toJsonString() String vfModuleModelInfoValue = jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo") @@ -321,18 +322,18 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { msoLogger.debug("vfModuleModelInfo: " + vfModuleModelInfoValue) break } - + } - } - + } + }catch(Exception e){ msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareNextModuleToUpdate Method:\n" + e.getMessage()) } msoLogger.trace("COMPLETED prepareNextModuleToUpdate ") } - - + + /** * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. * @@ -344,25 +345,25 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { ')' msoLogger.trace('Entered ' + method) - - try { + + try { def vnfId = execution.getVariable('vnfId') VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition") ModelInfo vnfDecompModelInfo = vnfResource.getModelInfo() String vnfModelInfo = execution.getVariable("vnfModelInfo") String modelUuid = execution.getVariable("DUVAM_modelUuid") if (modelUuid == null || modelUuid.isEmpty()) { - modelUuid = vnfDecompModelInfo.getModelUuid() + modelUuid = vnfDecompModelInfo.getModelUuid() } String modelCustomizationUuid = execution.getVariable("DUVAM_modelCustomizationUuid") if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) { modelCustomizationUuid = vnfDecompModelInfo.getModelCustomizationUuid() - } + } String nfType = vnfResource.getNfType() String nfTypeString = '' if (nfType != null && !nfType.isEmpty()) { nfTypeString = "" + nfType + "" - } + } String nfRole = vnfResource.getNfRole() String nfRoleString = '' if (nfRole != null && !nfRole.isEmpty()) { @@ -377,8 +378,8 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { String nfNamingCodeString = '' if (nfNamingCode != null && !nfNamingCode.isEmpty()) { nfNamingCodeString = "" + nfNamingCode + "" - } - + } + String updateAAIGenericVnfRequest = """ ${MsoUtils.xmlEscape(vnfId)} @@ -394,8 +395,8 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { execution.setVariable('DUVAM_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) msoLogger.debug("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) msoLogger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) - - + + msoLogger.trace('Exited ' + method) } catch (BpmnError e) { throw e; @@ -404,7 +405,7 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) } } - + /** * APP-C Call - placeholder. * @@ -415,6 +416,6 @@ class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { 'execution=' + execution.getId() + ')' - msoLogger.trace('Entered ' + method) + msoLogger.trace('Entered ' + method) } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy index d729c770ca..22b44c9ead 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy @@ -8,7 +8,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -32,9 +32,7 @@ import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.camunda.bpm.engine.delegate.BpmnError import org.camunda.bpm.engine.impl.cmd.AbstractSetVariableCmd import org.camunda.bpm.engine.delegate.DelegateExecution -import org.onap.so.rest.APIResponse -import org.onap.so.rest.RESTClient -import org.onap.so.rest.RESTConfig + import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; import org.onap.so.bpmn.common.scripts.VidUtils; import org.onap.so.bpmn.core.RollbackData @@ -61,7 +59,7 @@ public class RollbackVnf extends VnfCmBase { private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, RollbackVnf.class); ExceptionUtil exceptionUtil = new ExceptionUtil() - JsonUtils jsonUtils = new JsonUtils() + JsonUtils jsonUtils = new JsonUtils() def prefix = "VnfIPU_" /** @@ -71,16 +69,16 @@ public class RollbackVnf extends VnfCmBase { */ public void initProcessVariables(DelegateExecution execution) { execution.setVariable('prefix', 'RVnf_') - - execution.setVariable('rollbackSuccessful', false) + + execution.setVariable('rollbackSuccessful', false) execution.setVariable('currentActivity', 'RVnf') execution.setVariable('workStep', null) execution.setVariable('failedActivity', null) - execution.setVariable('errorCode', "0") - execution.setVariable('actionUnlock', Action.Unlock) + execution.setVariable('errorCode', "0") + execution.setVariable('actionUnlock', Action.Unlock) execution.setVariable('actionStart', Action.Start) execution.setVariable('actionResumeTraffic', Action.ResumeTraffic) - + } /** @@ -97,16 +95,16 @@ public class RollbackVnf extends VnfCmBase { msoLogger.trace('Entered ' + method) initProcessVariables(execution) - + try { - + execution.setVariable("rollbackErrorCode", "0") - + if (execution.getVariable("rollbackSetClosedLoopDisabledFlag") == true) { msoLogger.debug("Will call setClosedLoopDisabledFlag") - } + } + - msoLogger.trace('Exited ' + method) } @@ -115,9 +113,9 @@ public class RollbackVnf extends VnfCmBase { msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); execution.setVariable("rollbackErrorCode", "1") exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage) - } + } } - + /** * Determine success of rollback execution. * @@ -130,7 +128,7 @@ public class RollbackVnf extends VnfCmBase { initProcessVariables(execution) msoLogger.trace('Entered ' + method) - + def rollbackErrorCode = execution.getVariable('rollbackErrorCode') if (rollbackErrorCode == "0") { execution.setVariable('rollbackSuccessful', true) @@ -140,9 +138,9 @@ public class RollbackVnf extends VnfCmBase { execution.setVariable('rollbackSuccessful', false) msoLogger.debug("rollback unsuccessful") } - - msoLogger.trace('Exited ' + method) - - } - + + msoLogger.trace('Exited ' + method) + + } + } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy index 8a3dcbab5d..7a6fd72a7d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy @@ -32,7 +32,7 @@ import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.core.json.JsonUtils import org.onap.so.logger.MessageEnum import org.onap.so.logger.MsoLogger -import org.onap.so.rest.APIResponse + import org.onap.so.client.aai.AAIResourcesClient import org.onap.so.client.aai.AAIObjectType import org.onap.so.client.aai.entities.AAIResultWrapper diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy index aa88c2ac68..06d557532b 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,7 +28,7 @@ import org.onap.so.bpmn.common.scripts.ExceptionUtil import org.onap.so.bpmn.common.scripts.MsoUtils import org.onap.so.bpmn.common.scripts.AaiUtil import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils -import org.onap.so.rest.APIResponse + import java.util.UUID; import org.camunda.bpm.engine.delegate.BpmnError @@ -44,15 +44,15 @@ import org.onap.so.logger.MsoLogger * This groovy class supports the CreateAllottedResourceTXCRollback.bpmn process. * * @author - * + * * Inputs: * @param - msoRequestId * @param - isDebugLogEnabled - * @param - disableRollback - O + * @param - disableRollback - O * @param - rollbackData * * Outputs: - * @param - rollbackError + * @param - rollbackError * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) * */ @@ -63,31 +63,31 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc ExceptionUtil exceptionUtil = new ExceptionUtil() public void preProcessRequest (DelegateExecution execution) { - + String msg = "" msoLogger.trace("start preProcessRequest") execution.setVariable("prefix", Prefix) String rbType = "DCARTXC_" try { - + def rollbackData = execution.getVariable("rollbackData") msoLogger.debug("RollbackData:" + rollbackData) if (rollbackData != null) { if (rollbackData.hasType(rbType)) { - + execution.setVariable("serviceInstanceId", rollbackData.get(rbType, "serviceInstanceId")) execution.setVariable("parentServiceInstanceId", rollbackData.get(rbType, "parentServiceInstanceId")) execution.setVariable("allottedResourceId", rollbackData.get("SERVICEINSTANCE", "allottedResourceId")) - - + + def rollbackAAI = rollbackData.get(rbType, "rollbackAAI") if ("true".equals(rollbackAAI)) { execution.setVariable("rollbackAAI",true) execution.setVariable("aaiARPath", rollbackData.get(rbType, "aaiARPath")) - + } def rollbackSDNC = rollbackData.get(rbType, "rollbackSDNCassign") if ("true".equals(rollbackSDNC)) @@ -96,11 +96,11 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc execution.setVariable("deactivateSdnc", rollbackData.get(rbType, "rollbackSDNCactivate")) execution.setVariable("deleteSdnc", rollbackData.get(rbType, "rollbackSDNCcreate")) execution.setVariable("unassignSdnc", rollbackData.get(rbType, "rollbackSDNCassign")) - + msoLogger.debug("sdncDeactivate:\n" + execution.getVariable("deactivateSdnc") ) msoLogger.debug("sdncDelete:\n" + execution.getVariable("deleteSdnc")) msoLogger.debug("sdncUnassign:\n" + execution.getVariable("unassignSdnc")) - + execution.setVariable("sdncDeactivateRequest", rollbackData.get(rbType, "sdncActivateRollbackReq")) execution.setVariable("sdncDeleteRequest", rollbackData.get(rbType, "sdncCreateRollbackReq")) execution.setVariable("sdncUnassignRequest", rollbackData.get(rbType, "sdncAssignRollbackReq")) @@ -122,7 +122,7 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc { execution.setVariable("skipRollback", true) } - + }catch(BpmnError b){ msoLogger.debug("Rethrowing MSOWorkflowException") throw b @@ -213,7 +213,7 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc } msoLogger.trace("end deleteAaiAR") } - + public void postProcessRequest(DelegateExecution execution) { msoLogger.trace("start postProcessRequest") @@ -236,7 +236,7 @@ public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProc } } - + public void processRollbackException(DelegateExecution execution){ msoLogger.trace("start processRollbackException") diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegate.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegate.java index 8e57121876..469069e136 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegate.java +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/pnf/delegate/CheckAaiForCorrelationIdDelegate.java @@ -41,7 +41,6 @@ import org.springframework.stereotype.Component; * Outputs: * - aaiContainsInfoAboutPnf - local Boolean */ - @Component public class CheckAaiForCorrelationIdDelegate implements JavaDelegate { private AaiConnection aaiConnection; diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java index f5be34bf92..ab8d206a62 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java +++ b/bpmn/so-bpmn-infrastructure-common/src/test/java/org/onap/so/bpmn/infrastructure/pnf/delegate/PnfCheckInputsTest.java @@ -38,7 +38,7 @@ public class PnfCheckInputsTest { private static final String DEFAULT_TIMEOUT = "P1D"; @Rule - public ExpectedException expectedException = ExpectedException.none(); + public ExpectedException expectedException = ExpectedException.none(); private DelegateExecution mockDelegateExecution() { new PnfCheckInputs(DEFAULT_TIMEOUT); diff --git a/bpmn/so-bpmn-infrastructure-flows/pom.xml b/bpmn/so-bpmn-infrastructure-flows/pom.xml index 1afd2cb233..b3275eb6ec 100644 --- a/bpmn/so-bpmn-infrastructure-flows/pom.xml +++ b/bpmn/so-bpmn-infrastructure-flows/pom.xml @@ -7,7 +7,7 @@ 4.0.0 so-bpmn-infrastructure-flows - jar + jar @@ -34,7 +34,7 @@ - org.eclipse.m2e @@ -134,7 +134,7 @@ camunda-bpm-spring-boot-starter-webapp ${camunda.springboot.version} test - + org.springframework.boot spring-boot-starter-test @@ -211,11 +211,6 @@ javax.ws.rs-api ${jax.ws.rs} - - org.onap.so - MSORESTClient - ${project.version} - org.camunda.spin camunda-spin-core diff --git a/bpmn/so-bpmn-tasks/pom.xml b/bpmn/so-bpmn-tasks/pom.xml index 95e3a3ed07..63a65cdc24 100644 --- a/bpmn/so-bpmn-tasks/pom.xml +++ b/bpmn/so-bpmn-tasks/pom.xml @@ -14,6 +14,38 @@ 1.8 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + + + default-test + + test + + + + **/UnitTestSuite.java + + + + + integration-test + + test + + + + **/IntegrationTestSuite.java + + + + + + + diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java index 0190f3df56..7d0927e498 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/buildingblock/SniroHomingV2.java @@ -29,7 +29,6 @@ import java.util.UUID; import org.apache.commons.lang.SerializationUtils; import org.camunda.bpm.engine.delegate.BpmnError; -import org.camunda.bpm.engine.delegate.DelegateExecution; import org.json.JSONArray; import org.json.JSONObject; import org.onap.so.bpmn.common.BuildingBlockExecution; @@ -107,7 +106,7 @@ public class SniroHomingV2 { * @param execution */ public void callSniro(BuildingBlockExecution execution){ - log.trace("Started Sniro Homing Call Sniro"); + log.debug("Started Sniro Homing Call Sniro"); try{ GeneralBuildingBlock bb = execution.getGeneralBuildingBlock(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java index 1fe3143c4a..4506699ce8 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasks.java @@ -22,6 +22,7 @@ package org.onap.so.bpmn.infrastructure.sdnc.tasks; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; @@ -46,10 +47,17 @@ public class SDNCQueryTasks { @Autowired private ExtractPojosForBB extractPojosForBB; - public void queryVnf(BuildingBlockExecution execution) throws Exception { + public void queryVnf(BuildingBlockExecution execution) throws Exception { + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + String selfLink = "restconf/config/GENERIC-RESOURCE-API:services/service/" + + serviceInstance.getServiceInstanceId() + "/service-data/vnfs/vnf/" + + genericVnf.getVnfId() + "/vnf-data/vnf-topology/"; try { + if(genericVnf.getSelflink() == null) { + genericVnf.setSelflink(selfLink); + } String response = sdncVnfResources.queryVnf(genericVnf); execution.setVariable("SDNCQueryResponse_" + genericVnf.getVnfId(), response); } catch (Exception ex) { @@ -59,12 +67,18 @@ public class SDNCQueryTasks { public void queryVfModule(BuildingBlockExecution execution) throws Exception { + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); - + String selfLink = "restconf/config/GENERIC-RESOURCE-API:services/service/" + + serviceInstance.getServiceInstanceId() + "/service-data/vnfs/vnf/" + + genericVnf.getVnfId() + "/vnf-data/vf-modules/vf-module/" + + vfModule.getVfModuleId() + "/vf-module-data/vf-module-topology/"; try { + vfModule.setSelflink(selfLink); if(vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) { String response = sdncVfModuleResources.queryVfModule(vfModule); - execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), response); + execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), response); } else { throw new Exception("Vf Module " + vfModule.getVfModuleId() + " exists in gBuildingBlock but does not have a selflink value"); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java new file mode 100644 index 0000000000..fedec4f732 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasks.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.sdnc.tasks; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.onap.so.client.exception.BadResponseException; +import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.client.exception.MapperException; +import org.onap.so.client.sdnc.SDNCClient; +import org.onap.so.client.sdnc.beans.SDNCRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.jayway.jsonpath.JsonPath; + +@Component +public class SDNCRequestTasks { + + private static final Logger logger = LoggerFactory.getLogger(SDNCRequestTasks.class); + + private static final String SDNC_REQUEST = "SDNCRequest"; + private static final String MESSAGE = "_MESSAGE"; + private static final String CORRELATOR = "_CORRELATOR"; + protected static final String IS_CALLBACK_COMPLETED = "isCallbackCompleted"; + + @Autowired + private ExceptionBuilder exceptionBuilder; + + @Autowired + private SDNCClient sdncClient; + + public void createCorrelationVariables (DelegateExecution execution) { + SDNCRequest request = (SDNCRequest)execution.getVariable(SDNC_REQUEST); + execution.setVariable(request.getCorrelationName()+CORRELATOR, request.getCorrelationValue()); + execution.setVariable("sdncTimeout", request.getTimeOut()); + } + + public void callSDNC (DelegateExecution execution) { + SDNCRequest request = (SDNCRequest)execution.getVariable(SDNC_REQUEST); + try { + String response = sdncClient.post(request.getSDNCPayload(),request.getTopology()); + String finalMessageIndicator = JsonPath.read(response, "$.output.ack-final-indicator"); + execution.setVariable("isSDNCCompleted", convertIndicatorToBoolean(finalMessageIndicator)); + } catch (MapperException e) { + logger.error("Error Parsing SDNC Response", e); + exceptionBuilder.buildAndThrowWorkflowException(execution, 7000,"Error Parsing SDNC Response"); + } catch (BadResponseException e) { + logger.error("Error Reading SDNC Response", e); + exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, "Error Reading SDNC Response"); + } + } + + public void processCallback (DelegateExecution execution) { + try { + SDNCRequest request = (SDNCRequest)execution.getVariable(SDNC_REQUEST); + String asyncRequest = (String) execution.getVariable(request.getCorrelationName()+MESSAGE); + String finalMessageIndicator = JsonPath.read(asyncRequest, "$.input.ack-final-indicator"); + boolean isCallbackCompleted = convertIndicatorToBoolean(finalMessageIndicator); + execution.setVariable(IS_CALLBACK_COMPLETED, isCallbackCompleted); + } catch (Exception e) { + logger.error("Error procesing SDNC callback", e); + exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, "Error procesing SDNC callback"); + } + } + + public void handleTimeOutException (DelegateExecution execution) { + exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, "Error timed out waiting on SDNC Async-Response"); + } + + public void handleSyncError (DelegateExecution execution) { + String msg = (String) execution.getVariable("SDNCSyncError"); + exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg); + } + + protected boolean convertIndicatorToBoolean(String finalMessageIndicator) { + return "Y".equals(finalMessageIndicator); + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java index fabe8a159d..505c61da6b 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasks.java @@ -201,30 +201,11 @@ public class WorkflowActionBBTasks { execution.setVariable("mso-service-instance-id", resourceId); } - public void setupFalloutHandler(DelegateExecution execution) { - final String requestId = (String) execution.getVariable(G_REQUEST_ID); - final String action = (String) execution.getVariable(G_ACTION); - final String resourceId = (String) execution.getVariable("resourceId"); - String exceptionMsg = ""; - if (execution.getVariable("WorkflowActionErrorMessage") != null) { - exceptionMsg = (String) execution.getVariable("WorkflowActionErrorMessage"); - } else { - exceptionMsg = "Error in WorkflowAction"; - } - execution.setVariable("mso-service-instance-id", resourceId); - execution.setVariable("mso-request-id", requestId); - String falloutRequest = "" - + requestId + "" + action - + "VID" - + exceptionMsg - + "7000"; - execution.setVariable("falloutRequest", falloutRequest); - } - public void checkRetryStatus(DelegateExecution execution) { String handlingCode = (String) execution.getVariable("handlingCode"); int retryCount = (int) execution.getVariable(RETRY_COUNT); if (handlingCode.equals("Retry")){ + updateRequestErrorStatusMessage(execution); if(retryCount<5){ int currSequence = (int) execution.getVariable("gCurrentSequence"); execution.setVariable("gCurrentSequence", currSequence-1); @@ -266,6 +247,19 @@ public class WorkflowActionBBTasks { rollbackFlows.add(flowsToExecute.get(i)); } } + + int flowSize = rollbackFlows.size(); + String handlingCode = (String) execution.getVariable("handlingCode"); + if(handlingCode.equals("RollbackToAssigned")){ + for(int i = 0; i> STOClient = new BaseClient<>(); + private BaseClient> STOClient = new BaseClient<>(); @Autowired private SDNCProperties properties; @@ -64,9 +64,20 @@ public class SDNCClient { STOClient.setTargetUrl(targetUrl); HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth()); STOClient.setHttpHeader(httpHeader); - LinkedHashMap output = STOClient.post(jsonRequest, new ParameterizedTypeReference>() {}); + LinkedHashMap output = STOClient.post(jsonRequest, new ParameterizedTypeReference>() {}); return sdnCommonTasks.validateSDNResponse(output); } + + + public String post(Object request, String url) throws MapperException, BadResponseException { + String jsonRequest = sdnCommonTasks.buildJsonRequest(request); + STOClient.setTargetUrl(url); + HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth()); + STOClient.setHttpHeader(httpHeader); + LinkedHashMap output = STOClient.post(jsonRequest, new ParameterizedTypeReference>() {}); + return sdnCommonTasks.validateSDNResponse(output); +} + /** * @@ -86,7 +97,7 @@ public class SDNCClient { STOClient.setTargetUrl(targetUrl); HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth()); STOClient.setHttpHeader(httpHeader); - LinkedHashMap output = STOClient.get(jsonRequest, new ParameterizedTypeReference>() {}); + LinkedHashMap output = STOClient.get(jsonRequest, new ParameterizedTypeReference>() {}); return sdnCommonTasks.validateSDNGetResponse(output); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java index ee1d432b6f..37e13fb8d8 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SdnCommonTasks.java @@ -92,13 +92,13 @@ public class SdnCommonTasks { * @return * @throws BadResponseException */ - public String validateSDNResponse(LinkedHashMap output) throws BadResponseException { + public String validateSDNResponse(LinkedHashMap output) throws BadResponseException { if (CollectionUtils.isEmpty(output)) { msoLogger.error(MessageEnum.RA_RESPONSE_FROM_SDNC, NO_RESPONSE_FROM_SDNC, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, NO_RESPONSE_FROM_SDNC); throw new BadResponseException(NO_RESPONSE_FROM_SDNC); } - LinkedHashMap embeddedResponse =(LinkedHashMap) output.get("output"); + LinkedHashMap embeddedResponse =(LinkedHashMap) output.get("output"); String responseCode = ""; String responseMessage = ""; if (embeddedResponse != null) { @@ -125,7 +125,7 @@ public class SdnCommonTasks { * @return * @throws BadResponseException */ - public String validateSDNGetResponse(LinkedHashMap output) throws BadResponseException { + public String validateSDNGetResponse(LinkedHashMap output) throws BadResponseException { if (CollectionUtils.isEmpty(output)) { msoLogger.error(MessageEnum.RA_RESPONSE_FROM_SDNC, NO_RESPONSE_FROM_SDNC, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, NO_RESPONSE_FROM_SDNC); throw new BadResponseException(NO_RESPONSE_FROM_SDNC); @@ -143,6 +143,7 @@ public class SdnCommonTasks { msoLogger.debug("Received from GET request: " + stringOutput); return stringOutput; } + private boolean isHttpCodeSuccess(int code) { return code >= HttpStatus.SC_OK && code < HttpStatus.SC_MULTIPLE_CHOICES || code == 0; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java new file mode 100644 index 0000000000..3ee560f4f4 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/beans/SDNCRequest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.sdnc.beans; + +import java.io.Serializable; +import java.time.Duration; +import java.util.UUID; + +import org.onap.so.client.sdnc.endpoint.SDNCTopology; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.apache.commons.lang3.builder.EqualsBuilder; + +public class SDNCRequest implements Serializable{ + + /** + * + */ + private static final long serialVersionUID = 4679678988657593282L; + private String timeOut = "PT1H"; + private SDNCTopology topology; + private String CorrelationValue = UUID.randomUUID().toString(); + private String CorrelationName = "SDNCCallback"; + private Object SDNCPayload; + + + public String getTimeOut() { + return timeOut; + } + + public void setTimeOut(String timeOut) { + this.timeOut = timeOut; + } + + public SDNCTopology getTopology() { + return topology; + } + + public void setTopology(SDNCTopology topology) { + this.topology = topology; + } + + public String getCorrelationValue() { + return CorrelationValue; + } + public void setCorrelationValue(String correlationValue) { + CorrelationValue = correlationValue; + } + public String getCorrelationName() { + return CorrelationName; + } + public void setCorrelationName(String correlationName) { + CorrelationName = correlationName; + } + public Object getSDNCPayload() { + return SDNCPayload; + } + public void setSDNCPayload(Object sDNCPayload) { + SDNCPayload = sDNCPayload; + } + + @Override + public boolean equals(final Object other) { + if (!(other instanceof SDNCRequest)) { + return false; + } + SDNCRequest castOther = (SDNCRequest) other; + return new EqualsBuilder().append(CorrelationValue, castOther.CorrelationValue) + .append(CorrelationName, castOther.CorrelationName).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(CorrelationValue).append(CorrelationName).toHashCode(); + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java index 76a947a299..2cd0947fa8 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java @@ -20,6 +20,8 @@ package org.onap.so.client.sdnc.mapper; +import java.net.URI; + import org.onap.sdnc.northbound.client.model.*; import org.onap.so.bpmn.servicedecomposition.bbobjects.*; import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; @@ -37,11 +39,10 @@ public class GCTopologyOperationRequestMapper { RequestContext requestContext, Customer customer, Configuration vnrConfiguration, - GenericVnf voiceVnf) { + GenericVnf voiceVnf, String sdncReqId,URI callbackUri) { GenericResourceApiGcTopologyOperationInformation req = new GenericResourceApiGcTopologyOperationInformation(); - String sdncReqId = requestContext.getMsoRequestId(); - GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId);// TODO Set URL + GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId,callbackUri.toString()); GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(sdncReqId, reqAction); GenericResourceApiServiceinformationServiceInformation serviceInformation = generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, false); GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation = generalTopologyObjectMapper.buildConfigurationInformation(vnrConfiguration,true); @@ -60,12 +61,11 @@ public class GCTopologyOperationRequestMapper { public GenericResourceApiGcTopologyOperationInformation deactivateOrUnassignVnrReqMapper(SDNCSvcAction svcAction, ServiceInstance serviceInstance, RequestContext requestContext, - Configuration vnrConfiguration) { + Configuration vnrConfiguration, String sdncReqId, URI callbackUri) { - GenericResourceApiGcTopologyOperationInformation req = new GenericResourceApiGcTopologyOperationInformation(); - String sdncReqId = requestContext.getMsoRequestId(); + GenericResourceApiGcTopologyOperationInformation req = new GenericResourceApiGcTopologyOperationInformation(); GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = - generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId);// TODO Set URL + generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId,callbackUri.toString()); GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper .buildGenericResourceApiRequestinformationRequestInformation(sdncReqId, GenericResourceApiRequestActionEnumeration.DELETEGENERICCONFIGURATIONINSTANCE); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java index 3975b25356..9bbd665e4c 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java @@ -24,11 +24,14 @@ import org.onap.sdnc.northbound.client.model.*; import org.onap.so.bpmn.servicedecomposition.bbobjects.*; import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; import org.onap.so.client.sdnc.beans.SDNCSvcAction; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.onap.so.client.exception.MapperException; @Component public class GeneralTopologyObjectMapper { + /* * Build GenericResourceApiRequestinformationRequestInformation @@ -135,10 +138,17 @@ public class GeneralTopologyObjectMapper { vfModuleInformation.setFromPreload(null); return vfModuleInformation; } + + public GenericResourceApiSdncrequestheaderSdncRequestHeader buildSdncRequestHeader(SDNCSvcAction svcAction, String sdncReqId){ + return buildSdncRequestHeader(svcAction, sdncReqId, null); + } + + public GenericResourceApiSdncrequestheaderSdncRequestHeader buildSdncRequestHeader(SDNCSvcAction svcAction, String sdncReqId, String callbackUrl){ GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = new GenericResourceApiSdncrequestheaderSdncRequestHeader(); sdncRequestHeader.setSvcAction(svcAction.getSdncApiAction()); sdncRequestHeader.setSvcRequestId(sdncReqId); + sdncRequestHeader.setSvcNotificationUrl(callbackUrl); return sdncRequestHeader; } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java index eb12278528..7f09305d95 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroClient.java @@ -72,12 +72,12 @@ public class SniroClient { header.set("X-patchVersion", managerProperties.getHeaders().get("patchVersion")); header.set("X-minorVersion", managerProperties.getHeaders().get("minorVersion")); header.set("X-latestVersion", managerProperties.getHeaders().get("latestVersion")); - BaseClient> baseClient = new BaseClient<>(); + BaseClient> baseClient = new BaseClient<>(); baseClient.setTargetUrl(url); baseClient.setHttpHeader(header); - LinkedHashMap response = baseClient.post(homingRequest.toJsonString(), new ParameterizedTypeReference>() {}); + LinkedHashMap response = baseClient.post(homingRequest.toJsonString(), new ParameterizedTypeReference>() {}); validator.validateDemandsResponse(response); log.trace("Completed Sniro Client Post Demands"); } @@ -102,12 +102,12 @@ public class SniroClient { HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_JSON); header.set("Authorization", UrnPropertiesReader.getVariable("sniro.conductor.headers.auth")); - BaseClient> baseClient = new BaseClient<>(); + BaseClient> baseClient = new BaseClient<>(); baseClient.setTargetUrl(url); baseClient.setHttpHeader(header); - LinkedHashMap response = baseClient.post(releaseRequest.toJsonString(), new ParameterizedTypeReference>() {}); + LinkedHashMap response = baseClient.post(releaseRequest.toJsonString(), new ParameterizedTypeReference>() {}); SniroValidator v = new SniroValidator(); v.validateReleaseResponse(response); log.trace("Completed Sniro Client Post Release"); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java index bad45c87f2..0d0c1be5aa 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sniro/SniroValidator.java @@ -43,7 +43,7 @@ public class SniroValidator { * * @throws BadResponseException */ - public void validateDemandsResponse(LinkedHashMap response) throws BadResponseException { + public void validateDemandsResponse(LinkedHashMap response) throws BadResponseException { log.debug("Validating Sniro Managers synchronous response"); if(!response.isEmpty()){ JSONObject jsonResponse = new JSONObject(response); @@ -105,7 +105,7 @@ public class SniroValidator { * * @throws BadResponseException */ - public void validateReleaseResponse(LinkedHashMap response) throws BadResponseException { + public void validateReleaseResponse(LinkedHashMap response) throws BadResponseException { log.debug("Validating Sniro Conductors response"); if(!response.isEmpty()){ String status = (String) response.get("status"); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/AllIntegrationTestSuites.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/AllIntegrationTestSuites.java new file mode 100644 index 0000000000..8a57d5d43a --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/AllIntegrationTestSuites.java @@ -0,0 +1,12 @@ +package org.onap.so; + +import org.junit.runner.RunWith; + +import com.googlecode.junittoolbox.SuiteClasses; +import com.googlecode.junittoolbox.WildcardPatternSuite; + +@RunWith(WildcardPatternSuite.class) +@SuiteClasses({"**/SniroHomingV2IT.class"}) +public class AllIntegrationTestSuites{ + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/BaseIntegrationTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/BaseIntegrationTest.java index 4bf6f0e185..6500e3a850 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/BaseIntegrationTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/BaseIntegrationTest.java @@ -22,13 +22,16 @@ package org.onap.so; import java.io.IOException; import java.io.InputStream; +import org.junit.Before; import org.junit.runner.RunWith; import org.onap.so.bpmn.buildingblock.SniroHomingV2; import org.onap.so.bpmn.common.data.TestDataSetup; import org.onap.so.client.appc.ApplicationControllerAction; import org.onap.so.client.orchestration.SDNOHealthCheckResources; import org.onap.so.client.sdnc.SDNCClient; +import org.onap.so.client.sniro.SniroClient; import org.onap.so.db.catalog.client.CatalogDbClient; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; @@ -37,29 +40,40 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; +import com.github.tomakehurst.wiremock.client.WireMock; + @RunWith(SpringRunner.class) @SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") @ContextConfiguration @AutoConfigureWireMock(port = 0) public abstract class BaseIntegrationTest extends TestDataSetup { - + + @Value("${wiremock.server.port}") + protected String wireMockPort; + @SpyBean protected SDNCClient SPY_sdncClient; - + @SpyBean protected SDNOHealthCheckResources MOCK_sdnoHealthCheckResources; - @MockBean + @SpyBean protected SniroHomingV2 sniroHoming; - + + @SpyBean + protected SniroClient sniroClient; + @MockBean protected ApplicationControllerAction appCClient; - - + @MockBean protected CatalogDbClient catalogDbClient; - + + @Before + public void baseTestBefore() { + WireMock.reset(); + } public String readResourceFile(String fileName) { InputStream stream; try { @@ -73,7 +87,7 @@ public abstract class BaseIntegrationTest extends TestDataSetup { stream.close(); return ""; } - } catch (IOException e) { + } catch (IOException e) { return ""; } } @@ -85,7 +99,7 @@ public abstract class BaseIntegrationTest extends TestDataSetup { throw new IOException("Can't access resource '" + resourceName + "'"); } return stream; - } + } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/IntegrationTestSuite.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/IntegrationTestSuite.java new file mode 100644 index 0000000000..ab999a9889 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/IntegrationTestSuite.java @@ -0,0 +1,12 @@ +package org.onap.so; + +import org.junit.runner.RunWith; + +import com.googlecode.junittoolbox.SuiteClasses; +import com.googlecode.junittoolbox.WildcardPatternSuite; + +@RunWith(WildcardPatternSuite.class) +@SuiteClasses({"**/*IT.class"}) +public class IntegrationTestSuite { + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/UnitTestSuite.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/UnitTestSuite.java new file mode 100644 index 0000000000..5ac9f229f6 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/UnitTestSuite.java @@ -0,0 +1,13 @@ +package org.onap.so; + + +import org.junit.runner.RunWith; + +import com.googlecode.junittoolbox.SuiteClasses; +import com.googlecode.junittoolbox.WildcardPatternSuite; + +@RunWith(WildcardPatternSuite.class) +@SuiteClasses({"**/*Test.class"}) +public class UnitTestSuite { + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java index 09ca0e543e..95201d555d 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/BaseTaskTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,6 +23,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.bpmn.buildingblock.SniroHomingV2; import org.onap.so.bpmn.common.InjectionHelper; import org.onap.so.bpmn.common.data.TestDataSetup; import org.onap.so.bpmn.infrastructure.flowspecific.tasks.AssignNetworkBBUtils; @@ -51,89 +52,92 @@ import org.onap.so.client.orchestration.SDNCVnfResources; import org.onap.so.client.orchestration.VnfAdapterVfModuleResources; import org.onap.so.client.orchestration.VnfAdapterVolumeGroupResources; import org.onap.so.client.sdnc.SDNCClient; +import org.onap.so.client.sniro.SniroClient; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.db.request.client.RequestsDbClient; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.test.mock.mockito.SpyBean; @RunWith(MockitoJUnitRunner.Silent.class) public abstract class BaseTaskTest extends TestDataSetup { @Mock protected AAIVolumeGroupResources aaiVolumeGroupResources; - + @Mock protected AAIServiceInstanceResources aaiServiceInstanceResources; - + @Mock protected AAIVnfResources aaiVnfResources; - + @Mock protected AAIVfModuleResources aaiVfModuleResources; - + @Mock protected AAIVpnBindingResources aaiVpnBindingResources; - + @Mock protected AAINetworkResources aaiNetworkResources; - + @Mock protected AAICollectionResources aaiCollectionResources; - + @Mock protected NetworkAdapterResources networkAdapterResources; - + @Mock protected VnfAdapterVolumeGroupResources vnfAdapterVolumeGroupResources; - + @Mock protected VnfAdapterVfModuleResources vnfAdapterVfModuleResources; - + @Mock protected SDNCVnfResources sdncVnfResources; - + @Mock protected SDNCNetworkResources sdncNetworkResources; - + @Mock protected SDNCVfModuleResources sdncVfModuleResources; - + @Mock protected SDNCServiceInstanceResources sdncServiceInstanceResources; - + @Mock protected AssignNetworkBBUtils assignNetworkBBUtils; - + @Mock protected NetworkAdapterObjectMapper networkAdapterObjectMapper; - + @Mock protected AAIInstanceGroupResources aaiInstanceGroupResources; - + @Mock protected ApplicationControllerAction appCClient; - + @Mock protected CatalogDbClient catalogDbClient; - + @Mock protected RequestsDbClient requestsDbClient; - + @Mock protected BBInputSetupUtils bbSetupUtils; - + @Mock protected BBInputSetup bbInputSetup; @Mock protected AAIConfigurationResources aaiConfigurationResources; - + @Mock protected AAIObjectMapper MOCK_aaiObjectMapper; @Mock protected InjectionHelper MOCK_injectionHelper; - + @Mock - protected AAIResourcesClient MOCK_aaiResourcesClient; + protected AAIResourcesClient MOCK_aaiResourcesClient; @Mock protected ExtractPojosForBB extractPojosForBB; @@ -141,4 +145,5 @@ public abstract class BaseTaskTest extends TestDataSetup { @Mock protected ExceptionBuilder exceptionUtil; + } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/data/TestDataSetup.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/data/TestDataSetup.java index 1901a08f28..c96c38dab1 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/data/TestDataSetup.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/data/TestDataSetup.java @@ -478,6 +478,8 @@ public class TestDataSetup{ modelInfoGenericVnf.setModelInvariantUuid("testModelInvariantUUID" + genericVnfCounter); modelInfoGenericVnf.setModelVersion("testModelVersion" + genericVnfCounter); modelInfoGenericVnf.setModelUuid("testModelUUID" + genericVnfCounter); + modelInfoGenericVnf.setModelInstanceName("testInstanceName" + genericVnfCounter); + genericVnf.setModelInfoGenericVnf(modelInfoGenericVnf); License license = new License(); @@ -652,6 +654,7 @@ public class TestDataSetup{ modelInfo.setModelName("testProxyModelName" + uniqueIdentifier); modelInfo.setModelUuid("testProxyModelUuid" + uniqueIdentifier); modelInfo.setModelVersion("testProxyModelVersion" + uniqueIdentifier); + modelInfo.setModelInstanceName("testProxyInstanceName" + uniqueIdentifier); serviceProxy.setModelInfoServiceProxy(modelInfo); @@ -663,10 +666,11 @@ public class TestDataSetup{ ar.setId("testAllottedResourceId" + uniqueIdentifier); ModelInfoAllottedResource modelInfo = new ModelInfoAllottedResource(); - modelInfo.setModelInvariantUuid("testProxyModelInvariantUuid" + uniqueIdentifier); - modelInfo.setModelName("testProxyModelName" + uniqueIdentifier); - modelInfo.setModelUuid("testProxyModelUuid" + uniqueIdentifier); - modelInfo.setModelVersion("testProxyModelVersion" + uniqueIdentifier); + modelInfo.setModelInvariantUuid("testAllottedModelInvariantUuid" + uniqueIdentifier); + modelInfo.setModelName("testAllottedModelName" + uniqueIdentifier); + modelInfo.setModelUuid("testAllottedModelUuid" + uniqueIdentifier); + modelInfo.setModelVersion("testAllottedModelVersion" + uniqueIdentifier); + modelInfo.setModelInstanceName("testAllottedModelInstanceName" + uniqueIdentifier); ar.setModelInfoAllottedResource(modelInfo); @@ -688,7 +692,7 @@ public class TestDataSetup{ serviceInstance.setConfigurations(configurations); return config; } - + public Subnet buildSubnet() { Subnet subnet = new Subnet(); subnet.setSubnetId("testSubnetId"); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java index 52a64f4863..bf66283b17 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasksTest.java @@ -35,6 +35,7 @@ import static org.mockito.Mockito.when; import java.util.HashMap; import org.camunda.bpm.engine.delegate.BpmnError; +import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatchers; diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java new file mode 100644 index 0000000000..9cf1a1cdc9 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksIT.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.appc.tasks; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.HashMap; +import java.util.Optional; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.client.lcm.model.Action; +import org.onap.so.BaseIntegrationTest; +import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; +import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; +import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestParameters; +import org.onap.so.db.catalog.beans.ControllerSelectionReference; +import org.springframework.beans.factory.annotation.Autowired; + +public class AppcRunTasksIT extends BaseIntegrationTest { + + @Autowired + private AppcRunTasks appcRunTasks; + + private GenericVnf genericVnf; + private RequestContext requestContext; + private String msoRequestId; + + @Before + public void before() { + genericVnf = setGenericVnf(); + msoRequestId = UUID.randomUUID().toString(); + requestContext = setRequestContext(); + requestContext.setMsoRequestId(msoRequestId); + gBBInput.setRequestContext(requestContext); + } + + @Test + public void preProcessActivityTest() throws Exception { + appcRunTasks.preProcessActivity(execution); + assertEquals(execution.getVariable("actionQuiesceTraffic"), Action.QuiesceTraffic); + assertEquals(execution.getVariable("rollbackQuiesceTraffic"), false); + } + + @Test + public void runAppcCommandTest() throws Exception { + Action action = Action.QuiesceTraffic; + ControllerSelectionReference controllerSelectionReference = new ControllerSelectionReference(); + controllerSelectionReference.setControllerName("testName"); + controllerSelectionReference.setActionCategory(action.toString()); + controllerSelectionReference.setVnfType("testVnfType"); + + doReturn(controllerSelectionReference).when(catalogDbClient).getControllerSelectionReferenceByVnfTypeAndActionCategory(genericVnf.getVnfType(), Action.QuiesceTraffic.toString()); + + execution.setVariable("aicIdentity", "testAicIdentity"); + + String vnfId = genericVnf.getVnfId(); + genericVnf.setIpv4OamAddress("testOamIpAddress"); + String payload = "{\"testName\":\"testValue\",}"; + RequestParameters requestParameters = new RequestParameters(); + requestParameters.setPayload(payload); + gBBInput.getRequestContext().setRequestParameters(requestParameters); + + String controllerType = "testName"; + HashMap payloadInfo = new HashMap(); + payloadInfo.put("vnfName", "testVnfName1"); + payloadInfo.put("aicIdentity", "testAicIdentity"); + payloadInfo.put("vnfHostIpAddress", "testOamIpAddress"); + payloadInfo.put("vserverIdList", null); + payloadInfo.put("vfModuleId", null); + payloadInfo.put("identityUrl", null); + payloadInfo.put("vmIdList", null); + + doNothing().when(appCClient).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType); + + appcRunTasks.runAppcCommand(execution, action); + verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType); + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksITTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksITTest.java deleted file mode 100644 index 942553b1dc..0000000000 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksITTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.so.bpmn.infrastructure.appc.tasks; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.util.HashMap; -import java.util.Optional; -import java.util.UUID; - -import org.junit.Before; -import org.junit.Test; -import org.onap.appc.client.lcm.model.Action; -import org.onap.so.BaseIntegrationTest; -import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; -import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; -import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestParameters; -import org.onap.so.db.catalog.beans.ControllerSelectionReference; -import org.springframework.beans.factory.annotation.Autowired; - -public class AppcRunTasksITTest extends BaseIntegrationTest { - - @Autowired - private AppcRunTasks appcRunTasks; - - private GenericVnf genericVnf; - private RequestContext requestContext; - private String msoRequestId; - - @Before - public void before() { - genericVnf = setGenericVnf(); - msoRequestId = UUID.randomUUID().toString(); - requestContext = setRequestContext(); - requestContext.setMsoRequestId(msoRequestId); - gBBInput.setRequestContext(requestContext); - } - - @Test - public void preProcessActivityTest() throws Exception { - appcRunTasks.preProcessActivity(execution); - assertEquals(execution.getVariable("actionQuiesceTraffic"), Action.QuiesceTraffic); - assertEquals(execution.getVariable("rollbackQuiesceTraffic"), false); - } - - @Test - public void runAppcCommandTest() throws Exception { - Action action = Action.QuiesceTraffic; - ControllerSelectionReference controllerSelectionReference = new ControllerSelectionReference(); - controllerSelectionReference.setControllerName("testName"); - controllerSelectionReference.setActionCategory(action.toString()); - controllerSelectionReference.setVnfType("testVnfType"); - - doReturn(controllerSelectionReference).when(catalogDbClient).getControllerSelectionReferenceByVnfTypeAndActionCategory(genericVnf.getVnfType(), Action.QuiesceTraffic.toString()); - - execution.setVariable("aicIdentity", "testAicIdentity"); - - String vnfId = genericVnf.getVnfId(); - genericVnf.setIpv4OamAddress("testOamIpAddress"); - String payload = "{\"testName\":\"testValue\",}"; - RequestParameters requestParameters = new RequestParameters(); - requestParameters.setPayload(payload); - gBBInput.getRequestContext().setRequestParameters(requestParameters); - - String controllerType = "testName"; - HashMap payloadInfo = new HashMap(); - payloadInfo.put("vnfName", "testVnfName1"); - payloadInfo.put("aicIdentity", "testAicIdentity"); - payloadInfo.put("vnfHostIpAddress", "testOamIpAddress"); - payloadInfo.put("vserverIdList", null); - payloadInfo.put("vfModuleId", null); - payloadInfo.put("identityUrl", null); - payloadInfo.put("vmIdList", null); - - doNothing().when(appCClient).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType); - - appcRunTasks.runAppcCommand(execution, action); - verify(appCClient, times(1)).runAppCCommand(action, msoRequestId, vnfId, Optional.of(payload), payloadInfo, controllerType); - } -} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java new file mode 100644 index 0000000000..f0bb6a369c --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2IT.java @@ -0,0 +1,496 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.flowspecific.tasks; + +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.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.delegate.BpmnError; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.onap.so.bpmn.servicedecomposition.bbobjects.AllottedResource; +import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer; +import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceProxy; +import org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBondingLink; +import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; +import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestParameters; +import org.onap.so.bpmn.servicedecomposition.homingobjects.Candidate; +import org.onap.so.bpmn.servicedecomposition.homingobjects.CandidateType; +import org.onap.so.client.exception.BadResponseException; +import org.onap.so.client.sniro.beans.SniroManagerRequest; +import org.onap.so.BaseIntegrationTest; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class SniroHomingV2IT extends BaseIntegrationTest{ + + private ServiceInstance serviceInstance; + + private RequestContext requestContext; + + private Customer customer; + ObjectMapper mapper = new ObjectMapper(); + + private static final String RESOURCE_PATH = "__files/BuildingBlocks/SniroHoming/"; + + + String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"corys cool\", \"requestStatus\": \"accepted\"}"; + + @Before + public void before() { + serviceInstance = setServiceInstance(); + customer = setCustomer(); + customer.setGlobalCustomerId("testCustomerId"); + customer.setSubscriberName("testCustomerName"); + customer.getServiceSubscription().getServiceInstances().add(serviceInstance); + + requestContext = setRequestContext(); + requestContext.setMsoRequestId("testRequestId"); + RequestParameters params = new RequestParameters(); + params.setaLaCarte(false); + params.setSubscriptionServiceType("iptollfree"); + requestContext.setRequestParameters(params); + } + + public void beforeVpnBondingLink(String id){ + VpnBondingLink bondingLink = new VpnBondingLink(); + bondingLink.setVpnBondingLinkId("testVpnBondingId" + id); + bondingLink.getServiceProxies().add(setServiceProxy("1", "transport")); + ServiceProxy sp2 = setServiceProxy("2", "infrastructure"); + Candidate requiredCandidate = new Candidate(); + requiredCandidate.setCandidateType(CandidateType.VNF_ID); + List c = new ArrayList(); + c.add("testVnfId"); + requiredCandidate.setCandidates(c); + sp2.addRequiredCandidates(requiredCandidate); + bondingLink.getServiceProxies().add(sp2); + serviceInstance.getVpnBondingLinks().add(bondingLink); + + } + + public void beforeAllottedResource(){ + serviceInstance.getAllottedResources().add(setAllottedResource("1")); + serviceInstance.getAllottedResources().add(setAllottedResource("2")); + serviceInstance.getAllottedResources().add(setAllottedResource("3")); + } + + public void beforeVnf(){ + setGenericVnf(); + } + + @Test(expected = Test.None.class) + public void testCallSniro_success_1VpnLink() throws BadResponseException, IOException{ + beforeVpnBondingLink("1"); + + stubFor(post(urlEqualTo("/sniro/api/placement/v2")) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(mockResponse))); + + sniroHoming.callSniro(execution); + + String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest1Vpn.json"); + request = request.replace("28080", wireMockPort); + + ArgumentCaptor argument = ArgumentCaptor.forClass(SniroManagerRequest.class); + verify(sniroClient, times(1)).postDemands(argument.capture()); + assertEquals(request, argument.getValue().toJsonString()); + } + + @Test + public void testCallSniro_success_3VpnLink() throws JsonProcessingException, BadResponseException{ + beforeVpnBondingLink("1"); + beforeVpnBondingLink("2"); + beforeVpnBondingLink("3"); + + stubFor(post(urlEqualTo("/sniro/api/placement/v2")) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(mockResponse))); + + sniroHoming.callSniro(execution); + + String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest3Vpn.json"); + request = request.replace("28080", wireMockPort); + + ArgumentCaptor argument = ArgumentCaptor.forClass(SniroManagerRequest.class); + verify(sniroClient, times(1)).postDemands(argument.capture()); + assertEquals(request, argument.getValue().toJsonString()); + } + + @Test + public void testCallSniro_success_3Allotteds() throws BadResponseException, JsonProcessingException{ + beforeAllottedResource(); + + stubFor(post(urlEqualTo("/sniro/api/placement/v2")) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(mockResponse))); + + sniroHoming.callSniro(execution); + + String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest3AR.json"); + request = request.replace("28080", wireMockPort); + + ArgumentCaptor argument = ArgumentCaptor.forClass(SniroManagerRequest.class); + verify(sniroClient, times(1)).postDemands(argument.capture()); + assertEquals(request, argument.getValue().toJsonString()); + } + + @Test + public void testCallSniro_success_1Vnf() throws JsonProcessingException, BadResponseException{ + beforeVnf(); + + stubFor(post(urlEqualTo("/sniro/api/placement/v2")) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(mockResponse))); + + sniroHoming.callSniro(execution); + + ArgumentCaptor argument = ArgumentCaptor.forClass(SniroManagerRequest.class); + verify(sniroClient, times(1)).postDemands(argument.capture()); + //TODO assertEquals(request, argument.getValue().toJsonString()); + } + + @Test + public void testCallSniro_success_3Allotteds1Vnf() throws JsonProcessingException, BadResponseException{ + beforeAllottedResource(); + beforeVnf(); + + stubFor(post(urlEqualTo("/sniro/api/placement/v2")) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(mockResponse))); + + sniroHoming.callSniro(execution); + + verify(sniroClient, times(1)).postDemands(isA(SniroManagerRequest.class)); + } + + @Test(expected = Test.None.class) + public void testProcessSolution_success_1VpnLink_1Solution(){ + beforeVpnBondingLink("1"); + + JSONObject asyncResponse = new JSONObject(); + asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed"); + JSONArray solution1 = new JSONArray(); + solution1.put(new JSONObject().put("serviceResourceId", "testProxyId1").put("inventoryType", "service").put("solution", new JSONObject() + .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) + .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId1")))); + solution1.put(new JSONObject().put("serviceResourceId", "testProxyId2").put("inventoryType", "service").put("solution", new JSONObject() + .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName2")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) + .put(new JSONObject().put("key", "secondaryPnfName").put("value", "testSecondaryPnfName2")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId2")))); + + asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1)).put("licenseSolutions", new JSONArray())); + + sniroHoming.processSolution(execution, asyncResponse.toString()); + + ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0); + + assertFalse(si.getVpnBondingLinks().isEmpty()); + VpnBondingLink link = si.getVpnBondingLinks().get(0); + assertNotNull(link); + assertFalse(link.getServiceProxies().isEmpty()); + + assertEquals("testServiceInstanceId1", link.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId()); + assertNotNull(link.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo()); + assertEquals("testVnfHostName1", link.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName()); + + assertEquals("testServiceInstanceId2", link.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId()); + assertNotNull(link.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo()); + assertFalse(link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty()); + assertEquals("testPrimaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName()); + assertEquals("primary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole()); + assertEquals("testSecondaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName()); + assertEquals("secondary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole()); + } + + @Test + public void testProcessSolution_success_1VpnLink_2Solutions(){ + beforeVpnBondingLink("1"); + + JSONObject asyncResponse = new JSONObject(); + asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed"); + JSONArray solution1 = new JSONArray(); + solution1.put(new JSONObject().put("serviceResourceId", "testProxyId1").put("inventoryType", "service").put("solution", new JSONObject() + .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) + .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId1")))); + solution1.put(new JSONObject().put("serviceResourceId", "testProxyId2").put("inventoryType", "service").put("solution", new JSONObject() + .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName2")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) + .put(new JSONObject().put("key", "secondaryPnfName").put("value", "testSecondaryPnfName2")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId2")))); + + JSONArray solution2 = new JSONArray(); + solution2.put(new JSONObject().put("serviceResourceId", "testProxyId1").put("inventoryType", "service").put("solution", new JSONObject() + .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId3"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName3")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli3")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) + .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId3")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId3")))); + solution2.put(new JSONObject().put("serviceResourceId", "testProxyId2").put("inventoryType", "service").put("solution", new JSONObject() + .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId4"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName4")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli4")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) + .put(new JSONObject().put("key", "secondaryPnfName").put("value", "testSecondaryPnfName4")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId4")))); + + asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1).put(solution2)).put("licenseSolutions", new JSONArray())); + + sniroHoming.processSolution(execution, asyncResponse.toString()); + + ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0); + + assertFalse(si.getVpnBondingLinks().isEmpty()); + VpnBondingLink link = si.getVpnBondingLinks().get(0); + VpnBondingLink link2 = si.getVpnBondingLinks().get(1); + assertNotNull(link); + assertFalse(link.getServiceProxies().isEmpty()); + + assertEquals("testServiceInstanceId1", link.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId()); + assertNotNull(link.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo()); + assertEquals("testVnfHostName1", link.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName()); + + assertEquals("testServiceInstanceId2", link.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId()); + assertNotNull(link.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo()); + assertFalse(link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty()); + assertEquals("testPrimaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName()); + assertEquals("primary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole()); + assertEquals("testSecondaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName()); + assertEquals("secondary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole()); + + assertNotNull(link2); + assertFalse(link2.getServiceProxies().isEmpty()); + + assertEquals("testServiceInstanceId3", link2.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId()); + assertNotNull(link2.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo()); + assertEquals("testVnfHostName3", link2.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName()); + + assertEquals("testServiceInstanceId4", link2.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId()); + assertNotNull(link2.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo()); + assertFalse(link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty()); + assertEquals("testPrimaryPnfName4", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName()); + assertEquals("primary", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole()); + assertEquals("testSecondaryPnfName4", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName()); + assertEquals("secondary", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole()); + + } + + @Test + public void testProcessSolution_success_3VpnLink_2Solutions(){ + //TODO + } + + @Test + public void testProcessSolution_success_3Allotteds_1Solution(){ + beforeAllottedResource(); + + JSONObject asyncResponse = new JSONObject(); + asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed"); + JSONArray solution1 = new JSONArray(); + solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId1").put("inventoryType", "service").put("solution", new JSONObject() + .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) + .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId1")))); + solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId2").put("inventoryType", "service").put("solution", new JSONObject() + .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName2")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) + .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId2")))); + solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId3").put("inventoryType", "cloud").put("solution", new JSONObject() + .put("identifierType", "cloudRegionId").put("identifiers", new JSONArray().put("testCloudRegionId3"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3")))); + + asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1)).put("licenseSolutions", new JSONArray())); + + sniroHoming.processSolution(execution, asyncResponse.toString()); + + ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0); + + assertFalse(si.getAllottedResources().isEmpty()); + AllottedResource ar = si.getAllottedResources().get(0); + assertNotNull(ar); + assertEquals("testServiceInstanceId1", ar.getParentServiceInstance().getServiceInstanceId()); + assertNotNull(ar.getParentServiceInstance().getSolutionInfo()); + assertEquals("testVnfHostName1", ar.getParentServiceInstance().getVnfs().get(0).getVnfName()); + + AllottedResource ar2 = si.getAllottedResources().get(1); + assertNotNull(ar2); + assertEquals("testServiceInstanceId2", ar2.getParentServiceInstance().getServiceInstanceId()); + assertNotNull(ar2.getParentServiceInstance().getSolutionInfo()); + assertEquals("testVnfHostName2", ar2.getParentServiceInstance().getVnfs().get(0).getVnfName()); + + AllottedResource ar3 = si.getAllottedResources().get(2); + assertNotNull(ar3); + assertNotNull(ar3.getParentServiceInstance().getSolutionInfo()); + assertEquals("testCloudRegionId3", ar3.getParentServiceInstance().getSolutionInfo().getTargetedCloudRegion().getLcpCloudRegionId()); + } + + @Test + public void testProcessSolution_success_3Allotteds1Vnf_1Solution(){ + beforeVnf(); + beforeAllottedResource(); + + JSONObject asyncResponse = new JSONObject(); + asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed"); + JSONArray solution1 = new JSONArray(); + JSONArray licenseSolution = new JSONArray(); + solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId1").put("inventoryType", "service").put("solution", new JSONObject() + .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) + .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId1")))); + solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId2").put("inventoryType", "service").put("solution", new JSONObject() + .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName2")) + .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) + .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId2")))); + solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId3").put("inventoryType", "cloud").put("solution", new JSONObject() + .put("identifierType", "cloudRegionId").put("identifiers", new JSONArray().put("testCloudRegionId3"))) + .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) + .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")) + .put(new JSONObject().put("key", "aicVersion").put("value", "3")))); + + licenseSolution.put( + new JSONObject().put("serviceResourceId", "testVnfId1").put("entitlementPoolUUID", new JSONArray().put("f1d563e8-e714-4393-8f99-cc480144a05e").put("j1d563e8-e714-4393-8f99-cc480144a05e")) + .put("licenseKeyGroupUUID", new JSONArray().put("s1d563e8-e714-4393-8f99-cc480144a05e").put("b1d563e8-e714-4393-8f99-cc480144a05e"))); + + asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1)).put("licenseSolutions", licenseSolution)); + + sniroHoming.processSolution(execution, asyncResponse.toString()); + + ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0); + + assertFalse(si.getAllottedResources().isEmpty()); + AllottedResource ar = si.getAllottedResources().get(0); + assertNotNull(ar); + assertEquals("testServiceInstanceId1", ar.getParentServiceInstance().getServiceInstanceId()); + assertNotNull(ar.getParentServiceInstance().getSolutionInfo()); + assertEquals("testVnfHostName1", ar.getParentServiceInstance().getVnfs().get(0).getVnfName()); + + AllottedResource ar2 = si.getAllottedResources().get(1); + assertNotNull(ar2); + assertEquals("testServiceInstanceId2", ar2.getParentServiceInstance().getServiceInstanceId()); + assertNotNull(ar2.getParentServiceInstance().getSolutionInfo()); + assertEquals("testVnfHostName2", ar2.getParentServiceInstance().getVnfs().get(0).getVnfName()); + + AllottedResource ar3 = si.getAllottedResources().get(2); + assertNotNull(ar3); + assertNotNull(ar3.getParentServiceInstance().getSolutionInfo()); + assertEquals("testCloudRegionId3", ar3.getParentServiceInstance().getSolutionInfo().getTargetedCloudRegion().getLcpCloudRegionId()); + + GenericVnf vnf = si.getVnfs().get(0); + assertNotNull(vnf); + assertNotNull(vnf.getLicense()); + assertEquals(2, vnf.getLicense().getEntitlementPoolUuids().size()); + assertEquals("s1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getLicenseKeyGroupUuids().get(0)); + + } + + @Test + public void testProcessSolution_success_1Vnf_1Solution(){ + beforeVnf(); + + JSONObject asyncResponse = new JSONObject(); + asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed"); + JSONArray licenseSolution = new JSONArray(); + + licenseSolution.put( + new JSONObject().put("serviceResourceId", "testVnfId1").put("entitlementPoolUUID", new JSONArray().put("f1d563e8-e714-4393-8f99-cc480144a05e").put("j1d563e8-e714-4393-8f99-cc480144a05e")) + .put("licenseKeyGroupUUID", new JSONArray().put("s1d563e8-e714-4393-8f99-cc480144a05e").put("b1d563e8-e714-4393-8f99-cc480144a05e"))); + + asyncResponse.put("solutions", new JSONObject().put("licenseSolutions", licenseSolution)); + + sniroHoming.processSolution(execution, asyncResponse.toString()); + + ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0); + + GenericVnf vnf = si.getVnfs().get(0); + assertNotNull(vnf); + assertNotNull(vnf.getLicense()); + assertEquals(2, vnf.getLicense().getEntitlementPoolUuids().size()); + assertEquals(2, vnf.getLicense().getLicenseKeyGroupUuids().size()); + assertEquals("f1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getEntitlementPoolUuids().get(0)); + assertEquals("s1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getLicenseKeyGroupUuids().get(0)); + + + } + + @Test(expected = BpmnError.class) + public void testCallSniro_error_0Resources() throws BadResponseException, JsonProcessingException{ + + sniroHoming.callSniro(execution); + + verify(sniroClient, times(0)).postDemands(isA(SniroManagerRequest.class)); + } + + @Test(expected = BpmnError.class) + public void testCallSniro_error_badResponse() throws BadResponseException, JsonProcessingException{ + beforeAllottedResource(); + + mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"\", \"requestStatus\": \"failed\"}"; + stubFor(post(urlEqualTo("/sniro/api/placement/v2")) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(mockResponse))); + + sniroHoming.callSniro(execution); + + verify(sniroClient, times(1)).postDemands(isA(SniroManagerRequest.class)); + } + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2Test.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2Test.java deleted file mode 100644 index 73e7215fc6..0000000000 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/SniroHomingV2Test.java +++ /dev/null @@ -1,497 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.bpmn.infrastructure.flowspecific.tasks; - -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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.camunda.bpm.engine.delegate.BpmnError; -import org.json.JSONArray; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.onap.so.bpmn.servicedecomposition.bbobjects.AllottedResource; -import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer; -import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; -import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; -import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceProxy; -import org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBondingLink; -import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; -import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestParameters; -import org.onap.so.bpmn.servicedecomposition.homingobjects.Candidate; -import org.onap.so.bpmn.servicedecomposition.homingobjects.CandidateType; -import org.onap.so.client.exception.BadResponseException; -import org.onap.so.client.sniro.beans.SniroManagerRequest; -import org.onap.so.BaseIntegrationTest; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Ignore -public class SniroHomingV2Test extends BaseIntegrationTest{ - - private ServiceInstance serviceInstance; - - private RequestContext requestContext; - - private Customer customer; - ObjectMapper mapper = new ObjectMapper(); - - private static final String RESOURCE_PATH = "__files/BuildingBlocks/SniroHoming/"; - - - String mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"corys cool\", \"requestStatus\": \"accepted\"}"; -/** - @Before - public void before() { - serviceInstance = setServiceInstance(); - customer = setCustomer(); - customer.setGlobalCustomerId("testCustomerId"); - customer.setSubscriberName("testCustomerName"); - customer.getServiceSubscription().getServiceInstances().add(serviceInstance); - - requestContext = setRequestContext(); - requestContext.setMsoRequestId("testRequestId"); - RequestParameters params = new RequestParameters(); - params.setaLaCarte(false); - params.setSubscriptionServiceType("iptollfree"); - requestContext.setRequestParameters(params); - } - - public void beforeVpnBondingLink(String id){ - VpnBondingLink bondingLink = new VpnBondingLink(); - bondingLink.setVpnBondingLinkId("testVpnBondingId" + id); - bondingLink.getServiceProxies().add(setServiceProxy("1", "transport")); - ServiceProxy sp2 = setServiceProxy("2", "infrastructure"); - Candidate requiredCandidate = new Candidate(); - requiredCandidate.setCandidateType(CandidateType.VNF_ID); - List c = new ArrayList(); - c.add("testVnfId"); - requiredCandidate.setCandidates(c); - sp2.addRequiredCandidates(requiredCandidate); - bondingLink.getServiceProxies().add(sp2); - serviceInstance.getVpnBondingLinks().add(bondingLink); - - } - - public void beforeAllottedResource(){ - serviceInstance.getAllottedResources().add(setAllottedResource("1")); - serviceInstance.getAllottedResources().add(setAllottedResource("2")); - serviceInstance.getAllottedResources().add(setAllottedResource("3")); - } - - public void beforeVnf(){ - setGenericVnf(); - } - - @Test(expected = Test.None.class) - public void testCallSniro_success_1VpnLink() throws BadResponseException, IOException{ - beforeVpnBondingLink("1"); - - stubFor(post(urlEqualTo("/sniro/api/placement/v2")) - .willReturn(aResponse().withStatus(200) - .withHeader("Content-Type", "application/json") - .withBody(mockResponse))); - - sniroHoming.callSniro(execution); - - String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest1Vpn.json"); - request = request.replace("28080", wireMockPort); - - ArgumentCaptor argument = ArgumentCaptor.forClass(SniroManagerRequest.class); - verify(sniroClient, times(1)).postDemands(argument.capture()); - assertEquals(request, argument.getValue().toJsonString()); - } - - @Test - public void testCallSniro_success_3VpnLink() throws JsonProcessingException, BadResponseException{ - beforeVpnBondingLink("1"); - beforeVpnBondingLink("2"); - beforeVpnBondingLink("3"); - - stubFor(post(urlEqualTo("/sniro/api/placement/v2")) - .willReturn(aResponse().withStatus(200) - .withHeader("Content-Type", "application/json") - .withBody(mockResponse))); - - sniroHoming.callSniro(execution); - - String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest3Vpn.json"); - request = request.replace("28080", wireMockPort); - - ArgumentCaptor argument = ArgumentCaptor.forClass(SniroManagerRequest.class); - verify(sniroClient, times(1)).postDemands(argument.capture()); - assertEquals(request, argument.getValue().toJsonString()); - } - - @Test - public void testCallSniro_success_3Allotteds() throws BadResponseException, JsonProcessingException{ - beforeAllottedResource(); - - stubFor(post(urlEqualTo("/sniro/api/placement/v2")) - .willReturn(aResponse().withStatus(200) - .withHeader("Content-Type", "application/json") - .withBody(mockResponse))); - - sniroHoming.callSniro(execution); - - String request = readResourceFile(RESOURCE_PATH + "SniroManagerRequest3AR.json"); - request = request.replace("28080", wireMockPort); - - ArgumentCaptor argument = ArgumentCaptor.forClass(SniroManagerRequest.class); - verify(sniroClient, times(1)).postDemands(argument.capture()); - assertEquals(request, argument.getValue().toJsonString()); - } - - @Test - public void testCallSniro_success_1Vnf() throws JsonProcessingException, BadResponseException{ - beforeVnf(); - - stubFor(post(urlEqualTo("/sniro/api/placement/v2")) - .willReturn(aResponse().withStatus(200) - .withHeader("Content-Type", "application/json") - .withBody(mockResponse))); - - sniroHoming.callSniro(execution); - - ArgumentCaptor argument = ArgumentCaptor.forClass(SniroManagerRequest.class); - verify(sniroClient, times(1)).postDemands(argument.capture()); - //TODO assertEquals(request, argument.getValue().toJsonString()); - } - - @Test - public void testCallSniro_success_3Allotteds1Vnf() throws JsonProcessingException, BadResponseException{ - beforeAllottedResource(); - beforeVnf(); - - stubFor(post(urlEqualTo("/sniro/api/placement/v2")) - .willReturn(aResponse().withStatus(200) - .withHeader("Content-Type", "application/json") - .withBody(mockResponse))); - - sniroHoming.callSniro(execution); - - verify(sniroClient, times(1)).postDemands(isA(SniroManagerRequest.class)); - } - - @Test(expected = Test.None.class) - public void testProcessSolution_success_1VpnLink_1Solution(){ - beforeVpnBondingLink("1"); - - JSONObject asyncResponse = new JSONObject(); - asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed"); - JSONArray solution1 = new JSONArray(); - solution1.put(new JSONObject().put("serviceResourceId", "testProxyId1").put("inventoryType", "service").put("solution", new JSONObject() - .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1")) - .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) - .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId1")))); - solution1.put(new JSONObject().put("serviceResourceId", "testProxyId2").put("inventoryType", "service").put("solution", new JSONObject() - .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName2")) - .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) - .put(new JSONObject().put("key", "secondaryPnfName").put("value", "testSecondaryPnfName2")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId2")))); - - asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1)).put("licenseSolutions", new JSONArray())); - - sniroHoming.processSolution(execution, asyncResponse.toString()); - - ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0); - - assertFalse(si.getVpnBondingLinks().isEmpty()); - VpnBondingLink link = si.getVpnBondingLinks().get(0); - assertNotNull(link); - assertFalse(link.getServiceProxies().isEmpty()); - - assertEquals("testServiceInstanceId1", link.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId()); - assertNotNull(link.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo()); - assertEquals("testVnfHostName1", link.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName()); - - assertEquals("testServiceInstanceId2", link.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId()); - assertNotNull(link.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo()); - assertFalse(link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty()); - assertEquals("testPrimaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName()); - assertEquals("primary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole()); - assertEquals("testSecondaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName()); - assertEquals("secondary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole()); - } - - @Test - public void testProcessSolution_success_1VpnLink_2Solutions(){ - beforeVpnBondingLink("1"); - - JSONObject asyncResponse = new JSONObject(); - asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed"); - JSONArray solution1 = new JSONArray(); - solution1.put(new JSONObject().put("serviceResourceId", "testProxyId1").put("inventoryType", "service").put("solution", new JSONObject() - .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1")) - .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) - .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId1")))); - solution1.put(new JSONObject().put("serviceResourceId", "testProxyId2").put("inventoryType", "service").put("solution", new JSONObject() - .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName2")) - .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) - .put(new JSONObject().put("key", "secondaryPnfName").put("value", "testSecondaryPnfName2")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId2")))); - - JSONArray solution2 = new JSONArray(); - solution2.put(new JSONObject().put("serviceResourceId", "testProxyId1").put("inventoryType", "service").put("solution", new JSONObject() - .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId3"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName3")) - .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli3")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) - .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId3")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId3")))); - solution2.put(new JSONObject().put("serviceResourceId", "testProxyId2").put("inventoryType", "service").put("solution", new JSONObject() - .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId4"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "False")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "primaryPnfName").put("value", "testPrimaryPnfName4")) - .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli4")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) - .put(new JSONObject().put("key", "secondaryPnfName").put("value", "testSecondaryPnfName4")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testSloudRegionId4")))); - - asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1).put(solution2)).put("licenseSolutions", new JSONArray())); - - sniroHoming.processSolution(execution, asyncResponse.toString()); - - ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0); - - assertFalse(si.getVpnBondingLinks().isEmpty()); - VpnBondingLink link = si.getVpnBondingLinks().get(0); - VpnBondingLink link2 = si.getVpnBondingLinks().get(1); - assertNotNull(link); - assertFalse(link.getServiceProxies().isEmpty()); - - assertEquals("testServiceInstanceId1", link.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId()); - assertNotNull(link.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo()); - assertEquals("testVnfHostName1", link.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName()); - - assertEquals("testServiceInstanceId2", link.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId()); - assertNotNull(link.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo()); - assertFalse(link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty()); - assertEquals("testPrimaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName()); - assertEquals("primary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole()); - assertEquals("testSecondaryPnfName2", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName()); - assertEquals("secondary", link.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole()); - - assertNotNull(link2); - assertFalse(link2.getServiceProxies().isEmpty()); - - assertEquals("testServiceInstanceId3", link2.getServiceProxy("testProxyId1").getServiceInstance().getServiceInstanceId()); - assertNotNull(link2.getServiceProxy("testProxyId1").getServiceInstance().getSolutionInfo()); - assertEquals("testVnfHostName3", link2.getServiceProxy("testProxyId1").getServiceInstance().getVnfs().get(0).getVnfName()); - - assertEquals("testServiceInstanceId4", link2.getServiceProxy("testProxyId2").getServiceInstance().getServiceInstanceId()); - assertNotNull(link2.getServiceProxy("testProxyId2").getServiceInstance().getSolutionInfo()); - assertFalse(link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().isEmpty()); - assertEquals("testPrimaryPnfName4", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getPnfName()); - assertEquals("primary", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(0).getRole()); - assertEquals("testSecondaryPnfName4", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getPnfName()); - assertEquals("secondary", link2.getServiceProxy("testProxyId2").getServiceInstance().getPnfs().get(1).getRole()); - - } - - @Test - public void testProcessSolution_success_3VpnLink_2Solutions(){ - //TODO - } - - @Test - public void testProcessSolution_success_3Allotteds_1Solution(){ - beforeAllottedResource(); - - JSONObject asyncResponse = new JSONObject(); - asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed"); - JSONArray solution1 = new JSONArray(); - solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId1").put("inventoryType", "service").put("solution", new JSONObject() - .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1")) - .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) - .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId1")))); - solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId2").put("inventoryType", "service").put("solution", new JSONObject() - .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName2")) - .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) - .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId2")))); - solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId3").put("inventoryType", "cloud").put("solution", new JSONObject() - .put("identifierType", "cloudRegionId").put("identifiers", new JSONArray().put("testCloudRegionId3"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")) - .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3")))); - - asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1)).put("licenseSolutions", new JSONArray())); - - sniroHoming.processSolution(execution, asyncResponse.toString()); - - ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0); - - assertFalse(si.getAllottedResources().isEmpty()); - AllottedResource ar = si.getAllottedResources().get(0); - assertNotNull(ar); - assertEquals("testServiceInstanceId1", ar.getParentServiceInstance().getServiceInstanceId()); - assertNotNull(ar.getParentServiceInstance().getSolutionInfo()); - assertEquals("testVnfHostName1", ar.getParentServiceInstance().getVnfs().get(0).getVnfName()); - - AllottedResource ar2 = si.getAllottedResources().get(1); - assertNotNull(ar2); - assertEquals("testServiceInstanceId2", ar2.getParentServiceInstance().getServiceInstanceId()); - assertNotNull(ar2.getParentServiceInstance().getSolutionInfo()); - assertEquals("testVnfHostName2", ar2.getParentServiceInstance().getVnfs().get(0).getVnfName()); - - AllottedResource ar3 = si.getAllottedResources().get(2); - assertNotNull(ar3); - assertNotNull(ar3.getParentServiceInstance().getSolutionInfo()); - assertEquals("testCloudRegionId3", ar3.getParentServiceInstance().getSolutionInfo().getTargetedCloudRegion().getLcpCloudRegionId()); - } - - @Test - public void testProcessSolution_success_3Allotteds1Vnf_1Solution(){ - beforeVnf(); - beforeAllottedResource(); - - JSONObject asyncResponse = new JSONObject(); - asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed"); - JSONArray solution1 = new JSONArray(); - JSONArray licenseSolution = new JSONArray(); - solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId1").put("inventoryType", "service").put("solution", new JSONObject() - .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId1"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName1")) - .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli1")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) - .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId1")))); - solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId2").put("inventoryType", "service").put("solution", new JSONObject() - .put("identifierType", "serviceInstanceId").put("identifiers", new JSONArray().put("testServiceInstanceId2"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "vnfHostName").put("value", "testVnfHostName2")) - .put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")).put(new JSONObject().put("key", "aicVersion").put("value", "3")) - .put(new JSONObject().put("key", "vnfId").put("value", "testVnfId1")).put(new JSONObject().put("key", "cloudRegionId").put("value", "testCloudRegionId2")))); - solution1.put(new JSONObject().put("serviceResourceId", "testAllottedResourceId3").put("inventoryType", "cloud").put("solution", new JSONObject() - .put("identifierType", "cloudRegionId").put("identifiers", new JSONArray().put("testCloudRegionId3"))) - .put("assignmentInfo", new JSONArray().put(new JSONObject().put("key", "isRehome").put("value", "True")) - .put(new JSONObject().put("key", "cloudOwner").put("value", "aic")).put(new JSONObject().put("key", "aicClli").put("value", "testAicClli2")) - .put(new JSONObject().put("key", "aicVersion").put("value", "3")))); - - licenseSolution.put( - new JSONObject().put("serviceResourceId", "testVnfId1").put("entitlementPoolUUID", new JSONArray().put("f1d563e8-e714-4393-8f99-cc480144a05e").put("j1d563e8-e714-4393-8f99-cc480144a05e")) - .put("licenseKeyGroupUUID", new JSONArray().put("s1d563e8-e714-4393-8f99-cc480144a05e").put("b1d563e8-e714-4393-8f99-cc480144a05e"))); - - asyncResponse.put("solutions", new JSONObject().put("placementSolutions", new JSONArray().put(solution1)).put("licenseSolutions", licenseSolution)); - - sniroHoming.processSolution(execution, asyncResponse.toString()); - - ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0); - - assertFalse(si.getAllottedResources().isEmpty()); - AllottedResource ar = si.getAllottedResources().get(0); - assertNotNull(ar); - assertEquals("testServiceInstanceId1", ar.getParentServiceInstance().getServiceInstanceId()); - assertNotNull(ar.getParentServiceInstance().getSolutionInfo()); - assertEquals("testVnfHostName1", ar.getParentServiceInstance().getVnfs().get(0).getVnfName()); - - AllottedResource ar2 = si.getAllottedResources().get(1); - assertNotNull(ar2); - assertEquals("testServiceInstanceId2", ar2.getParentServiceInstance().getServiceInstanceId()); - assertNotNull(ar2.getParentServiceInstance().getSolutionInfo()); - assertEquals("testVnfHostName2", ar2.getParentServiceInstance().getVnfs().get(0).getVnfName()); - - AllottedResource ar3 = si.getAllottedResources().get(2); - assertNotNull(ar3); - assertNotNull(ar3.getParentServiceInstance().getSolutionInfo()); - assertEquals("testCloudRegionId3", ar3.getParentServiceInstance().getSolutionInfo().getTargetedCloudRegion().getLcpCloudRegionId()); - - GenericVnf vnf = si.getVnfs().get(0); - assertNotNull(vnf); - assertNotNull(vnf.getLicense()); - assertEquals(2, vnf.getLicense().getEntitlementPoolUuids().size()); - assertEquals("s1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getLicenseKeyGroupUuids().get(0)); - - } - - @Test - public void testProcessSolution_success_1Vnf_1Solution(){ - beforeVnf(); - - JSONObject asyncResponse = new JSONObject(); - asyncResponse.put("transactionId", "testRequestId").put("requestId", "testRequestId").put("requestState", "completed"); - JSONArray licenseSolution = new JSONArray(); - - licenseSolution.put( - new JSONObject().put("serviceResourceId", "testVnfId1").put("entitlementPoolUUID", new JSONArray().put("f1d563e8-e714-4393-8f99-cc480144a05e").put("j1d563e8-e714-4393-8f99-cc480144a05e")) - .put("licenseKeyGroupUUID", new JSONArray().put("s1d563e8-e714-4393-8f99-cc480144a05e").put("b1d563e8-e714-4393-8f99-cc480144a05e"))); - - asyncResponse.put("solutions", new JSONObject().put("licenseSolutions", licenseSolution)); - - sniroHoming.processSolution(execution, asyncResponse.toString()); - - ServiceInstance si = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0); - - GenericVnf vnf = si.getVnfs().get(0); - assertNotNull(vnf); - assertNotNull(vnf.getLicense()); - assertEquals(2, vnf.getLicense().getEntitlementPoolUuids().size()); - assertEquals(2, vnf.getLicense().getLicenseKeyGroupUuids().size()); - assertEquals("f1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getEntitlementPoolUuids().get(0)); - assertEquals("s1d563e8-e714-4393-8f99-cc480144a05e", vnf.getLicense().getLicenseKeyGroupUuids().get(0)); - - - } - - @Test(expected = BpmnError.class) - public void testCallSniro_error_0Resources() throws BadResponseException, JsonProcessingException{ - - sniroHoming.callSniro(execution); - - verify(sniroClient, times(0)).postDemands(isA(SniroManagerRequest.class)); - } - - @Test(expected = BpmnError.class) - public void testCallSniro_error_badResponse() throws BadResponseException, JsonProcessingException{ - beforeAllottedResource(); - - mockResponse = "{\"transactionId\": \"123456789\", \"requestId\": \"1234\", \"statusMessage\": \"\", \"requestStatus\": \"failed\"}"; - stubFor(post(urlEqualTo("/sniro/api/placement/v2")) - .willReturn(aResponse().withStatus(200) - .withHeader("Content-Type", "application/json") - .withBody(mockResponse))); - - sniroHoming.callSniro(execution); - - verify(sniroClient, times(1)).postDemands(isA(SniroManagerRequest.class)); - } -**/ -} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasksTest.java index 4ba6339f0a..4c5c50ebbf 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCQueryTasksTest.java @@ -40,6 +40,7 @@ import org.mockito.InjectMocks; import org.onap.so.bpmn.BaseTaskTest; import org.onap.so.bpmn.common.BuildingBlockExecution; import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; +import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance; import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; import org.onap.so.client.exception.BBObjectNotFoundException; @@ -51,15 +52,19 @@ public class SDNCQueryTasksTest extends BaseTaskTest{ @Rule public ExpectedException expectedException = ExpectedException.none(); + private ServiceInstance serviceInstance; private GenericVnf genericVnf; private VfModule vfModule; @Before public void before() throws BBObjectNotFoundException { + serviceInstance = setServiceInstance(); genericVnf = setGenericVnf(); vfModule = setVfModule(); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any())).thenReturn(genericVnf); when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID), any())).thenReturn(vfModule); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java new file mode 100644 index 0000000000..a6efbd5989 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCRequestTasksTest.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.sdnc.tasks; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.camunda.bpm.engine.delegate.BpmnError; +import org.camunda.bpm.engine.delegate.DelegateExecution; + +import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.sdnc.northbound.client.model.GenericResourceApiServiceOperationInformation; +import org.onap.so.client.exception.BadResponseException; +import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.client.exception.MapperException; +import org.onap.so.client.sdnc.SDNCClient; +import org.onap.so.client.sdnc.beans.SDNCRequest; +import org.onap.so.client.sdnc.endpoint.SDNCTopology; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.class) +public class SDNCRequestTasksTest extends SDNCRequestTasks{ + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @InjectMocks + SDNCRequestTasks sndcRequestTasks = new SDNCRequestTasks(); + + @Mock + SDNCClient sdncClient; + + @Spy + private ExceptionBuilder exceptionBuilder; + + protected DelegateExecution delegateExecution; + + + @Before + public void setup(){ + delegateExecution = new DelegateExecutionFake(); + delegateExecution.setVariable("SDNCRequest", createSDNCRequest()); + } + + @Test + public void createCorrelationVariables_Test(){ + sndcRequestTasks.createCorrelationVariables(delegateExecution); + assertEquals("correlationValue",delegateExecution.getVariable("correlationName_CORRELATOR")); + } + + @Test + public void callSDNC_Final_Test() throws MapperException, BadResponseException, IOException{ + final String sdncResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNCClientPut200Response.json"))); + doReturn(sdncResponse).when(sdncClient).post(createSDNCRequest().getSDNCPayload(),SDNCTopology.CONFIGURATION); + sndcRequestTasks.callSDNC(delegateExecution); + assertEquals(true,delegateExecution.getVariable("isSDNCCompleted")); + } + + @Test + public void callSDNC_Not_Final_Test() throws MapperException, BadResponseException, IOException{ + final String sdncResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNCClientPut200ResponseNotFinal.json"))); + doReturn(sdncResponse).when(sdncClient).post(createSDNCRequest().getSDNCPayload(),SDNCTopology.CONFIGURATION); + sndcRequestTasks.callSDNC(delegateExecution); + assertEquals(false,delegateExecution.getVariable("isSDNCCompleted")); + } + + @Test + public void callSDNC_Error_Test() throws MapperException, BadResponseException{ + doThrow(MapperException.class).when(sdncClient).post(createSDNCRequest().getSDNCPayload(),SDNCTopology.CONFIGURATION); + doReturn("processKey").when(exceptionBuilder).getProcessKey(delegateExecution); + expectedException.expect(BpmnError.class); + sndcRequestTasks.callSDNC(delegateExecution); + } + + @Test + public void convertIndicatorToBoolean_True_Test() throws MapperException, BadResponseException{ + boolean testValue = sndcRequestTasks.convertIndicatorToBoolean("Y"); + assertEquals(true,testValue); + } + + @Test + public void convertIndicatorToBoolean_False_Test() throws MapperException, BadResponseException{ + boolean testValue = sndcRequestTasks.convertIndicatorToBoolean("N"); + assertEquals(false,testValue); + } + + @Test + public void HandleTimeout_Test() throws MapperException, BadResponseException{ + doReturn("processKey").when(exceptionBuilder).getProcessKey(delegateExecution); + expectedException.expect(BpmnError.class); + sndcRequestTasks.handleTimeOutException(delegateExecution); + } + + + @Test + public void HandleSyncError_Test() throws MapperException, BadResponseException{ + delegateExecution.setVariable("SDNCSyncError", "Error in SDNC Request"); + doReturn("processKey").when(exceptionBuilder).getProcessKey(delegateExecution); + expectedException.expect(BpmnError.class); + sndcRequestTasks.handleSyncError(delegateExecution); + } + + @Test + public void processCallBack_Final_Test() throws MapperException, BadResponseException, IOException{ + final String sdncResponse = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNC_ASYNC_Request.json"))); + delegateExecution.setVariable("correlationName_MESSAGE", sdncResponse); + sndcRequestTasks.processCallback(delegateExecution); + assertEquals(true,delegateExecution.getVariable(IS_CALLBACK_COMPLETED)); + } + + public SDNCRequest createSDNCRequest(){ + SDNCRequest request = new SDNCRequest(); + request.setCorrelationName("correlationName"); + request.setCorrelationValue("correlationValue"); + request.setTopology(SDNCTopology.CONFIGURATION); + ObjectMapper mapper = new ObjectMapper(); + try { + GenericResourceApiServiceOperationInformation sdncReq = + mapper.readValue(Files.readAllBytes(Paths.get("src/test/resources/__files/SDNC_Client_Request.json")), GenericResourceApiServiceOperationInformation.class); + request.setSDNCPayload(sdncReq); + } catch (JsonParseException e) { + + } catch (JsonMappingException e) { + + } catch (IOException e) { + + } + + return request; + } + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java index 8a2230feb5..b0a80ebc72 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksTest.java @@ -25,27 +25,23 @@ import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; -import org.camunda.bpm.engine.delegate.BpmnError; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; import org.junit.Before; -import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Spy; import org.onap.so.bpmn.BaseTaskTest; import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; -import org.onap.so.db.request.beans.InfraActiveRequests; -import org.springframework.beans.factory.annotation.Autowired; public class WorkflowActionBBTasksTest extends BaseTaskTest { @@ -53,6 +49,7 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { protected WorkflowAction workflowAction; @InjectMocks + @Spy protected WorkflowActionBBTasks workflowActionBBTasks; private DelegateExecution execution; @@ -87,32 +84,6 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { assertEquals(true,success); } - @Test - public void getUpdatedRequestTest() throws Exception{ - List flowsToExecute = new ArrayList(); - ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock(); - BuildingBlock bb1 = new BuildingBlock(); - bb1.setBpmnFlowName("CreateNetworkBB"); - flowsToExecute.add(ebb1); - ebb1.setBuildingBlock(bb1); - ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock(); - BuildingBlock bb2 = new BuildingBlock(); - bb2.setBpmnFlowName("ActivateNetworkBB"); - flowsToExecute.add(ebb2); - ebb2.setBuildingBlock(bb2); - String requestId = "requestId"; - execution.setVariable("mso-request-id", requestId); - execution.setVariable("flowsToExecute", flowsToExecute); - int currentSequence = 2; - String expectedStatusMessage = "Execution of CreateNetworkBB has completed successfully, next invoking ActivateNetworkBB (Execution Path progress: BBs completed = 1; BBs remaining = 1)."; - Long expectedLong = new Long(52); - InfraActiveRequests mockedRequest = new InfraActiveRequests(); - when(requestsDbClient.getInfraActiveRequestbyRequestId(requestId)).thenReturn(mockedRequest); - InfraActiveRequests actual = workflowActionBBTasks.getUpdatedRequest(execution, currentSequence); - assertEquals(expectedStatusMessage, actual.getStatusMessage()); - assertEquals(expectedLong, actual.getProgress()); - } - @Test public void select2BBTest() throws Exception{ String gAction = "Delete-Network-Collection"; @@ -145,18 +116,9 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { assertEquals(response,"00f704ca-c5e5-4f95-a72c-6889db7b0688createInstanceMSOALaCarte-Service-createInstance request was executed correctly.123WorkflowActionBB"); } - @Test - public void setupFalloutHandlerTest(){ - execution.setVariable("mso-request-id", "00f704ca-c5e5-4f95-a72c-6889db7b0688"); - execution.setVariable("serviceInstanceId", "123"); - execution.setVariable("WorkflowActionErrorMessage", "Error in WorkFlowAction"); - execution.setVariable("requestAction", "createInstance"); - workflowActionBBTasks.setupFalloutHandler(execution); - assertEquals(execution.getVariable("falloutRequest"),"00f704ca-c5e5-4f95-a72c-6889db7b0688createInstanceVIDError in WorkFlowAction7000"); - } - @Test public void rollbackExecutionPathTest(){ + execution.setVariable("handlingCode", "Rollback"); execution.setVariable("isRollback", false); List flowsToExecute = new ArrayList(); ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock(); @@ -177,7 +139,8 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { execution.setVariable("flowsToExecute", flowsToExecute); execution.setVariable("gCurrentSequence", 3); - + doNothing().when(workflowActionBBTasks).updateRequestErrorStatusMessage(isA(DelegateExecution.class)); + workflowActionBBTasks.rollbackExecutionPath(execution); List ebbs = (List) execution.getVariable("flowsToExecute"); assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(),"DeactivateVfModuleBB"); @@ -188,6 +151,7 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { @Test public void rollbackExecutionPathUnfinishedFlowTest(){ + execution.setVariable("handlingCode", "Rollback"); execution.setVariable("isRollback", false); List flowsToExecute = new ArrayList(); ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock(); @@ -208,7 +172,8 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { execution.setVariable("flowsToExecute", flowsToExecute); execution.setVariable("gCurrentSequence", 2); - + doNothing().when(workflowActionBBTasks).updateRequestErrorStatusMessage(isA(DelegateExecution.class)); + workflowActionBBTasks.rollbackExecutionPath(execution); List ebbs = (List) execution.getVariable("flowsToExecute"); assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(),"DeleteVfModuleBB"); @@ -219,6 +184,7 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { @Test public void rollbackExecutionTest(){ + execution.setVariable("handlingCode", "Rollback"); execution.setVariable("isRollback", false); List flowsToExecute = new ArrayList(); ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock(); @@ -244,7 +210,8 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { execution.setVariable("flowsToExecute", flowsToExecute); execution.setVariable("gCurrentSequence", 3); - + doNothing().when(workflowActionBBTasks).updateRequestErrorStatusMessage(isA(DelegateExecution.class)); + workflowActionBBTasks.rollbackExecutionPath(execution); List ebbs = (List) execution.getVariable("flowsToExecute"); assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(),"UnassignNetworkBB"); @@ -253,8 +220,45 @@ public class WorkflowActionBBTasksTest extends BaseTaskTest { assertEquals(0,execution.getVariable("gCurrentSequence")); } + @Test + public void rollbackExecutionRollbackToAssignedTest(){ + execution.setVariable("isRollback", false); + execution.setVariable("handlingCode", "RollbackToAssigned"); + List flowsToExecute = new ArrayList(); + ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock(); + BuildingBlock bb1 = new BuildingBlock(); + bb1.setBpmnFlowName("AssignServiceInstanceBB"); + ebb1.setBuildingBlock(bb1); + flowsToExecute.add(ebb1); + ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock(); + BuildingBlock bb2 = new BuildingBlock(); + bb2.setBpmnFlowName("CreateNetworkCollectionBB"); + ebb2.setBuildingBlock(bb2); + flowsToExecute.add(ebb2); + ExecuteBuildingBlock ebb3 = new ExecuteBuildingBlock(); + BuildingBlock bb3 = new BuildingBlock(); + bb3.setBpmnFlowName("AssignNetworkBB"); + ebb3.setBuildingBlock(bb3); + flowsToExecute.add(ebb3); + ExecuteBuildingBlock ebb4 = new ExecuteBuildingBlock(); + BuildingBlock bb4 = new BuildingBlock(); + bb4.setBpmnFlowName("CreateNetworkBB"); + ebb4.setBuildingBlock(bb4); + flowsToExecute.add(ebb4); + + execution.setVariable("flowsToExecute", flowsToExecute); + execution.setVariable("gCurrentSequence", 3); + doNothing().when(workflowActionBBTasks).updateRequestErrorStatusMessage(isA(DelegateExecution.class)); + + workflowActionBBTasks.rollbackExecutionPath(execution); + List ebbs = (List) execution.getVariable("flowsToExecute"); + assertEquals(ebbs.get(0).getBuildingBlock().getBpmnFlowName(),"DeleteNetworkCollectionBB"); + assertEquals(0,execution.getVariable("gCurrentSequence")); + } + @Test public void checkRetryStatusTest(){ + doNothing().when(workflowActionBBTasks).updateRequestErrorStatusMessage(isA(DelegateExecution.class)); execution.setVariable("handlingCode","Retry"); execution.setVariable("retryCount", 1); execution.setVariable("gCurrentSequence",1); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksUpdateReqDbTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksUpdateReqDbTest.java new file mode 100644 index 0000000000..1e2558b580 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/workflow/tasks/WorkflowActionBBTasksUpdateReqDbTest.java @@ -0,0 +1,74 @@ +package org.onap.so.bpmn.infrastructure.workflow.tasks; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.extension.mockito.delegate.DelegateExecutionFake; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.InjectMocks; +import org.mockito.Spy; +import org.onap.so.bpmn.BaseTaskTest; +import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock; +import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock; +import org.onap.so.db.request.beans.InfraActiveRequests; + +public class WorkflowActionBBTasksUpdateReqDbTest extends BaseTaskTest{ + + protected WorkflowAction workflowAction = new WorkflowAction(); + + @Spy + @InjectMocks + protected WorkflowActionBBTasks workflowActionBBTasks; + + private DelegateExecution execution; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Before + public void before() throws Exception { + execution = new DelegateExecutionFake(); + org.onap.aai.domain.yang.ServiceInstance servInstance = new org.onap.aai.domain.yang.ServiceInstance(); + servInstance.setServiceInstanceId("TEST"); + when(bbSetupUtils.getAAIServiceInstanceByName(anyString(), any())).thenReturn(servInstance); + workflowAction.setBbInputSetupUtils(bbSetupUtils); + workflowAction.setBbInputSetup(bbInputSetup); + } + + @Test + public void getUpdatedRequestTest() throws Exception{ + List flowsToExecute = new ArrayList(); + ExecuteBuildingBlock ebb1 = new ExecuteBuildingBlock(); + BuildingBlock bb1 = new BuildingBlock(); + bb1.setBpmnFlowName("CreateNetworkBB"); + flowsToExecute.add(ebb1); + ebb1.setBuildingBlock(bb1); + ExecuteBuildingBlock ebb2 = new ExecuteBuildingBlock(); + BuildingBlock bb2 = new BuildingBlock(); + bb2.setBpmnFlowName("ActivateNetworkBB"); + flowsToExecute.add(ebb2); + ebb2.setBuildingBlock(bb2); + String requestId = "requestId"; + execution.setVariable("mso-request-id", requestId); + execution.setVariable("flowsToExecute", flowsToExecute); + int currentSequence = 2; + String expectedStatusMessage = "Execution of CreateNetworkBB has completed successfully, next invoking ActivateNetworkBB (Execution Path progress: BBs completed = 1; BBs remaining = 1)."; + Long expectedLong = new Long(52); + InfraActiveRequests mockedRequest = new InfraActiveRequests(); + doReturn(mockedRequest).when(requestsDbClient).getInfraActiveRequestbyRequestId(isA(String.class)); + InfraActiveRequests actual = workflowActionBBTasks.getUpdatedRequest(execution, currentSequence); + assertEquals(expectedStatusMessage, actual.getStatusMessage()); + assertEquals(expectedLong, actual.getProgress()); + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java index 9ca49788ae..a2880ce07f 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java @@ -25,11 +25,13 @@ import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; 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.urlPathEqualTo; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; +import org.onap.so.BaseIntegrationTest; import org.onap.so.adapters.nwrest.CreateNetworkError; import org.onap.so.adapters.nwrest.CreateNetworkRequest; import org.onap.so.adapters.nwrest.CreateNetworkResponse; @@ -44,12 +46,11 @@ import org.onap.so.adapters.nwrest.RollbackNetworkResponse; import org.onap.so.adapters.nwrest.UpdateNetworkError; import org.onap.so.adapters.nwrest.UpdateNetworkRequest; import org.onap.so.adapters.nwrest.UpdateNetworkResponse; -import org.onap.so.BaseIntegrationTest; +import org.onap.so.client.policy.JettisonStyleMapperProvider; import org.onap.so.openstack.beans.NetworkRollback; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import static com.github.tomakehurst.wiremock.client.WireMock.*; public class NetworkAdapterClientIT extends BaseIntegrationTest{ @@ -58,7 +59,7 @@ public class NetworkAdapterClientIT extends BaseIntegrationTest{ private static final String REST_ENDPOINT = "/networks/rest/v1/networks"; private NetworkAdapterClientImpl client = new NetworkAdapterClientImpl(); - private ObjectMapper mapper = new ObjectMapper(); + private ObjectMapper mapper = new JettisonStyleMapperProvider().getMapper(); @BeforeClass public static void setUp() { diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java index 0f9e11f354..3387920d40 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java @@ -31,6 +31,7 @@ import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; +import org.onap.so.BaseIntegrationTest; import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; import org.onap.so.adapters.vnfrest.CreateVfModuleResponse; import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest; @@ -42,7 +43,8 @@ import org.onap.so.adapters.vnfrest.UpdateVfModuleRequest; import org.onap.so.adapters.vnfrest.UpdateVfModuleResponse; import org.onap.so.adapters.vnfrest.VfModuleExceptionResponse; import org.onap.so.adapters.vnfrest.VfModuleRollback; -import org.onap.so.BaseIntegrationTest; +import org.onap.so.client.policy.JettisonStyleMapperProvider; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -54,7 +56,7 @@ public class VnfAdapterClientIT extends BaseIntegrationTest{ private static final String REST_ENDPOINT = "/services/rest/v1/vnfs"; private VnfAdapterClientImpl client = new VnfAdapterClientImpl(); - private ObjectMapper mapper = new ObjectMapper(); + private ObjectMapper mapper = new JettisonStyleMapperProvider().getMapper(); @BeforeClass public static void setUp() { diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/oof/OofClientTestIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/oof/OofClientTestIT.java index 149417d89b..0b33b1d187 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/oof/OofClientTestIT.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/oof/OofClientTestIT.java @@ -20,20 +20,21 @@ package org.onap.so.client.oof; -import com.fasterxml.jackson.core.JsonProcessingException; +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 org.junit.Test; +import org.onap.so.BaseIntegrationTest; import org.onap.so.client.exception.BadResponseException; -import org.onap.so.client.oof.OofClient; import org.onap.so.client.oof.beans.OofRequest; import org.springframework.beans.factory.annotation.Autowired; -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 com.fasterxml.jackson.core.JsonProcessingException; -public class OofClientTestIT { +public class OofClientTestIT extends BaseIntegrationTest { @Autowired private OofClient client; diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCConfigurationResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCConfigurationResourcesTest.java index 8bb46d80d7..4d90a3fcc9 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCConfigurationResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/SDNCConfigurationResourcesTest.java @@ -27,11 +27,15 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import java.net.URI; +import java.net.URISyntaxException; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.bpmn.common.data.TestDataSetup; @@ -68,49 +72,34 @@ public class SDNCConfigurationResourcesTest extends TestDataSetup{ @Before public void setUp(){ - customer = buildCustomer(); - requestContext = buildRequestContext(); - serviceInstance = buildServiceInstance(); - - vpnBondingLink = buildVpnBondingLink(); - + vpnBondingLink = buildVpnBondingLink(); vnf = vpnBondingLink.getInfrastructureServiceProxy().getServiceInstance().getVnfs().get(0); } @Test - public void activateVnrConfigurationTest() throws BadResponseException, MapperException { - - doReturn("success").when(MOCK_sdncClient).post(isA(GenericResourceApiGcTopologyOperationInformation.class), isA(SDNCTopology.class)); - String response = sdncConfigurationResources.activateVnrConfiguration(serviceInstance,requestContext,customer,vpnBondingLink.getVnrConfiguration(),vnf); - verify(MOCK_sdncClient, times(1)).post(any(GenericResourceApiGcTopologyOperationInformation.class), any(SDNCTopology.class)); + public void activateVnrConfigurationTest() throws BadResponseException, MapperException, URISyntaxException { + GenericResourceApiGcTopologyOperationInformation response = sdncConfigurationResources.activateVnrConfiguration(serviceInstance,requestContext,customer,vpnBondingLink.getVnrConfiguration(),vnf,"uuid",new URI("http://localhost")); assertNotNull(response); } @Test - public void assignVnrConfigurationTest() throws BadResponseException, MapperException { - - doReturn("success").when(MOCK_sdncClient).post(isA(GenericResourceApiGcTopologyOperationInformation.class), isA(SDNCTopology.class)); - String response = sdncConfigurationResources.assignVnrConfiguration(serviceInstance,requestContext,customer,vpnBondingLink.getVnrConfiguration(),vnf); - verify(MOCK_sdncClient, times(1)).post(any(GenericResourceApiGcTopologyOperationInformation.class), any(SDNCTopology.class)); + public void assignVnrConfigurationTest() throws BadResponseException, MapperException, URISyntaxException { + GenericResourceApiGcTopologyOperationInformation response = sdncConfigurationResources.assignVnrConfiguration(serviceInstance,requestContext,customer,vpnBondingLink.getVnrConfiguration(),vnf,"uuid",new URI("http://localhost")); assertNotNull(response); } @Test - public void unAssignVnrConfigurationTest() throws BadResponseException, MapperException { - doReturn("success").when(MOCK_sdncClient).post(isA(GenericResourceApiGcTopologyOperationInformation.class), isA(SDNCTopology.class)); - String response = sdncConfigurationResources.unAssignVnrConfiguration(serviceInstance,requestContext,vpnBondingLink.getVnrConfiguration()); - verify(MOCK_sdncClient, times(1)).post(any(GenericResourceApiGcTopologyOperationInformation.class), any(SDNCTopology.class)); + public void unAssignVnrConfigurationTest() throws BadResponseException, MapperException , URISyntaxException{ + GenericResourceApiGcTopologyOperationInformation response = sdncConfigurationResources.unAssignVnrConfiguration(serviceInstance,requestContext,vpnBondingLink.getVnrConfiguration(),"uuid",new URI("http://localhost")); assertNotNull(response); } @Test - public void deactivateVnrConfigurationTest() throws BadResponseException, MapperException { - doReturn("success").when(MOCK_sdncClient).post(isA(GenericResourceApiGcTopologyOperationInformation.class), isA(SDNCTopology.class)); - String response = sdncConfigurationResources.deactivateVnrConfiguration(serviceInstance,requestContext,vpnBondingLink.getVnrConfiguration()); - verify(MOCK_sdncClient, times(1)).post(any(GenericResourceApiGcTopologyOperationInformation.class), any(SDNCTopology.class)); + public void deactivateVnrConfigurationTest() throws BadResponseException, MapperException , URISyntaxException{ + GenericResourceApiGcTopologyOperationInformation response = sdncConfigurationResources.deactivateVnrConfiguration(serviceInstance,requestContext,vpnBondingLink.getVnrConfiguration(),"uuid",new URI("http://localhost")); assertNotNull(response); } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientIT.java new file mode 100644 index 0000000000..cc1c5c5329 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientIT.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.client.sdnc; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +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 java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.junit.Test; +import org.onap.so.BaseIntegrationTest; +import org.onap.so.client.exception.BadResponseException; +import org.onap.so.client.exception.MapperException; +import org.onap.so.client.sdnc.endpoint.SDNCTopology; +import org.skyscreamer.jsonassert.JSONAssert; + +public class SDNCClientIT extends BaseIntegrationTest { + private final static String JSON_FILE_LOCATION = "src/test/resources/__files/"; + + @Test + public void getTest() throws BadResponseException, MapperException, IOException { + String responseJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientGetResponse.json"))); + String queryLink = "/topologyQuery"; + + stubFor(get(urlEqualTo(queryLink)) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json").withBody(responseJson))); + String response = SPY_sdncClient.get(queryLink); + JSONAssert.assertEquals(responseJson, response, false); + } + + @Test(expected = BadResponseException.class) + public void post404Test() throws BadResponseException, MapperException, IOException { + String responseJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientPut404Response.json"))); + + String queryLink = "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation/"; + + stubFor(post(urlMatching(queryLink)) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json").withBody(responseJson))); + + SPY_sdncClient.post("", SDNCTopology.NETWORK); + } + + @Test + public void post200Test() throws BadResponseException, MapperException, IOException { + String responseJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientPut200Response.json"))); + + String queryLink = "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation/"; + + stubFor(post(urlMatching(queryLink)) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json").withBody(responseJson))); + + String response = SPY_sdncClient.post("", SDNCTopology.NETWORK); + JSONAssert.assertEquals("", response, false); + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientTest.java deleted file mode 100644 index 66ec514039..0000000000 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/SDNCClientTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.client.sdnc; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; -import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; - -import org.junit.Rule; -import org.junit.Test; -import org.onap.so.BaseIntegrationTest; -import org.onap.so.bpmn.BaseTaskTest; -import org.onap.so.client.exception.BadResponseException; -import org.onap.so.client.exception.MapperException; -import org.onap.so.client.sdnc.endpoint.SDNCTopology; -import org.skyscreamer.jsonassert.JSONAssert; - -import com.github.tomakehurst.wiremock.junit.WireMockRule; - -public class SDNCClientTest extends BaseIntegrationTest { - private final static String JSON_FILE_LOCATION = "src/test/resources/__files/"; - - @Rule - public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().port(8446)); - - @Test - public void getTest() throws BadResponseException, MapperException, IOException { - String responseJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientGetResponse.json"))); - String queryLink = "/topologyQuery"; - - wireMockRule.stubFor(get(urlEqualTo(queryLink)) - .willReturn(aResponse().withStatus(200) - .withHeader("Content-Type", "application/json").withBody(responseJson))); - String response = SPY_sdncClient.get(queryLink); - JSONAssert.assertEquals(responseJson, response, false); - } - - @Test(expected = BadResponseException.class) - public void post404Test() throws BadResponseException, MapperException, IOException { - String responseJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientPut404Response.json"))); - - String queryLink = "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation/"; - - wireMockRule.stubFor(post(urlMatching(queryLink)) - .willReturn(aResponse().withStatus(200) - .withHeader("Content-Type", "application/json").withBody(responseJson))); - - SPY_sdncClient.post("", SDNCTopology.NETWORK); - } - - @Test - public void post200Test() throws BadResponseException, MapperException, IOException { - String responseJson = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "SDNCClientPut200Response.json"))); - - String queryLink = "/restconf/operations/GENERIC-RESOURCE-API:network-topology-operation/"; - - wireMockRule.stubFor(post(urlMatching(queryLink)) - .willReturn(aResponse().withStatus(200) - .withHeader("Content-Type", "application/json").withBody(responseJson))); - - String response = SPY_sdncClient.post("", SDNCTopology.NETWORK); - JSONAssert.assertEquals("", response, false); - } -} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java index 7c5e9ccf26..f01eeaeae8 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java @@ -20,6 +20,8 @@ package org.onap.so.client.sdnc.mapper; +import java.net.URI; +import java.net.URISyntaxException; import java.util.HashMap; import java.util.List; @@ -44,7 +46,7 @@ public class GCTopologyOperationRequestMapperTest extends TestDataSetup{ private GCTopologyOperationRequestMapper genObjMapper = new GCTopologyOperationRequestMapper(); @Test - public void deactivateOrUnassignVnrReqMapperTest() { + public void deactivateOrUnassignVnrReqMapperTest() throws URISyntaxException { RequestContext requestContext = new RequestContext(); requestContext.setMsoRequestId("MsoRequestId"); ServiceInstance serviceInstance = new ServiceInstance(); @@ -52,10 +54,15 @@ public class GCTopologyOperationRequestMapperTest extends TestDataSetup{ Configuration Configuration = new Configuration(); Configuration.setConfigurationId("ConfigurationId"); GenericResourceApiGcTopologyOperationInformation genericInfo = genObjMapper.deactivateOrUnassignVnrReqMapper - (SDNCSvcAction.UNASSIGN, serviceInstance, requestContext, Configuration); + (SDNCSvcAction.UNASSIGN, serviceInstance, requestContext, Configuration,"uuid",new URI("http://localhost")); Assert.assertNotNull(genericInfo); - Assert.assertNotNull(genericInfo.getSdncRequestHeader().getSvcRequestId()); + Assert.assertNotNull(genericInfo.getRequestInformation()); + Assert.assertNotNull(genericInfo.getSdncRequestHeader()); + Assert.assertNotNull(genericInfo.getClass()); + Assert.assertNotNull(genericInfo.getServiceInformation()); + Assert.assertEquals("uuid",genericInfo.getSdncRequestHeader().getSvcRequestId()); + Assert.assertEquals("http://localhost",genericInfo.getSdncRequestHeader().getSvcNotificationUrl()); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sniro/SniroClientTestIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sniro/SniroClientTestIT.java index e5eb6bce54..3387e9ddef 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sniro/SniroClientTestIT.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sniro/SniroClientTestIT.java @@ -22,18 +22,20 @@ package org.onap.so.client.sniro; 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 org.junit.Test; +import org.onap.so.BaseIntegrationTest; import org.onap.so.client.exception.BadResponseException; import org.onap.so.client.sniro.beans.SniroConductorRequest; import org.onap.so.client.sniro.beans.SniroManagerRequest; import org.springframework.beans.factory.annotation.Autowired; import com.fasterxml.jackson.core.JsonProcessingException; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -public class SniroClientTestIT{ +public class SniroClientTestIT extends BaseIntegrationTest { @Autowired private SniroClient client; diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1Vpn.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1Vpn.json index ba7ab9e3b8..55aa2ef58c 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1Vpn.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest1Vpn.json @@ -2,5 +2,5 @@ "requestInfo" : {"sourceId":"mso","requestType":"create","requestId":"testRequestId","callbackUrl":"http://localhost:28080/mso/WorkflowMesssage/SNIROResponse/testRequestId","transactionId":"testRequestId","timeout":1800}, "serviceInfo" : {"modelInfo":{"modelName":"testModelName1","modelVersionId":"testModelUUID1","modelVersion":"testModelVersion1","modelInvariantId":"testModelInvariantUUID1"},"serviceInstanceId":"testServiceInstanceId1","serviceName":"testServiceType1"}, "placementInfo" : {"subscriberInfo":{"subscriberName":"testCustomerName","globalSubscriberId":"testCustomerId"},"placementDemands":[{"resourceModelInfo":{"modelName":"testProxyModelName1","modelVersionId":"testProxyModelUuid1","modelVersion":"testProxyModelVersion1","modelInvariantId":"testProxyModelInvariantUuid1"},"resourceModuleName":"testProxyInstanceName1","serviceResourceId":"testProxyId1"},{"resourceModelInfo":{"modelName":"testProxyModelName2","modelVersionId":"testProxyModelUuid2","modelVersion":"testProxyModelVersion2","modelInvariantId":"testProxyModelInvariantUuid2"},"requiredCandidates":[{"candidateType":{"name":"vnfId"},"candidates":["testVnfId"]}],"resourceModuleName":"testProxyInstanceName2","serviceResourceId":"testProxyId2"}],"requestParameters":{"aLaCarte":false,"subscriptionServiceType":"iptollfree"}}, - "licenseInfo" : [] + "licenseInfo" : {"licenseDemands":[]} } \ No newline at end of file diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3AR.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3AR.json new file mode 100644 index 0000000000..6977224ffa --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3AR.json @@ -0,0 +1,6 @@ +{ + "requestInfo" : {"sourceId":"mso","requestType":"create","requestId":"testRequestId","callbackUrl":"http://localhost:28080/mso/WorkflowMesssage/SNIROResponse/testRequestId","transactionId":"testRequestId","timeout":1800}, + "serviceInfo" : {"modelInfo":{"modelName":"testModelName1","modelVersionId":"testModelUUID1","modelVersion":"testModelVersion1","modelInvariantId":"testModelInvariantUUID1"},"serviceInstanceId":"testServiceInstanceId1","serviceName":"testServiceType1"}, + "placementInfo" : {"subscriberInfo":{"subscriberName":"testCustomerName","globalSubscriberId":"testCustomerId"},"placementDemands":[{"resourceModelInfo":{"modelName":"testAllottedModelName1","modelVersionId":"testAllottedModelUuid1","modelVersion":"testAllottedModelVersion1","modelInvariantId":"testAllottedModelInvariantUuid1"},"resourceModuleName":"testAllottedModelInstanceName1","serviceResourceId":"testAllottedResourceId1"},{"resourceModelInfo":{"modelName":"testAllottedModelName2","modelVersionId":"testAllottedModelUuid2","modelVersion":"testAllottedModelVersion2","modelInvariantId":"testAllottedModelInvariantUuid2"},"resourceModuleName":"testAllottedModelInstanceName2","serviceResourceId":"testAllottedResourceId2"},{"resourceModelInfo":{"modelName":"testAllottedModelName3","modelVersionId":"testAllottedModelUuid3","modelVersion":"testAllottedModelVersion3","modelInvariantId":"testAllottedModelInvariantUuid3"},"resourceModuleName":"testAllottedModelInstanceName3","serviceResourceId":"testAllottedResourceId3"}],"requestParameters":{"aLaCarte":false,"subscriptionServiceType":"iptollfree"}}, + "licenseInfo" : {"licenseDemands":[]} +} \ No newline at end of file diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3Vpn.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3Vpn.json index c5d0ffe38d..c72831b79f 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3Vpn.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/SniroHoming/SniroManagerRequest3Vpn.json @@ -2,5 +2,5 @@ "requestInfo" : {"sourceId":"mso","requestType":"create","requestId":"testRequestId","callbackUrl":"http://localhost:28080/mso/WorkflowMesssage/SNIROResponse/testRequestId","transactionId":"testRequestId","timeout":1800}, "serviceInfo" : {"modelInfo":{"modelName":"testModelName1","modelVersionId":"testModelUUID1","modelVersion":"testModelVersion1","modelInvariantId":"testModelInvariantUUID1"},"serviceInstanceId":"testServiceInstanceId1","serviceName":"testServiceType1"}, "placementInfo" : {"subscriberInfo":{"subscriberName":"testCustomerName","globalSubscriberId":"testCustomerId"},"placementDemands":[{"resourceModelInfo":{"modelName":"testProxyModelName1","modelVersionId":"testProxyModelUuid1","modelVersion":"testProxyModelVersion1","modelInvariantId":"testProxyModelInvariantUuid1"},"resourceModuleName":"testProxyInstanceName1","serviceResourceId":"testProxyId1"},{"resourceModelInfo":{"modelName":"testProxyModelName2","modelVersionId":"testProxyModelUuid2","modelVersion":"testProxyModelVersion2","modelInvariantId":"testProxyModelInvariantUuid2"},"requiredCandidates":[{"candidateType":{"name":"vnfId"},"candidates":["testVnfId"]}],"resourceModuleName":"testProxyInstanceName2","serviceResourceId":"testProxyId2"},{"resourceModelInfo":{"modelName":"testProxyModelName1","modelVersionId":"testProxyModelUuid1","modelVersion":"testProxyModelVersion1","modelInvariantId":"testProxyModelInvariantUuid1"},"resourceModuleName":"testProxyInstanceName1","serviceResourceId":"testProxyId1"},{"resourceModelInfo":{"modelName":"testProxyModelName2","modelVersionId":"testProxyModelUuid2","modelVersion":"testProxyModelVersion2","modelInvariantId":"testProxyModelInvariantUuid2"},"requiredCandidates":[{"candidateType":{"name":"vnfId"},"candidates":["testVnfId"]}],"resourceModuleName":"testProxyInstanceName2","serviceResourceId":"testProxyId2"},{"resourceModelInfo":{"modelName":"testProxyModelName1","modelVersionId":"testProxyModelUuid1","modelVersion":"testProxyModelVersion1","modelInvariantId":"testProxyModelInvariantUuid1"},"resourceModuleName":"testProxyInstanceName1","serviceResourceId":"testProxyId1"},{"resourceModelInfo":{"modelName":"testProxyModelName2","modelVersionId":"testProxyModelUuid2","modelVersion":"testProxyModelVersion2","modelInvariantId":"testProxyModelInvariantUuid2"},"requiredCandidates":[{"candidateType":{"name":"vnfId"},"candidates":["testVnfId"]}],"resourceModuleName":"testProxyInstanceName2","serviceResourceId":"testProxyId2"}],"requestParameters":{"aLaCarte":false,"subscriptionServiceType":"iptollfree"}}, - "licenseInfo" : [] + "licenseInfo" : {"licenseDemands":[]} } \ No newline at end of file diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/SDNCClientPut200ResponseNotFinal.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/SDNCClientPut200ResponseNotFinal.json new file mode 100644 index 0000000000..deb4de0219 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/SDNCClientPut200ResponseNotFinal.json @@ -0,0 +1,15 @@ +{ + "output": { + "svc-request-id": "5d24d40e-4c77-4c06-94a3-6d168c47a57c", + "network-response-information": { + "instance-id": "4063e0aa-af13-4872-8473-b40c94f9316b", + "object-path": "restconf/config/GENERIC-RESOURCE-API:services/service/2c9c7996-75a7-4f92-becc-9e13e8bd288a/service-data/networks/network/4063e0aa-af13-4872-8473-b40c94f9316b/network-data/network-topology/" + }, + "response-code": "200", + "service-response-information": { + "instance-id": "2c9c7996-75a7-4f92-becc-9e13e8bd288a" + }, + "response-message": "", + "ack-final-indicator": "N" + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/SDNC_ASYNC_Request.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/SDNC_ASYNC_Request.json new file mode 100644 index 0000000000..c1ea682068 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/SDNC_ASYNC_Request.json @@ -0,0 +1,15 @@ +{ + "input": { + "svc-request-id": "5d24d40e-4c77-4c06-94a3-6d168c47a57c", + "network-response-information": { + "instance-id": "4063e0aa-af13-4872-8473-b40c94f9316b", + "object-path": "restconf/config/GENERIC-RESOURCE-API:services/service/2c9c7996-75a7-4f92-becc-9e13e8bd288a/service-data/networks/network/4063e0aa-af13-4872-8473-b40c94f9316b/network-data/network-topology/" + }, + "response-code": "200", + "service-response-information": { + "instance-id": "2c9c7996-75a7-4f92-becc-9e13e8bd288a" + }, + "response-message": "", + "ack-final-indicator": "Y" + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/SDNC_Client_Request.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/SDNC_Client_Request.json new file mode 100644 index 0000000000..f60767b85e --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/SDNC_Client_Request.json @@ -0,0 +1,28 @@ +: { + "input": { + "request-information": { + "request-action": "CreateServiceInstance", + "source": "MSO", + "request-id": "5a09ab96-032b-41cd-ad81-4fb9ec5fade7" + }, + "sdnc-request-header": { + "svc-request-id": "5a09ab96-032b-41cd-ad81-4fb9ec5fade7", + "svc-action": "assign" + }, + "service-information": { + "onap-model-information": { + "model-name": "Vf zrdm5bpxmc02092017-Service", + "model-version": "1.0", + "model-uuid": "bad955c3-29b2-4a27-932e-28e942cc6480", + "model-invariant-uuid": "b16a9398-ffa3-4041-b78c-2956b8ad9c7b" + }, + "subscription-service-type": "Robot_Test_Service_Type", + "service-id": "48121c5e-dde0-42a6-a78a-89556ff355d0", + "global-customer-id": "Robot_Test_Subscriber_ID", + "service-instance-id": "48121c5e-dde0-42a6-a78a-89556ff355d0" + }, + "service-request-input": { + "service-instance-name": "Robot_SI_For_VolumeGroup" + } + } +} \ No newline at end of file diff --git a/bpmn/so-bpmn-tasks/src/test/resources/application-test.yaml b/bpmn/so-bpmn-tasks/src/test/resources/application-test.yaml index 69d2e18e7a..4ecdc721f0 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/application-test.yaml +++ b/bpmn/so-bpmn-tasks/src/test/resources/application-test.yaml @@ -160,7 +160,7 @@ policy: environment: TEST sdnc: auth: Basic YWRtaW46YWRtaW4= - host: http://localhost:8446 + host: http://localhost:${wiremock.server.port} path: /restconf/operations/GENERIC-RESOURCE-API sniro: conductor: @@ -180,8 +180,7 @@ sniro: oof: timeout: PT30M host: http://localhost:${wiremock.server.port} - uri.v1: /api/oof/v1/placement - uri.v2: /api/oof/v2/placement + uri: /api/oof/v1/placement headers.auth: Basic dGVzdDp0ZXN0cHdk spring: datasource: -- cgit 1.2.3-korg