diff options
222 files changed, 8062 insertions, 3354 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java index b6c98ad996..e8ef86a3b4 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java @@ -147,6 +147,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ cloudOwner, tenantId, stackName, + null, heatTemplate, stackInputs, pollForCompletion, @@ -172,6 +173,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ cloudOwner, tenantId, stackName, + null, heatTemplate, stackInputs, pollForCompletion, @@ -197,6 +199,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ cloudOwner, tenantId, stackName, + null, heatTemplate, stackInputs, pollForCompletion, @@ -223,6 +226,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ cloudOwner, tenantId, stackName, + null, heatTemplate, stackInputs, pollForCompletion, @@ -262,6 +266,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ * @param cloudOwner the cloud owner of the cloud site in which to create the stack * @param tenantId The Openstack ID of the tenant in which to create the Stack * @param stackName The name of the stack to create + * @param vduModelInfo contains information about the vdu model (added for plugin adapter) * @param heatTemplate The Heat template * @param stackInputs A map of key/value inputs * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client @@ -279,6 +284,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ String cloudOwner, String tenantId, String stackName, + VduModelInfo vduModel, String heatTemplate, Map <String, ?> stackInputs, boolean pollForCompletion, @@ -1551,6 +1557,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin{ cloudOwner, tenantId, instanceName, + vduModel, heatTemplate, inputs, true, // poll for completion diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java index 01120d51a3..fec4a1d16c 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java @@ -67,11 +67,12 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{ public static final String OOF_DIRECTIVES = "oof_directives"; public static final String SDNC_DIRECTIVES = "sdnc_directives"; + public static final String USER_DIRECTIVES = "user_directives"; public static final String VNF_ID = "vnf_id"; public static final String VF_MODULE_ID = "vf_module_id"; public static final String TEMPLATE_TYPE = "template_type"; public static final List<String> MULTICLOUD_INPUTS = - Arrays.asList(OOF_DIRECTIVES, SDNC_DIRECTIVES, TEMPLATE_TYPE); + Arrays.asList(OOF_DIRECTIVES, SDNC_DIRECTIVES, USER_DIRECTIVES, TEMPLATE_TYPE); private static final Logger logger = LoggerFactory.getLogger(MsoMulticloudUtils.class); @@ -134,6 +135,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{ String cloudOwner, String tenantId, String stackName, + VduModelInfo vduModel, String heatTemplate, Map <String, ?> stackInputs, boolean pollForCompletion, @@ -148,6 +150,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{ // Get the directives, if present. String oofDirectives = "{}"; String sdncDirectives = "{}"; + String userDirectives = "{}"; String genericVnfId = ""; String vfModuleId = ""; String templateType = ""; @@ -160,6 +163,9 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{ if (key == SDNC_DIRECTIVES) { sdncDirectives = (String) stackInputs.get(key); } + if (key == USER_DIRECTIVES) { + sdncDirectives = (String) stackInputs.get(key); + } if (key == TEMPLATE_TYPE) { templateType = (String) stackInputs.get(key); } @@ -184,10 +190,14 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{ multicloudRequest.setGenericVnfId(genericVnfId); multicloudRequest.setVfModuleId(vfModuleId); + multicloudRequest.setVfModuleModelInvariantId(vduModel.getModelInvariantUUID()); + multicloudRequest.setVfModuleModelVersionId(vduModel.getModelUUID()); + multicloudRequest.setVfModuleModelCustomizationId(vduModel.getModelCustomizationUUID()); multicloudRequest.setTemplateType(templateType); multicloudRequest.setTemplateData(stack); multicloudRequest.setOofDirectives(getDirectiveNode(oofDirectives)); multicloudRequest.setSdncDirectives(getDirectiveNode(sdncDirectives)); + multicloudRequest.setUserDirectives(getDirectiveNode(userDirectives)); if (logger.isDebugEnabled()) { logger.debug(String.format("Multicloud Request is: %s", multicloudRequest.toString())); } @@ -677,6 +687,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin{ cloudOwner, tenantId, instanceName, + vduModel, heatTemplate, inputs, true, // poll for completion diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java index 22ce6d9781..93460ff119 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoNeutronUtils.java @@ -23,21 +23,11 @@ package org.onap.so.openstack.utils; -import com.woorea.openstack.base.client.OpenStackBaseException; -import com.woorea.openstack.base.client.OpenStackConnectException; -import com.woorea.openstack.base.client.OpenStackRequest; -import com.woorea.openstack.base.client.OpenStackResponseException; -import com.woorea.openstack.keystone.Keystone; -import com.woorea.openstack.keystone.model.Access; -import com.woorea.openstack.keystone.model.Authentication; -import com.woorea.openstack.keystone.utils.KeystoneUtils; -import com.woorea.openstack.quantum.Quantum; -import com.woorea.openstack.quantum.model.Network; -import com.woorea.openstack.quantum.model.Networks; -import com.woorea.openstack.quantum.model.Segment; import java.util.ArrayList; import java.util.Calendar; import java.util.List; +import java.util.Optional; + import org.onap.so.cloud.CloudConfig; import org.onap.so.cloud.authentication.AuthenticationMethodFactory; import org.onap.so.cloud.authentication.KeystoneAuthHolder; @@ -62,6 +52,20 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import com.woorea.openstack.base.client.OpenStackBaseException; +import com.woorea.openstack.base.client.OpenStackConnectException; +import com.woorea.openstack.base.client.OpenStackRequest; +import com.woorea.openstack.base.client.OpenStackResponseException; +import com.woorea.openstack.keystone.Keystone; +import com.woorea.openstack.keystone.model.Access; +import com.woorea.openstack.keystone.model.Authentication; +import com.woorea.openstack.keystone.utils.KeystoneUtils; +import com.woorea.openstack.quantum.Quantum; +import com.woorea.openstack.quantum.model.Network; +import com.woorea.openstack.quantum.model.Networks; +import com.woorea.openstack.quantum.model.Port; +import com.woorea.openstack.quantum.model.Segment; + @Component public class MsoNeutronUtils extends MsoCommonUtils { @@ -211,6 +215,24 @@ public class MsoNeutronUtils extends MsoCommonUtils throw me; } } + + public Optional<Port> getNeutronPort(String neutronPortId, String tenantId, String cloudSiteId) + { + try { + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); + Quantum neutronClient = getNeutronClient (cloudSite, tenantId); + Port port = findPortById (neutronClient, neutronPortId); + if (port == null) { + return Optional.empty(); + } + return Optional.of(port); + } + catch (RuntimeException | MsoException e) { + logger.error("Error retrieving neutron port", e); + return Optional.empty(); + } + } /** * Delete the specified Network (by ID) in the given cloud. @@ -488,6 +510,29 @@ public class MsoNeutronUtils extends MsoCommonUtils } } } + + + private Port findPortById (Quantum neutronClient, String neutronPortId) + { + if (neutronPortId == null) { + return null; + } + + try { + OpenStackRequest<Port> request = neutronClient.ports().show(neutronPortId); + Port port = executeAndRecordOpenstackRequest(request); + return port; + } + catch (OpenStackResponseException e) { + if (e.getStatus() == 404) { + return null; + } else { + logger.error("{} {} Openstack Error, GET Neutron Port By ID ({}): ", MessageEnum.RA_CONNECTION_EXCEPTION, + ErrorCode.DataError.getValue(), neutronPortId, e); + throw e; + } + } + } /* * Find a network (or query its existence) by its Name. This method avoids an diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java index 4204813cec..3689d34204 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MulticloudRequest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ - * Copyright (C) 2018 Intel Corp. All rights reserved. + * Copyright (C) 2019 Intel Corp. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,12 @@ import org.apache.commons.lang.builder.ToStringBuilder; @JsonPropertyOrder({ "generic-vnf-id", "vf-module-id", + "vf-module-model-invariant-id", + "vf-module-model-version-id", + "vf-module-model-customization-id", "oof_directives", "sdnc_directives", + "user_directives", "template_type", "template_data" }) @@ -45,10 +49,18 @@ public class MulticloudRequest implements Serializable { private String genericVnfId; @JsonProperty("vf-module-id") private String vfModuleId; + @JsonProperty("vf-module-model-invariant-id") + private String vfModuleModelInvariantId; + @JsonProperty("vf-module-model-version-id") + private String vfModuleModelVersionId; + @JsonProperty("vf-module-model-customization-id") + private String vfModuleModelCustomizationId; @JsonProperty("oof_directives") private JsonNode oofDirectives; @JsonProperty("sdnc_directives") private JsonNode sdncDirectives; + @JsonProperty("user_directives") + private JsonNode userDirectives; @JsonProperty("template_type") private String templateType; @JsonProperty("template_data") @@ -75,6 +87,36 @@ public class MulticloudRequest implements Serializable { this.vfModuleId = vfModuleId; } + @JsonProperty("vf-module-model-invariant-id") + public String getVfModuleModelInvariantId() { + return vfModuleModelInvariantId; + } + + @JsonProperty("vf-module-model-invariant-id") + public void setVfModuleModelInvariantId(String vfModuleModelInvariantId) { + this.vfModuleModelInvariantId = vfModuleModelInvariantId; + } + + @JsonProperty("vf-module-model-version-id") + public String getVfModuleModelVersionId() { + return vfModuleModelVersionId; + } + + @JsonProperty("vf-module-model-version-id") + public void setVfModuleModelVersionId(String vfModuleModelVersionId) { + this.vfModuleModelVersionId = vfModuleModelVersionId; + } + + @JsonProperty("vf-module-model-customization-id") + public String getVfModuleModelCustomizationId() { + return vfModuleModelCustomizationId; + } + + @JsonProperty("vf-module-model-customization-id") + public void setVfModuleModelCustomizationId(String vfModuleModelCustomizationId) { + this.vfModuleModelCustomizationId = vfModuleModelCustomizationId; + } + @JsonProperty("oof_directives") public JsonNode getOofDirectives() { return oofDirectives; @@ -95,6 +137,16 @@ public class MulticloudRequest implements Serializable { this.sdncDirectives = sdncDirectives; } + @JsonProperty("user_directives") + public JsonNode getUserDirectives() { + return userDirectives; + } + + @JsonProperty("user_directives") + public void setUserDirectives(JsonNode userDirectives) { + this.userDirectives = userDirectives; + } + @JsonProperty("template_type") public String getTemplateType() { return templateType; @@ -117,7 +169,16 @@ public class MulticloudRequest implements Serializable { @Override public String toString() { - return new ToStringBuilder(this).append("genericVnfId", genericVnfId).append("vfModuleId", vfModuleId).append("oofDirectives", oofDirectives).append("sdncDirectives", sdncDirectives).append("templateType", templateType).append("templateData", templateData).toString(); + return new ToStringBuilder(this).append("genericVnfId", genericVnfId) + .append("vfModuleId", vfModuleId) + .append("vfModuleModelInvariantId", vfModuleModelInvariantId) + .append("vfModuleModelVersionId", vfModuleModelVersionId) + .append("vfModuleModelCustomizationId", vfModuleModelCustomizationId) + .append("oofDirectives", oofDirectives) + .append("sdncDirectives", sdncDirectives) + .append("userDirectives", userDirectives) + .append("templateType", templateType) + .append("templateData", templateData).toString(); } } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java index 888d376d37..c771a75976 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java @@ -229,7 +229,7 @@ public class MsoHeatUtilsTest extends BaseTest{ StubOpenStack.mockOpenStackResponseAccess(wireMockPort); StubOpenStack.mockOpenStackPostStack_200("OpenstackResponse_Stack_Created.json"); StubOpenStack.mockOpenStackGet("TEST-stack/stackId"); - StackInfo stackInfo = heatUtils.createStack(cloudSite.getId(), "CloudOwner", "tenantId", "TEST-stack", + StackInfo stackInfo = heatUtils.createStack(cloudSite.getId(), "CloudOwner", "tenantId", "TEST-stack", null, "TEST-heat", new HashMap<>(), false, 1, "TEST-env", new HashMap<>(), new HashMap<>(), false); assertNotNull(stackInfo); diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java index b999b49ab1..b2a69ded46 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java @@ -37,6 +37,7 @@ import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.onap.so.BaseTest; +import org.onap.so.adapters.vdu.VduModelInfo; import org.onap.so.cloud.CloudConfig; import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.db.catalog.beans.CloudSite; @@ -64,9 +65,9 @@ public class MsoMulticloudUtilsTest extends BaseTest { .willReturn(aResponse().withHeader("Content-Type", "application/json") .withBody(CREATE_STACK_RESPONSE) .withStatus(HttpStatus.SC_CREATED))); - StackInfo result = multicloudUtils.createStack("MTN13", "CloudOwner", "TEST-tenant", "TEST-stack", + StackInfo result = multicloudUtils.createStack("MTN13", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), "TEST-heat", new HashMap<>(), false, 200, "TEST-env", - new HashMap<>(), new HashMap<>()); + new HashMap<>(), new HashMap<>(), false); assertNotNull(result); assertEquals("TEST-stack", result.getName()); } @@ -79,9 +80,9 @@ public class MsoMulticloudUtilsTest extends BaseTest { cloudSite.setIdentityService(new CloudIdentity()); when(cloudConfigMock.getCloudSite("MTN13")). thenReturn(Optional.of(cloudSite)); - multicloudUtilsMock.createStack("MTN13", "CloudOwner", "TEST-tenant", "TEST-stack", + multicloudUtilsMock.createStack("MTN13", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), "TEST-heat", new HashMap<>(), false, 200, "TEST-env", - new HashMap<>(), new HashMap<>()); + new HashMap<>(), new HashMap<>(), false); } catch (MsoException e) { assertEquals("0 : Multicloud client could not be initialized", e.toString()); return; @@ -95,9 +96,9 @@ public class MsoMulticloudUtilsTest extends BaseTest { stubFor(post(urlPathEqualTo("/v2.0")) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withStatus(HttpStatus.SC_BAD_REQUEST))); - multicloudUtils.createStack("MTN13", "CloudOwner", "TEST-tenant", "TEST-stack", + multicloudUtils.createStack("MTN13", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), "TEST-heat", new HashMap<>(), false, 200, "TEST-env", - new HashMap<>(), new HashMap<>()); + new HashMap<>(), new HashMap<>(), false); } catch (MsoException e) { assertEquals("0 : Bad Request", e.toString()); return; @@ -110,9 +111,9 @@ public class MsoMulticloudUtilsTest extends BaseTest { stubFor(post(urlPathEqualTo("/v2.0")) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withStatus(HttpStatus.SC_CREATED))); - StackInfo result = multicloudUtils.createStack("MTN13", "CloudOwner", "TEST-tenant", "TEST-stack", + StackInfo result = multicloudUtils.createStack("MTN13", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), "TEST-heat", new HashMap<>(), false, 200, "TEST-env", - new HashMap<>(), new HashMap<>()); + new HashMap<>(), new HashMap<>(), false); assertNotNull(result); assertEquals("TEST-stack/", result.getName()); } diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduModelInfo.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduModelInfo.java index 47f4c74aae..a3ce1b5a6c 100644 --- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduModelInfo.java +++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vdu/VduModelInfo.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,17 +23,31 @@ package org.onap.so.adapters.vdu; import java.util.ArrayList; import java.util.List; -public class VduModelInfo { +public class VduModelInfo { private String modelCustomizationUUID; + private String modelUUID; + private String modelInvariantUUID; private int timeoutMinutes; private List<VduArtifact> artifacts = new ArrayList<>(); - + public String getModelCustomizationUUID() { return modelCustomizationUUID; } public void setModelCustomizationUUID(String modelCustomizationUUID) { this.modelCustomizationUUID = modelCustomizationUUID; } + public String getModelUUID() { + return modelUUID; + } + public void setModelUUID(String modelUUID) { + this.modelUUID = modelUUID; + } + public String getModelInvariantUUID() { + return modelInvariantUUID; + } + public void setModelInvariantUUID(String modelInvariantUUID) { + this.modelInvariantUUID = modelInvariantUUID; + } public int getTimeoutMinutes() { return timeoutMinutes; } @@ -46,5 +60,5 @@ public class VduModelInfo { public void setArtifacts(List<VduArtifact> artifacts) { this.artifacts = artifacts; } - + }
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.6__Fix_CVNFC_Customization.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.6__Fix_CVNFC_Customization.sql new file mode 100644 index 0000000000..f09c7362d5 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.6__Fix_CVNFC_Customization.sql @@ -0,0 +1,23 @@ +use catalogdb; + +DROP TABLE vnf_vfmodule_cvnfc_configuration_customization; + +CREATE TABLE IF NOT EXISTS vnf_vfmodule_cvnfc_configuration_customization ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + `MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, + `CONFIGURATION_TYPE` VARCHAR(200) NULL, + `CONFIGURATION_ROLE` VARCHAR(200) NULL, + `CONFIGURATION_FUNCTION` VARCHAR(200) NULL, + `POLICY_NAME` VARCHAR(200) NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `CONFIGURATION_MODEL_UUID` VARCHAR(200) NOT NULL, + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) DEFAULT NULL, + `VF_MODULE_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) DEFAULT NULL, + `CVNFC_CUSTOMIZATION_ID` INT(11) DEFAULT NULL, + PRIMARY KEY (`ID`), + INDEX `fk_vnf_vfmodule_cvnfc_config_cust__configuration_idx` (`CONFIGURATION_MODEL_UUID` ASC), + + CONSTRAINT `fk_vnf_vfmod_cvnfc_config_cust__configuration_resource` FOREIGN KEY (`CONFIGURATION_MODEL_UUID`) + REFERENCES `configuration` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = INNODB AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = LATIN1;
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7__WorkFlowDesignerTables.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7__WorkFlowDesignerTables.sql new file mode 100644 index 0000000000..e44a6b97ba --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V5.7__WorkFlowDesignerTables.sql @@ -0,0 +1,175 @@ +USE catalogdb; + +CREATE TABLE IF NOT EXISTS `catalogdb`.`workflow` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `ARTIFACT_UUID` VARCHAR(200) NOT NULL, + `ARTIFACT_NAME` VARCHAR(200) NOT NULL, + `NAME` VARCHAR(200) NOT NULL, + `OPERATION_NAME` VARCHAR(200) NULL, + `VERSION` DOUBLE NOT NULL, + `DESCRIPTION` VARCHAR(1200) NULL, + `BODY` LONGTEXT NULL, + `RESOURCE_TARGET` VARCHAR(200) NOT NULL, + `SOURCE` VARCHAR(200) NOT NULL, + `TIMEOUT_MINUTES` INT(11) NULL DEFAULT NULL, + `ARTIFACT_CHECKSUM` VARCHAR(200) NULL DEFAULT 'MANUAL RECORD', + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_workflow` (`ARTIFACT_UUID` ASC, `NAME` ASC, `VERSION` ASC, `SOURCE` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `catalogdb`.`vnf_resource_to_workflow` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `VNF_RESOURCE_MODEL_UUID` VARCHAR(200) NOT NULL, + `WORKFLOW_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_vnf_resource_to_workflow` (`VNF_RESOURCE_MODEL_UUID` ASC, `WORKFLOW_ID` ASC), + INDEX `fk_vnf_resource_to_workflow__workflow1_idx` (`WORKFLOW_ID` ASC), + INDEX `fk_vnf_resource_to_workflow__vnf_res_mod_uuid_idx` (`VNF_RESOURCE_MODEL_UUID` ASC), + CONSTRAINT `fk_vnf_resource_to_workflow__vnf_resource1` + FOREIGN KEY (`VNF_RESOURCE_MODEL_UUID`) + REFERENCES `catalogdb`.`vnf_resource` (`MODEL_UUID`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_vnf_resource_to_workflow__workflow1` + FOREIGN KEY (`WORKFLOW_ID`) + REFERENCES `catalogdb`.`workflow` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `catalogdb`.`activity_spec` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `NAME` VARCHAR(200) NOT NULL, + `DESCRIPTION` VARCHAR(1200) NOT NULL, + `VERSION` DOUBLE NOT NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_activity_spec` (`NAME` ASC, `VERSION` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `catalogdb`.`user_parameters` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `NAME` VARCHAR(200) NOT NULL, + `PAYLOAD_LOCATION` VARCHAR(500) NULL, + `LABEL` VARCHAR(200) NOT NULL, + `TYPE` VARCHAR(200) NOT NULL, + `DESCRIPTION` VARCHAR(1200) NULL, + `IS_REQUIRED` TINYINT(1) NOT NULL, + `MAX_LENGTH` INT(11) NULL, + `ALLOWABLE_CHARS` VARCHAR(200) NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_user_parameters` (`NAME` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `catalogdb`.`workflow_activity_spec_sequence` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `WORKFLOW_ID` INT(11) NOT NULL, + `ACTIVITY_SPEC_ID` INT(11) NOT NULL, + `SEQ_NO` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_workflow_activity_spec_sequence` (`WORKFLOW_ID` ASC, `ACTIVITY_SPEC_ID` ASC, `SEQ_NO` ASC), + INDEX `fk_workflow_activity_spec_sequence__activity_spec_idx` (`ACTIVITY_SPEC_ID` ASC), + INDEX `fk_workflow_activity_spec_sequence__workflow_actifact_uuid_idx` (`WORKFLOW_ID` ASC), + CONSTRAINT `fk_workflow_activity_spec_sequence__activity_spec1` + FOREIGN KEY (`ACTIVITY_SPEC_ID`) + REFERENCES `catalogdb`.`activity_spec` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_workflow_activity_spec_sequence__workflow1` + FOREIGN KEY (`WORKFLOW_ID`) + REFERENCES `catalogdb`.`workflow` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `catalogdb`.`activity_spec_parameters` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `NAME` VARCHAR(200) NOT NULL, + `TYPE` VARCHAR(200) NOT NULL, + `DIRECTION` VARCHAR(200) NULL, + `DESCRIPTION` VARCHAR(1200) NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_activity_spec_parameters` (`NAME` ASC, `DIRECTION` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `catalogdb`.`activity_spec_categories` ( + `ID` INT(11) NOT NULL, + `NAME` VARCHAR(200) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_activity_spec_categories` (`NAME` ASC)) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `catalogdb`.`activity_spec_to_activity_spec_categories` ( + `ID` INT(11) NOT NULL, + `ACTIVITY_SPEC_ID` INT(11) NOT NULL, + `ACTIVITY_SPEC_CATEGORIES_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_activity_spec_to_activity_spec_categories` (`ACTIVITY_SPEC_ID` ASC, `ACTIVITY_SPEC_CATEGORIES_ID` ASC), + INDEX `fk_activity_spec_to_activity_spec_categories__activity_spec_idx` (`ACTIVITY_SPEC_CATEGORIES_ID` ASC), + INDEX `fk_activity_spec_to_activity_spec_categories__activity_spec_idx1` (`ACTIVITY_SPEC_ID` ASC), + CONSTRAINT `fk_activity_spec_to_activity_spec_categories__activity_spec1` + FOREIGN KEY (`ACTIVITY_SPEC_ID`) + REFERENCES `catalogdb`.`activity_spec` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_activity_spec_to_activity_spec_categories__activity_spec_c1` + FOREIGN KEY (`ACTIVITY_SPEC_CATEGORIES_ID`) + REFERENCES `catalogdb`.`activity_spec_categories` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `catalogdb`.`activity_spec_to_activity_spec_parameters` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `ACTIVITY_SPEC_ID` INT(11) NOT NULL, + `ACTIVITY_SPEC_PARAMETERS_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + INDEX `fk_activity_spec_to_activity_spec_params__act_sp_param_id_idx` (`ACTIVITY_SPEC_PARAMETERS_ID` ASC), + UNIQUE INDEX `UK_activity_spec_to_activity_spec_parameters` (`ACTIVITY_SPEC_ID` ASC, `ACTIVITY_SPEC_PARAMETERS_ID` ASC), + INDEX `fk_activity_spec_to_activity_spec_parameters__act_spec_id_idx` (`ACTIVITY_SPEC_ID` ASC), + CONSTRAINT `fk_activity_spec_to_activity_spec_parameters__activity_spec_1` + FOREIGN KEY (`ACTIVITY_SPEC_ID`) + REFERENCES `catalogdb`.`activity_spec` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_activity_spec_to_activity_spec_parameters__activ_spec_param1` + FOREIGN KEY (`ACTIVITY_SPEC_PARAMETERS_ID`) + REFERENCES `catalogdb`.`activity_spec_parameters` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + +CREATE TABLE IF NOT EXISTS `catalogdb`.`activity_spec_to_user_parameters` ( + `ID` INT(11) NOT NULL, + `ACTIVITY_SPEC_ID` INT(11) NOT NULL, + `USER_PARAMETERS_ID` INT(11) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE INDEX `UK_activity_spec_to_user_parameters` (`ACTIVITY_SPEC_ID` ASC, `USER_PARAMETERS_ID` ASC), + INDEX `fk_activity_spec_to_user_parameters__user_parameters1_idx` (`USER_PARAMETERS_ID` ASC), + INDEX `fk_activity_spec_to_user_parameters__activity_spec1_idx` (`ACTIVITY_SPEC_ID` ASC), + CONSTRAINT `fk_activity_spec_to_user_parameters__activity_spec1` + FOREIGN KEY (`ACTIVITY_SPEC_ID`) + REFERENCES `catalogdb`.`activity_spec` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE, + CONSTRAINT `fk_activity_spec_to_user_parameters__user_parameters1` + FOREIGN KEY (`USER_PARAMETERS_ID`) + REFERENCES `catalogdb`.`user_parameters` (`ID`) + ON DELETE CASCADE + ON UPDATE CASCADE) +ENGINE = InnoDB +DEFAULT CHARACTER SET = latin1; + + diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CvnfcCatalogDbQueryTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CvnfcCatalogDbQueryTest.java index 89f4824492..898e8eadf1 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CvnfcCatalogDbQueryTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CvnfcCatalogDbQueryTest.java @@ -89,7 +89,7 @@ public class CvnfcCatalogDbQueryTest { CvnfcCustomization found = foundCvnfcCustomization.get(0); CvnfcCustomization templateCvnfcCustomization = new CvnfcCustomization(); - BeanUtils.copyProperties(found, templateCvnfcCustomization, "vnfVfmoduleCvnfcConfigurationCustomization"); + BeanUtils.copyProperties(found, templateCvnfcCustomization, "vnfVfmoduleCvnfcConfigurationCustomization", "vfModuleCustomization", "vnfcCustomization", "vnfResourceCustomization"); assertThat(cvnfcCustomization, sameBeanAs(templateCvnfcCustomization) .ignoring("id") @@ -99,86 +99,23 @@ public class CvnfcCatalogDbQueryTest { } @Test - public void getLinkedVnfVfmoduleCvnfcConfigurationCustomizationTest() { + public void cVnfcByCustomizationUUID_Test() { - CvnfcCustomization cvnfcCustomization = setUpCvnfcCustomization("0c042562-2bac-11e9-b210-d663bd873d93"); - - VnfcCustomization vnfcCustomization = setUpVnfcCustomization(); - vnfcCustomization.setModelCustomizationUUID("d95d704a-9ff2-11e8-98d0-529269fb1459"); - cvnfcCustomization.setVnfcCustomization(vnfcCustomization); - - ConfigurationResource configurationResource = new ConfigurationResource(); - configurationResource.setToscaNodeType("FabricConfiguration"); - configurationResource.setModelInvariantUUID("modelInvariantUUID"); - configurationResource.setModelUUID("modelUUID"); - configurationResource.setModelName("modelName"); - configurationResource.setModelVersion("modelVersion"); - configurationResource.setDescription("description"); - configurationResource.setToscaNodeType("toscaNodeTypeFC"); - - VnfResource vnfResource = new VnfResource(); - vnfResource.setModelUUID("6f19c5fa-2b19-11e9-b210-d663bd873d93"); - vnfResource.setModelVersion("modelVersion"); - vnfResource.setOrchestrationMode("orchestrationMode"); + CvnfcCustomization cvnfcCustomization = setUpCvnfcCustomization("dadc2c8c-2bab-11e9-b210-d663bd873d93"); + + CvnfcCustomization found = client.getCvnfcCustomizationByCustomizationUUID("dadc2c8c-2bab-11e9-b210-d663bd873d93"); + assertNotNull(found); - VfModule vfModule = new VfModule(); - vfModule.setModelUUID("98aa2a6e-2b18-11e9-b210-d663bd873d93"); - vfModule.setModelInvariantUUID("9fe57860-2b18-11e9-b210-d663bd873d93"); - vfModule.setIsBase(true); - vfModule.setModelName("modelName"); - vfModule.setModelVersion("modelVersion"); - vfModule.setVnfResources(vnfResource); + CvnfcCustomization templateCvnfcCustomization = new CvnfcCustomization(); + BeanUtils.copyProperties(found, templateCvnfcCustomization, "vnfVfmoduleCvnfcConfigurationCustomization", "vfModuleCustomization", "vnfcCustomization", "vnfResourceCustomization"); - VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); - vfModuleCustomization.setModelCustomizationUUID("bdbf984a-2b16-11e9-b210-d663bd873d93"); - vfModuleCustomization.setVfModule(vfModule); - cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization); - - VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization(); - vnfResourceCustomization.setModelCustomizationUUID("6912dd02-2b16-11e9-b210-d663bd873d93"); - vnfResourceCustomization.setModelInstanceName("testModelInstanceName"); - vnfResourceCustomization.setVnfResources(vnfResource); - cvnfcCustomization.setVnfResourceCustomization(vnfResourceCustomization); - - VnfVfmoduleCvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization = new VnfVfmoduleCvnfcConfigurationCustomization(); - vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationFunction("configurationFunction"); - vnfVfmoduleCvnfcConfigurationCustomization.setModelCustomizationUUID("64627fec-2b1b-11e9-b210-d663bd873d93"); - vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationResource(configurationResource); - vnfVfmoduleCvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization); - vnfVfmoduleCvnfcConfigurationCustomization.setModelInstanceName("modelInstanceName"); - vnfVfmoduleCvnfcConfigurationCustomization.setVfModuleCustomization(vfModuleCustomization); - vnfVfmoduleCvnfcConfigurationCustomization.setVnfResourceCustomization(vnfResourceCustomization); - - Set<VnfVfmoduleCvnfcConfigurationCustomization> vnfVfmoduleCvnfcConfigurationCustomizationSet = new HashSet<VnfVfmoduleCvnfcConfigurationCustomization>(); - vnfVfmoduleCvnfcConfigurationCustomizationSet.add(vnfVfmoduleCvnfcConfigurationCustomization); - cvnfcCustomization.setVnfVfmoduleCvnfcConfigurationCustomization(vnfVfmoduleCvnfcConfigurationCustomizationSet); - - vnfVfmoduleCvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization); - - cvnfcCustomizationRepository.save(cvnfcCustomization); - - List<CvnfcCustomization> foundCvnfcCustomization = client.getCvnfcCustomizationByVnfCustomizationUUIDAndVfModuleCustomizationUUID("6912dd02-2b16-11e9-b210-d663bd873d93","bdbf984a-2b16-11e9-b210-d663bd873d93"); - assertNotNull(foundCvnfcCustomization); - assertTrue(foundCvnfcCustomization.size() > 0); - CvnfcCustomization found = foundCvnfcCustomization.get(0); - - Set<VnfVfmoduleCvnfcConfigurationCustomization> vnfVfmoduleCvnfcConfigurationCustomizations = found.getVnfVfmoduleCvnfcConfigurationCustomization(); - if (vnfVfmoduleCvnfcConfigurationCustomizations.size() > 0){ - for(VnfVfmoduleCvnfcConfigurationCustomization customization : vnfVfmoduleCvnfcConfigurationCustomizations) { - Assert.assertTrue(customization.getConfigurationResource().getToscaNodeType().equalsIgnoreCase("toscaNodeTypeFC")); - } - } else { - Assert.fail("No linked VnfVfmoduleCvnfcConfigurationCustomization found for CvnfcCustomization"); - } - - VnfVfmoduleCvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomizationFound = client. - getVnfVfmoduleCvnfcConfigurationCustomizationByVnfCustomizationUuidAndVfModuleCustomizationUuidAndCvnfcCustomizationUuid( - "6912dd02-2b16-11e9-b210-d663bd873d93", - "bdbf984a-2b16-11e9-b210-d663bd873d93", - "0c042562-2bac-11e9-b210-d663bd873d93"); - assertNotNull(vnfVfmoduleCvnfcConfigurationCustomizationFound); - System.out.println(vnfVfmoduleCvnfcConfigurationCustomizationFound.getModelCustomizationUUID()); + assertThat(cvnfcCustomization, sameBeanAs(templateCvnfcCustomization) + .ignoring("id") + .ignoring("created") + .ignoring("vnfVfmoduleCvnfcConfigurationCustomization") + .ignoring("vnfResourceCusteModelCustomizationUUID")); } + protected CvnfcCustomization setUpCvnfcCustomization(String id){ CvnfcCustomization cvnfcCustomization = new CvnfcCustomization(); diff --git a/adapters/mso-openstack-adapters/pom.xml b/adapters/mso-openstack-adapters/pom.xml index cb35e90860..73f50ed908 100644 --- a/adapters/mso-openstack-adapters/pom.xml +++ b/adapters/mso-openstack-adapters/pom.xml @@ -10,11 +10,13 @@ <packaging>jar</packaging> <name>mso-openstack-adapters</name> <description>Consolidate openstack adapters into one Spring Boot project</description> - + <properties> + <openfeign.version>10.1.0</openfeign.version> + </properties> <build> <finalName>${project.artifactId}-${project.version}</finalName> - - <plugins> + + <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> @@ -211,12 +213,44 @@ <artifactId>janino</artifactId> <version>2.5.15</version> </dependency> - - <!-- end added for spring boot support --> - - - - <!-- added for unit testing --> + + <!-- end added for spring boot support --> + + <dependency> + <groupId>org.pacesys</groupId> + <artifactId>openstack4j-core</artifactId> + <version>3.1.0</version> + </dependency> + <dependency> + <groupId>org.pacesys.openstack4j.connectors</groupId> + <artifactId>openstack4j-httpclient</artifactId> + <version>3.1.0</version> + </dependency> + + <dependency> + <groupId>commons-collections</groupId> + <artifactId>commons-collections</artifactId> + <version>3.2.1</version> + </dependency> + + <dependency> + <groupId>com.typesafe</groupId> + <artifactId>config</artifactId> + <version>1.3.2</version> + </dependency> + <dependency> + <groupId>com.google.code.findbugs</groupId> + <artifactId>jsr305</artifactId> + <version>1.3.9</version> + </dependency> + + <dependency> + <groupId>commons-validator</groupId> + <artifactId>commons-validator</artifactId> + <version>1.4.0</version> + </dependency> + + <!-- added for unit testing --> <dependency> <groupId>org.onap.so.adapters</groupId> <artifactId>mso-adapter-utils</artifactId> diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java index 19e3ab71f5..72dee07379 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java @@ -34,6 +34,7 @@ import org.onap.aai.domain.yang.LInterface; import org.onap.aai.domain.yang.LInterfaces; import org.onap.aai.domain.yang.Vserver; import org.onap.so.openstack.utils.MsoHeatUtils; +import org.onap.so.openstack.utils.MsoNeutronUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -43,6 +44,7 @@ import com.woorea.openstack.heat.model.Link; import com.woorea.openstack.heat.model.Resource; import com.woorea.openstack.heat.model.Resources; import com.woorea.openstack.heat.model.Stack; +import com.woorea.openstack.quantum.model.Port; @Component public class HeatStackAudit { @@ -55,6 +57,9 @@ public class HeatStackAudit { protected MsoHeatUtils heat; @Autowired + protected MsoNeutronUtils neutron; + + @Autowired protected AuditVServer auditVservers; public boolean auditHeatStackCreate(String cloudRegion, String cloudOwner, String tenantId, String heatStackName) { @@ -82,8 +87,9 @@ public class HeatStackAudit { if(novaResources.isEmpty()) return true; else{ + List<Optional<Port>> neutronPortDetails = retrieveNeutronPortDetails(resources,cloudRegion,tenantId); List<Resource> resourceGroups = extractResourceGroups(resources); - Set<Vserver> vserversToAudit = createVserverSet(resources, novaResources); + Set<Vserver> vserversToAudit = createVserverSet(resources, novaResources,neutronPortDetails); Set<Vserver> vserversWithSubInterfaces = processSubInterfaces(cloudRegion, tenantId, resourceGroups, vserversToAudit); if(isCreateAudit){ @@ -186,18 +192,16 @@ public class HeatStackAudit { lInterface.getInterfaceId(),subinterfaceStack.getId()); } - protected Set<Vserver> createVserverSet(Resources resources, List<Resource> novaResources) { + protected Set<Vserver> createVserverSet(Resources resources, List<Resource> novaResources, List<Optional<Port>> neutronPortDetails) { Set<Vserver> vserversToAudit = new HashSet<>(); for (Resource novaResource : novaResources) { Vserver auditVserver = new Vserver(); auditVserver.setLInterfaces(new LInterfaces()); auditVserver.setVserverId(novaResource.getPhysicalResourceId()); - Stream<Resource> filteredNeutronNetworks = resources.getList().stream() - .filter(resource -> resource.getRequiredBy().contains(novaResource.getLogicalResourceId())) - .filter(resource -> "OS::Neutron::Port".equals(resource.getType())); - filteredNeutronNetworks.forEach(network -> { + Stream<Port> filteredNeutronPorts = filterNeutronPorts(novaResource, neutronPortDetails); + filteredNeutronPorts.forEach(port -> { LInterface lInterface = new LInterface(); - lInterface.setInterfaceId(network.getPhysicalResourceId()); + lInterface.setInterfaceId(port.getId()); auditVserver.getLInterfaces().getLInterface().add(lInterface); }); vserversToAudit.add(auditVserver); @@ -205,6 +209,31 @@ public class HeatStackAudit { return vserversToAudit; } + /** + * @param novaResource Single openstack resource that is of type Nova + * @param neutronPorts List of Neutron ports created within the stack + * @return Filtered list of neutron ports taht relate to the nova server in openstack + */ + protected Stream<Port> filterNeutronPorts(Resource novaResource, List<Optional<Port>> neutronPorts) { + List<Port> filteredNeutronPorts = neutronPorts.stream().filter(Optional::isPresent).map(Optional::get) + .collect(Collectors.toList()); + return filteredNeutronPorts.stream() + .filter(port -> port.getDeviceId().equalsIgnoreCase(novaResource.getPhysicalResourceId())); + } + + /** + * @param resources Resource stream created by the stack in openstack + * @param cloudSiteId Unique site id to identify which openstack we talk to + * @param tenantId The tenant within the cloud we are talking to where resouces exist + * @return List of optional neutron ports found within the cloud site and tenant + */ + protected List<Optional<Port>> retrieveNeutronPortDetails(Resources resources,String cloudSiteId,String tenantId){ + return resources.getList().stream() + .filter(resource -> "OS::Neutron::Port".equals(resource.getType())) + .map(resource -> neutron.getNeutronPort(resource.getPhysicalResourceId(),cloudSiteId,tenantId)).collect(Collectors.toList()); + + } + protected Optional<String> extractResourcePathFromHref(String href) { try { Optional<String> stackPath = extractStackPathFromHref(href); @@ -234,3 +263,4 @@ public class HeatStackAudit { } } + diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java index 8053cd6f9e..2e8c7990db 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java @@ -537,6 +537,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { "CloudOwner", tenantId, networkName, + null, template, stackParams, true, diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java index f6442b6252..b418368170 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vdu/mapper/VfModuleCustomizationToVduMapper.java @@ -33,25 +33,29 @@ import org.springframework.stereotype.Component; @Component public class VfModuleCustomizationToVduMapper { - + public VduModelInfo mapVfModuleCustomizationToVdu(VfModuleCustomization vfModuleCustom) - { + { VduModelInfo vduModel = new VduModelInfo(); vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID()); - + vduModel.setModelUUID(vfModuleCustom.getVfModule().getModelUUID()); + vduModel.setModelInvariantUUID(vfModuleCustom.getVfModule().getModelInvariantUUID()); + // Map the cloud templates, attached files, and environment file mapCloudTemplates(vfModuleCustom.getVfModule().getModuleHeatTemplate(), vduModel); mapCloudFiles(vfModuleCustom,vduModel); mapEnvironment(vfModuleCustom.getHeatEnvironment(), vduModel); - + return vduModel; } - + public VduModelInfo mapVfModuleCustVolumeToVdu(VfModuleCustomization vfModuleCustom) - { + { VduModelInfo vduModel = new VduModelInfo(); vduModel.setModelCustomizationUUID(vfModuleCustom.getModelCustomizationUUID()); - + vduModel.setModelUUID(vfModuleCustom.getVfModule().getModelUUID()); + vduModel.setModelInvariantUUID(vfModuleCustom.getVfModule().getModelInvariantUUID()); + // Map the cloud templates, attached files, and environment file mapCloudTemplates(vfModuleCustom.getVfModule().getVolumeHeatTemplate(), vduModel); mapCloudFiles(vfModuleCustom,vduModel); @@ -62,20 +66,20 @@ public class VfModuleCustomizationToVduMapper { private void mapCloudTemplates(HeatTemplate heatTemplate, VduModelInfo vduModel) { // TODO: These catalog objects will be refactored to be non-Heat-specific - + List<VduArtifact> vduArtifacts = vduModel.getArtifacts(); - + // Main template. Also set the VDU timeout based on the main template. vduArtifacts.add(mapHeatTemplateToVduArtifact(heatTemplate, ArtifactType.MAIN_TEMPLATE)); vduModel.setTimeoutMinutes(heatTemplate.getTimeoutMinutes()); - + // Nested templates List<HeatTemplate> childTemplates = heatTemplate.getChildTemplates(); if (childTemplates != null) { for(HeatTemplate childTemplate : childTemplates){ vduArtifacts.add(mapHeatTemplateToVduArtifact(childTemplate, ArtifactType.NESTED_TEMPLATE)); } - } + } } private VduArtifact mapHeatTemplateToVduArtifact(HeatTemplate heatTemplate, ArtifactType artifactType) { @@ -85,12 +89,12 @@ public class VfModuleCustomizationToVduMapper { vduArtifact.setType(artifactType); return vduArtifact; } - + private void mapCloudFiles(VfModuleCustomization vfModuleCustom, VduModelInfo vduModel) { // TODO: These catalog objects will be refactored to be non-Heat-specific - + List<VduArtifact> vduArtifacts = vduModel.getArtifacts(); - + // Attached Files List<HeatFiles> heatFiles = vfModuleCustom.getVfModule().getHeatFiles(); if (heatFiles != null) { @@ -115,7 +119,7 @@ public class VfModuleCustomizationToVduMapper { vduArtifacts.add(mapEnvironmentFileToVduArtifact(heatEnvironment)); } } - + private VduArtifact mapEnvironmentFileToVduArtifact(HeatEnvironment heatEnv) { VduArtifact vduArtifact = new VduArtifact(); vduArtifact.setName(heatEnv.getName()); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java index 0563d6c242..949027f7c1 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java @@ -37,10 +37,22 @@ import java.util.concurrent.TimeUnit; import javax.jws.WebService; import javax.xml.ws.Holder; +import org.apache.commons.collections.CollectionUtils; +import org.onap.so.adapters.valet.GenericValetResponse; +import org.onap.so.adapters.valet.ValetClient; +import org.onap.so.adapters.valet.beans.HeatRequest; +import org.onap.so.adapters.valet.beans.ValetConfirmResponse; +import org.onap.so.adapters.valet.beans.ValetCreateResponse; +import org.onap.so.adapters.valet.beans.ValetDeleteResponse; +import org.onap.so.adapters.valet.beans.ValetRollbackResponse; +import org.onap.so.adapters.valet.beans.ValetStatus; +import org.onap.so.adapters.valet.beans.ValetUpdateResponse; import org.onap.so.adapters.vnf.exceptions.VnfAlreadyExists; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.adapters.vnf.exceptions.VnfNotFound; +import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.cloud.CloudConfig; +import org.onap.so.db.catalog.beans.CloudIdentity; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.HeatEnvironment; import org.onap.so.db.catalog.beans.HeatFiles; @@ -54,27 +66,26 @@ import org.onap.so.db.catalog.data.repository.VnfResourceRepository; import org.onap.so.db.catalog.utils.MavenLikeVersioning; import org.onap.so.entity.MsoRequest; import org.onap.so.logger.ErrorCode; +import org.onap.so.heatbridge.HeatBridgeApi; +import org.onap.so.heatbridge.HeatBridgeImpl; +import org.onap.so.heatbridge.openstack.api.OpenstackClient; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.HeatStatus; import org.onap.so.openstack.beans.StackInfo; import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.beans.VnfStatus; +import org.onap.so.openstack.exceptions.MsoCloudSiteNotFound; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoExceptionCategory; import org.onap.so.openstack.exceptions.MsoHeatNotFoundException; import org.onap.so.openstack.utils.MsoHeatEnvironmentEntry; import org.onap.so.openstack.utils.MsoHeatUtils; import org.onap.so.openstack.utils.MsoHeatUtilsWithUpdate; -import org.onap.so.adapters.valet.ValetClient; -import org.onap.so.adapters.valet.beans.HeatRequest; -import org.onap.so.adapters.valet.beans.ValetConfirmResponse; -import org.onap.so.adapters.valet.beans.ValetCreateResponse; -import org.onap.so.adapters.valet.beans.ValetDeleteResponse; -import org.onap.so.adapters.valet.beans.ValetRollbackResponse; -import org.onap.so.adapters.valet.beans.ValetStatus; -import org.onap.so.adapters.valet.beans.ValetUpdateResponse; -import org.onap.so.adapters.valet.GenericValetResponse; +import org.openstack4j.model.compute.Flavor; +import org.openstack4j.model.compute.Image; +import org.openstack4j.model.compute.Server; +import org.openstack4j.model.heat.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -509,6 +520,67 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } } + private void heatbridge(StackInfo heatStack, String cloudSiteId, String tenantId, String genericVnfName, + String vfModuleId) { + try { + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); + CloudIdentity cloudIdentity = cloudSite.getIdentityService(); + String heatStackId = heatStack.getCanonicalName().split("/")[1]; + + String cloudOwner = "CloudOwner";//cloud owner needs to come from bpmn-adapter + List<String> oobMgtNetNames = new ArrayList<>(); + + HeatBridgeApi heatBridgeClient = new HeatBridgeImpl(new AAIResourcesClient(), cloudIdentity, + cloudOwner, cloudSiteId, tenantId); + + OpenstackClient openstackClient = heatBridgeClient.authenticate(); + List<Resource> stackResources = heatBridgeClient.queryNestedHeatStackResources(heatStackId); + + List<Server> osServers = heatBridgeClient.getAllOpenstackServers(stackResources); + + List<Image> osImages = heatBridgeClient.extractOpenstackImagesFromServers(osServers); + + List<Flavor> osFlavors = heatBridgeClient.extractOpenstackFlavorsFromServers(osServers); + + logger.debug("Successfully queried heat stack{} for resources.", heatStackId); + //os images + if (osImages != null && !osImages.isEmpty()) { + heatBridgeClient.buildAddImagesToAaiAction(osImages); + logger.debug("Successfully built AAI actions to add images."); + } else { + logger.debug("No images to update to AAI."); + } + //flavors + if (osFlavors != null && !osFlavors.isEmpty()) { + heatBridgeClient.buildAddFlavorsToAaiAction(osFlavors); + logger.debug("Successfully built AAI actions to add flavors."); + } else { + logger.debug("No flavors to update to AAI."); + } + + //compute resources + heatBridgeClient.buildAddVserversToAaiAction(genericVnfName, vfModuleId, osServers); + logger.debug("Successfully queried compute resources and built AAI vserver actions."); + + //neutron resources + List<String> oobMgtNetIds = new ArrayList<>(); + + //if no network-id list is provided, however network-name list is + if (!CollectionUtils.isEmpty(oobMgtNetNames)) { + oobMgtNetIds = heatBridgeClient.extractNetworkIds(oobMgtNetNames); + } + heatBridgeClient.buildAddVserverLInterfacesToAaiAction(stackResources, oobMgtNetIds); + logger.debug( + "Successfully queried neutron resources and built AAI actions to add l-interfaces to vservers."); + + //Update AAI + heatBridgeClient.submitToAai(); + } catch (Exception ex) { + logger.debug("Heatbrige failed for stackId: " + heatStack.getCanonicalName(), ex); + } + } + private String convertNode(final JsonNode node) { try { final Object obj = JSON_MAPPER.treeToValue(node, Object.class); @@ -1206,6 +1278,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { cloudOwner, tenantId, vfModuleName, + null, template, goldenInputs, true, @@ -1270,7 +1343,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.error("Exception encountered while sending Confirm to Valet ", e); } } - logger.debug("VF Module {} successfully created", vfModuleName); + logger.debug ("VF Module {} successfully created", vfModuleName); + //call heatbridge + heatbridge(heatStack, cloudSiteId, tenantId, genericVnfName, vfModuleId); return; } catch (Exception e) { logger.debug("unhandled exception in create VF",e); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java new file mode 100644 index 0000000000..6b06761474 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeApi.java @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.so.heatbridge; + +import java.util.List; +import org.onap.so.heatbridge.openstack.api.OpenstackClient; +import org.openstack4j.model.compute.Flavor; +import org.openstack4j.model.compute.Image; +import org.openstack4j.model.compute.Server; +import org.openstack4j.model.heat.Resource; + +/** + * Defines the contract to extract Heat Stack Resources from Openstack and inventory it to AAI. + * This API is used only to "create" objects in AAI. + */ +public interface HeatBridgeApi { + + /** + * Authenticate with Openstack Keystone. The auth information is read from SO cloud configuration file. + * + * @return Openstack client object with keystone token + * @throws HeatBridgeException upon failure to authenticate with keystone + */ + OpenstackClient authenticate() throws HeatBridgeException; + + /** + * Query all the stack based resources from Openstack Heat service + * + * @param heatStackId Heat stack UUID + * @return A list of stack based resources + */ + List<Resource> queryNestedHeatStackResources(String heatStackId); + + /** + * Get a filtered list of resource IDs by resource type + * + * @param stackResources A list of stack based resources + * @param resourceType Resource type to filter by + * @return A list of stack resources matching the specified resource-type + */ + List<String> extractStackResourceIdsByResourceType(List<Resource> stackResources, String resourceType); + + /** + * Get network IDs for a given list of network names. + * It is assumed that there is a one to one mapping between the name and ID. + * @param networkNameList List of network names + * @return List of matching network IDs + */ + List<String> extractNetworkIds(List<String> networkNameList); + + /** + * Query the Openstack server objects from the list of stack resources + * + * @param stackResources A list of stack based resources + * @return A list of Openstack Server objects + */ + List<Server> getAllOpenstackServers(List<Resource> stackResources); + + /** + * Extract Openstack Image objects from a a list of Server objects + * + * @param servers A list of Openstack Server objects + * @return A list of Openstack Image objects + */ + List<Image> extractOpenstackImagesFromServers(List<Server> servers); + + /** + * Extract Openstack Flavor objects from a a list of Server objects + * + * @param servers A list of Openstack Server objects + * @return A list of Openstack Flavor objects + */ + List<Flavor> extractOpenstackFlavorsFromServers(List<Server> servers); + + /** + * Query and build AAI actions for Openstack Image resources to AAI's image objects + * + * @param images List of Openstack Image objects + * @throws HeatBridgeException when failing to add images to AAI + */ + void buildAddImagesToAaiAction(List<Image> images) throws HeatBridgeException; + + /** + * Query and build AAI actions for Openstack Flavor resources to AAI's flavor objects + * + * @param flavors List of Openstack Flavor objects + * @throws HeatBridgeException when failing to add flavors to AAI + */ + void buildAddFlavorsToAaiAction(List<Flavor> flavors) throws HeatBridgeException; + + /** + * Query and build AAI actions for Openstack Compute resources to AAI's vserver objects + * + * @param genericVnfId AAI generic-vnf-id + * @param vfModuleId AAI vf-module-id + * @param servers Openstack Server list + */ + void buildAddVserversToAaiAction(String genericVnfId, String vfModuleId, List<Server> servers); + + /** + * Query and build AAI actions for Openstack Neutron resources associated with a Compute resource to AAI's + * l-interface objects + * + * @param stackResources Openstack Heat stack resource list + * @param oobMgtNetIds List of OOB network IDs list + */ + void buildAddVserverLInterfacesToAaiAction(List<Resource> stackResources, List<String> oobMgtNetIds); + + /** + * Execute AAI restful API to update the Openstack resources + * + * @throws HeatBridgeException when failing to add openstack resource PoJos to AAI + */ + void submitToAai() throws HeatBridgeException; +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java new file mode 100644 index 0000000000..f993d71e4c --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeException.java @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.so.heatbridge; + +public class HeatBridgeException extends Exception { + + private static final long serialVersionUID = -1472047930391718894L; + + public HeatBridgeException(final String message) { + super(message); + } + + public HeatBridgeException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java new file mode 100644 index 0000000000..90ceeb7d1c --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/HeatBridgeImpl.java @@ -0,0 +1,365 @@ +/* + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.so.heatbridge; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import javax.annotation.Nonnull; +import javax.ws.rs.WebApplicationException; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.validator.routines.InetAddressValidator; +import org.onap.aai.domain.yang.Flavor; +import org.onap.aai.domain.yang.Image; +import org.onap.aai.domain.yang.L3InterfaceIpv4AddressList; +import org.onap.aai.domain.yang.LInterface; +import org.onap.aai.domain.yang.PInterface; +import org.onap.aai.domain.yang.SriovPf; +import org.onap.aai.domain.yang.SriovPfs; +import org.onap.aai.domain.yang.SriovVf; +import org.onap.aai.domain.yang.SriovVfs; +import org.onap.aai.domain.yang.Vlan; +import org.onap.aai.domain.yang.Vlans; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.AAISingleTransactionClient; +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.client.graphinventory.exceptions.BulkProcessFailed; +import org.onap.so.db.catalog.beans.CloudIdentity; +import org.onap.so.heatbridge.constants.HeatBridgeConstants; +import org.onap.so.heatbridge.factory.MsoCloudClientFactoryImpl; +import org.onap.so.heatbridge.helpers.AaiHelper; +import org.onap.so.heatbridge.openstack.api.OpenstackClient; +import org.onap.so.heatbridge.openstack.factory.OpenstackClientFactoryImpl; +import org.onap.so.heatbridge.utils.HeatBridgeUtils; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.ErrorCode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.openstack4j.model.compute.Server; +import org.openstack4j.model.heat.Resource; +import org.openstack4j.model.network.IP; +import org.openstack4j.model.network.Network; +import org.openstack4j.model.network.NetworkType; +import org.openstack4j.model.network.Port; + +import com.google.common.base.Preconditions; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; + +/** + * This class provides an implementation of {@link HeatBridgeApi} + */ +public class HeatBridgeImpl implements HeatBridgeApi { + + private static final Logger logger = LoggerFactory.getLogger(HeatBridgeImpl.class); + private static final String ERR_MSG_NULL_OS_CLIENT = "Initialization error: Null openstack client. Authenticate with Keystone first."; + private static final String OOB_MGT_NETWORK_IDENTIFIER = "Management"; + private OpenstackClient osClient; + private AAIResourcesClient resourcesClient; + private AAISingleTransactionClient transaction; + private String cloudOwner; + private String cloudRegionId; + private String tenantId; + private AaiHelper aaiHelper = new AaiHelper(); + private CloudIdentity cloudIdentity; + + + public HeatBridgeImpl(AAIResourcesClient resourcesClient, final CloudIdentity cloudIdentity, + @Nonnull final String cloudOwner, @Nonnull final String cloudRegionId, @Nonnull final String tenantId) { + Objects.requireNonNull(cloudOwner, "Null cloud-owner value!"); + Objects.requireNonNull(cloudRegionId, "Null cloud-region identifier!"); + Objects.requireNonNull(tenantId, "Null tenant identifier!"); + Objects.requireNonNull(tenantId, "Null AAI actions list!"); + + this.cloudIdentity = cloudIdentity; + this.cloudOwner = cloudOwner; + this.cloudRegionId = cloudRegionId; + this.tenantId = tenantId; + this.resourcesClient = resourcesClient; + this.transaction = resourcesClient.beginSingleTransaction(); + } + + @Override + public OpenstackClient authenticate() throws HeatBridgeException { + this.osClient = new MsoCloudClientFactoryImpl(new OpenstackClientFactoryImpl()) + .getOpenstackClient(cloudIdentity.getIdentityUrl(), cloudIdentity.getMsoId(), cloudIdentity.getMsoPass(), cloudRegionId, tenantId); + logger.debug("Successfully authenticated with keystone for tenant: " + tenantId + " and cloud " + + "region: " + cloudRegionId); + return osClient; + } + + @Override + public List<Resource> queryNestedHeatStackResources(final String heatStackId) { + Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); + Preconditions.checkState(!Strings.isNullOrEmpty(heatStackId), "Invalid heatStackId!"); + List<Resource> stackBasedResources = osClient + .getStackBasedResources(heatStackId, HeatBridgeConstants.OS_DEFAULT_HEAT_NESTING); + logger.debug(stackBasedResources.size() + " heat stack resources are extracted for stack: " + heatStackId); + return stackBasedResources; + } + + @Override + public List<String> extractStackResourceIdsByResourceType(final List<Resource> stackResources, + final String resourceType) { + return stackResources.stream() + .filter(stackResource -> stackResource.getType().equals(resourceType)) + .map(Resource::getPhysicalResourceId) + .collect(Collectors.toList()); + } + + @Override + public List<String> extractNetworkIds(final List<String> networkNameList) { + Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); + return networkNameList.stream() + .map(netName -> osClient.listNetworksByFilter(ImmutableMap.of(HeatBridgeConstants.OS_NAME_KEY, netName))) + .filter(nets -> nets != null && nets.size() == 1) //extract network-id only if network-name is unique + .map(nets -> nets.get(0).getId()) + .collect(Collectors.toList()); + } + + @Override + public List<Server> getAllOpenstackServers(final List<Resource> stackResources) { + Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); + + // Filter Openstack Compute resources + List<String> serverIds = extractStackResourceIdsByResourceType(stackResources, + HeatBridgeConstants.OS_SERVER_RESOURCE_TYPE); + return serverIds.stream().map(serverId -> osClient.getServerById(serverId)).collect(Collectors.toList()); + } + + @Override + public List<org.openstack4j.model.compute.Image> extractOpenstackImagesFromServers(final List<Server> servers) { + Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); + return servers.stream().map(Server::getImage) + .filter(distinctByProperty(org.openstack4j.model.compute.Image::getId)).collect(Collectors.toList()); + } + + @Override + public List<org.openstack4j.model.compute.Flavor> extractOpenstackFlavorsFromServers(final List<Server> servers) { + Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); + return servers.stream().map(Server::getFlavor) + .filter(distinctByProperty(org.openstack4j.model.compute.Flavor::getId)).collect(Collectors.toList()); + } + + @Override + public void buildAddImagesToAaiAction(final List<org.openstack4j.model.compute.Image> images) + throws HeatBridgeException { + for (org.openstack4j.model.compute.Image image : images) { + Image aaiImage = aaiHelper.buildImage(image); + try { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.IMAGE, cloudOwner, cloudRegionId, aaiImage.getImageId()); + if (!resourcesClient.exists(uri)) { + transaction.create(uri, aaiImage); + logger.debug("Queuing AAI command to add image: " + aaiImage.getImageId()); + } else { + logger.debug("Nothing to add since image: " + aaiImage.getImageId() + "already exists in AAI."); + } + } catch (WebApplicationException e) { + throw new HeatBridgeException("Failed to update image to AAI: " + aaiImage.getImageId() + ". Error" + + " cause: " + e, e); + } + } + } + + @Override + public void buildAddFlavorsToAaiAction(final List<org.openstack4j.model.compute.Flavor> flavors) + throws HeatBridgeException { + for (org.openstack4j.model.compute.Flavor flavor : flavors) { + Flavor aaiFlavor = aaiHelper.buildFlavor(flavor); + try { + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.FLAVOR, cloudOwner, cloudRegionId, aaiFlavor.getFlavorId()); + if (!resourcesClient.exists(uri)) { + transaction.create(uri, aaiFlavor); + logger.debug("Queuing AAI command to add flavor: " + aaiFlavor.getFlavorId()); + } else { + logger.debug("Nothing to add since flavor: " + aaiFlavor.getFlavorId() + "already exists in AAI."); + } + } catch (WebApplicationException e) { + throw new HeatBridgeException("Failed to update flavor to AAI: " + aaiFlavor.getFlavorId() + ". Error" + + " cause: " + e, e); + } + } + } + + @Override + public void buildAddVserversToAaiAction(final String genericVnfId, final String vfModuleId, + final List<Server> servers) { + servers.forEach(server -> { + Vserver vserver = aaiHelper.buildVserver(server.getId(), server); + + // Build vserver relationships to: image, flavor, pserver, vf-module + vserver.setRelationshipList(aaiHelper.getVserverRelationshipList(cloudOwner, cloudRegionId, genericVnfId, + vfModuleId, server)); + transaction.create(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegionId, tenantId, vserver.getVserverId()), vserver); + }); + } + + @Override + public void buildAddVserverLInterfacesToAaiAction(final List<Resource> stackResources, + final List<String> oobMgtNetIds) { + Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT); + List<String> portIds = extractStackResourceIdsByResourceType(stackResources, + HeatBridgeConstants.OS_PORT_RESOURCE_TYPE); + for (String portId : portIds) { + Port port = osClient.getPortById(portId); + LInterface lIf = new LInterface(); + lIf.setInterfaceId(port.getId()); + lIf.setInterfaceName(port.getName()); + lIf.setMacaddr(port.getMacAddress()); + if (oobMgtNetIds != null && oobMgtNetIds.contains(port.getNetworkId())) { + lIf.setInterfaceRole(OOB_MGT_NETWORK_IDENTIFIER); + } else { + lIf.setInterfaceRole(port.getvNicType()); + } + + updateLInterfaceIps(port, lIf); + updateLInterfaceVlan(port, lIf); + + // Update l-interface to the vserver + transaction.create(AAIUriFactory.createResourceUri( + AAIObjectType.L_INTERFACE, cloudOwner, cloudRegionId, tenantId, port.getDeviceId(), lIf.getInterfaceName()), lIf); + } + } + + private void updateLInterfaceVlan(final Port port, final LInterface lIf) { + Vlan vlan = new Vlan(); + Network network = osClient.getNetworkById(port.getNetworkId()); + lIf.setNetworkName(network.getName()); + if (network.getNetworkType().equals(NetworkType.VLAN)) { + vlan.setVlanInterface(network.getProviderSegID()); + Vlans vlans = new Vlans(); + List<Vlan> vlanList = vlans.getVlan(); + vlanList.add(vlan); + lIf.setVlans(vlans); + } + // Build sriov-vf to the l-interface + if (port.getvNicType().equalsIgnoreCase(HeatBridgeConstants.OS_SRIOV_PORT_TYPE)) { + SriovVfs sriovVfs = new SriovVfs(); + // JAXB does not generate setters for list, however getter ensures its creation. + // Thus, all list manipulations must be made on live list. + List<SriovVf> sriovVfList = sriovVfs.getSriovVf(); + SriovVf sriovVf = new SriovVf(); + sriovVf.setPciId(port.getProfile().get(HeatBridgeConstants.OS_PCI_SLOT_KEY).toString()); + sriovVf.setNeutronNetworkId(port.getNetworkId()); + if (port.getVifDetails() != null) { + sriovVf.setVfVlanFilter((String) port.getVifDetails().get(HeatBridgeConstants.OS_VLAN_NETWORK_KEY)); + } + sriovVfList.add(sriovVf); + + lIf.setSriovVfs(sriovVfs); + + // For the given port create sriov-pf for host pserver/p-interface if absent + updateSriovPfToPserver(port, lIf); + } + } + + /** + * Needs to be corrected according to the specification that is in draft + * If pserver/p-interface does not have a SRIOV-PF object matching the PCI-ID of the Openstack port object, then + * create it in AAI. + * Openstack SRIOV Port object has pci-id (to match sriov-pf on pserver/p-interface), physical-network ID (that + * matches the p-interface name). + * + * @param port Openstack port object + * @param lIf AAI l-interface object + */ + private void updateSriovPfToPserver(final Port port, final LInterface lIf) { + if (port.getProfile() == null || Strings + .isNullOrEmpty(port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString())) { + logger.debug("The SRIOV port:" + port.getName() + " is missing physical-network-id, cannot update " + + "sriov-pf object for host pserver: " + port.getHostId()); + return; + } + Optional<String> matchingPifName = HeatBridgeUtils + .getMatchingPserverPifName(port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString()); + if (matchingPifName.isPresent()) { + // Update l-interface description + String pserverHostName = port.getHostId(); + lIf.setInterfaceDescription( + "Attached to SR-IOV port: " + pserverHostName + "::" + matchingPifName.get()); + try { + Optional<PInterface> matchingPIf = resourcesClient.get(PInterface.class, + AAIUriFactory.createResourceUri(AAIObjectType.P_INTERFACE, pserverHostName, matchingPifName.get()).depth(Depth.ONE)); + if (matchingPIf.isPresent()) { + SriovPfs pIfSriovPfs = matchingPIf.get().getSriovPfs(); + if (pIfSriovPfs == null) { + pIfSriovPfs = new SriovPfs(); + } + // Extract PCI-ID from OS port object + String pfPciId = port.getProfile().get(HeatBridgeConstants.OS_PCI_SLOT_KEY).toString(); + + List<SriovPf> existingSriovPfs = pIfSriovPfs.getSriovPf(); + if (CollectionUtils.isEmpty(existingSriovPfs) || existingSriovPfs.stream() + .noneMatch(existingSriovPf -> existingSriovPf.getPfPciId().equals(pfPciId))) { + // Add sriov-pf object with PCI-ID to AAI + SriovPf sriovPf = new SriovPf(); + sriovPf.setPfPciId(pfPciId); + logger.debug("Queuing AAI command to update sriov-pf object to pserver: " + pserverHostName + "/" + + matchingPifName.get()); + transaction.create(AAIUriFactory.createResourceUri( + AAIObjectType.SRIOV_PF, pserverHostName, matchingPifName.get(), sriovPf.getPfPciId()), sriovPf); + } + } + } catch (WebApplicationException e) { + // Silently log that we failed to update the Pserver p-interface with PCI-ID + logger.error("{} {} {} {} {} {} {} {} {}", MessageEnum.GENERAL_EXCEPTION, pserverHostName, matchingPifName.get(), cloudOwner, + tenantId, "OpenStack", "Heatbridge", ErrorCode.DataError.getValue(), "Exception - Failed to add sriov-pf object to pserver", e); + } + } + } + + private void updateLInterfaceIps(final Port port, final LInterface lIf) { + List<L3InterfaceIpv4AddressList> lInterfaceIps = lIf.getL3InterfaceIpv4AddressList(); + for (IP ip : port.getFixedIps()) { + String ipAddress = ip.getIpAddress(); + if (InetAddressValidator.getInstance().isValidInet4Address(ipAddress)) { + L3InterfaceIpv4AddressList lInterfaceIp = new L3InterfaceIpv4AddressList(); + lInterfaceIp.setL3InterfaceIpv4Address(ipAddress); + lInterfaceIp.setNeutronNetworkId(port.getNetworkId()); + lInterfaceIp.setNeutronSubnetId(ip.getSubnetId()); + lInterfaceIp.setL3InterfaceIpv4PrefixLength(32L); + lInterfaceIps.add(lInterfaceIp); + } + } + } + + @Override + public void submitToAai() throws HeatBridgeException { + try { + transaction.execute(); + } catch (BulkProcessFailed e) { + String msg = "Failed to commit transaction"; + logger.debug(msg + " with error: " + e); + throw new HeatBridgeException(msg, e); + } + } + + private <T> Predicate<T> distinctByProperty(Function<? super T, Object> keyExtractor) { + Map<Object, Boolean> map = new ConcurrentHashMap<>(); + return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java new file mode 100644 index 0000000000..1f302341ad --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/constants/HeatBridgeConstants.java @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.so.heatbridge.constants; + +public class HeatBridgeConstants { + + private HeatBridgeConstants() { + throw new IllegalStateException("Trying to instantiate a constants class."); + } + + /** + * Openstack related constants + */ + public static final Integer OS_DEFAULT_HEAT_NESTING = 5; + public static final String OS_SERVER_RESOURCE_TYPE = "OS::Nova::Server"; + public static final String OS_PORT_RESOURCE_TYPE = "OS::Neutron::Port"; + public static final String OS_SRIOV_PORT_TYPE = "direct"; + public static final String OS_PCI_SLOT_KEY = "pci_slot"; + public static final String OS_PHYSICAL_NETWORK_KEY = "physical_network"; + public static final String OS_VLAN_NETWORK_KEY = "vlan"; + public static final String OS_UNKNOWN_KEY = "unknown"; + public static final String OS_RESOURCES_SELF_LINK_KEY = "self"; + public static final String OS_DEFAULT_DOMAIN_NAME = "default"; + public static final String OS_KEYSTONE_V2_KEY = "v2.0"; + public static final String OS_KEYSTONE_V3_KEY = "v3"; + public static final String OS_NAME_KEY = "name"; + + /** + * AAI related constants + */ + public static final String AAI_GENERIC_VNF = "generic-vnf"; + public static final String AAI_GENERIC_VNF_ID = "generic-vnf.vnf-id"; + public static final String AAI_PSERVER = "pserver"; + public static final String AAI_VSERVER = "vserver"; + public static final String AAI_PSERVER_HOSTNAME = "pserver.hostname"; + public static final String AAI_VF_MODULE = "vf-module"; + public static final String AAI_VF_MODULE_ID = "vf-module.vf-module-id"; + public static final String AAI_IMAGE = "image"; + public static final String AAI_IMAGE_ID = "image.image-id"; + public static final String AAI_CLOUD_OWNER = "cloud-region.cloud-owner"; + public static final String AAI_CLOUD_REGION_ID = "cloud-region.cloud-region-id"; + public static final String AAI_FLAVOR = "flavor"; + public static final String AAI_FLAVOR_ID = "flavor.flavor-id"; + public static final String AAI_RESOURCE_DEPTH_ALL = "all"; + public static final String AAI_SRIOV_PF = "sriov-pf"; + public static final String AAI_P_INTERFACE_NAME = "p-interface.interface-name"; + public static final String AAI_SRIOV_PF_PCI_ID = "sriov-pf.pf-pci-id"; + + /** + * Keys for internal usage + */ + public static final String KEY_FLAVORS = "flavors"; + public static final String KEY_IMAGES = "images"; + public static final String KEY_VSERVERS = "vservers"; + public static final String KEY_SRIOV_PFS = "pserverSriovPfs"; + public static final String KEY_GLOBAL_SUBSCRIBER_ID = "globalSubscriberId"; + public static final String KEY_SERVICE_TYPE = "subscriptionServiceType"; + public static final String KEY_SERVICE_INSTANCE_ID = "serviceInstanceId"; + public static final String KEY_VNF_INSTANCE_ID = "genericVnfId"; + public static final String KEY_MSO_REQUEST_ID = "msoRequestId"; + public static final String KEY_SO_WORKFLOW_EXCEPTION = "WorkflowException"; + public static final String KEY_PROCESS_STATUS_MSG = "processStatusMsg"; +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java new file mode 100644 index 0000000000..100b50e502 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactory.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.so.heatbridge.factory; + +import org.onap.so.heatbridge.HeatBridgeException; +import org.onap.so.heatbridge.openstack.api.OpenstackClient; + +/** + * Defines contract to load the cloud configuration from SO, authenticate with keystone for a given cloud-region and + * tenant. + */ +public interface MsoCloudClientFactory { + + /** + * Get the Openstack Client for keystone version specified in cloud configuration. + * + * @param url openstack url + * @param msoId openstack user for mso + * @param msoPass openstack password for mso user + * @param cloudRegionId cloud-region identifier + * @param tenantId tenant identifier + * @return Openstack Client for the keystone version requested + * @throws HeatBridgeException if any errors when reading cloud configuration or getting openstack client + */ + + + OpenstackClient getOpenstackClient(String url, String msoId, String msoPass, String cloudRegionId, String tenantId) throws HeatBridgeException; +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java new file mode 100644 index 0000000000..b70b32a4d6 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/factory/MsoCloudClientFactoryImpl.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.so.heatbridge.factory; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Objects; +import javax.annotation.Nonnull; +import org.onap.so.heatbridge.HeatBridgeException; +import org.onap.so.heatbridge.constants.HeatBridgeConstants; +import org.onap.so.heatbridge.openstack.api.OpenstackAccess; +import org.onap.so.heatbridge.openstack.api.OpenstackAccess.OpenstackAccessBuilder; +import org.onap.so.heatbridge.openstack.api.OpenstackClient; +import org.onap.so.heatbridge.openstack.api.OpenstackClientException; +import org.onap.so.heatbridge.openstack.factory.OpenstackClientFactory; +import org.onap.so.utils.CryptoUtils; + +/** + * This class implements {@link MsoCloudClientFactory} + * It loads the cloud configuration from SO and uses it to authenticate with keystone. + * As a result of authentication with keystone, it returns the Openstack client with the auth token so that + * subsequent API calls to Openstack can be made. + */ +public class MsoCloudClientFactoryImpl implements MsoCloudClientFactory { + + private OpenstackClientFactory openstackClientFactory; + + public MsoCloudClientFactoryImpl(@Nonnull OpenstackClientFactory openstackClientFactory) { + Objects.requireNonNull(openstackClientFactory, "Null OpenstackClientFactory object"); + this.openstackClientFactory = openstackClientFactory; + } + @Override + public OpenstackClient getOpenstackClient(@Nonnull String url, @Nonnull String msoId, @Nonnull String msoPass, @Nonnull String cloudRegionId, @Nonnull String tenantId) throws + HeatBridgeException { + Objects.requireNonNull(url, "Null openstack url!"); + Objects.requireNonNull(msoId, "Null openstack user id!"); + Objects.requireNonNull(msoPass, "Null openstack password!"); + Objects.requireNonNull(cloudRegionId, "Null cloud-region ID!"); + Objects.requireNonNull(tenantId, "Null tenant ID!"); + try { + final OpenstackAccess osAccess = new OpenstackAccessBuilder() + .setBaseUrl(url) // keystone URL + .setUser(msoId) // keystone username + .setPassword(CryptoUtils.decryptCloudConfigPassword(msoPass)) // keystone decrypted password + .setRegion(cloudRegionId) // openstack region + .setDomainName(HeatBridgeConstants.OS_DEFAULT_DOMAIN_NAME) // hardcode to "default" + .setTenantId(tenantId) // tenantId + .build(); + + // Identify the Keystone version + String version = new URL(url).getPath().replace("/", ""); + if (version.equals(HeatBridgeConstants.OS_KEYSTONE_V2_KEY)) { + return openstackClientFactory.createOpenstackV2Client(osAccess); + } else if (version.equals(HeatBridgeConstants.OS_KEYSTONE_V3_KEY)) { + return openstackClientFactory.createOpenstackV3Client(osAccess); + } + throw new OpenstackClientException("Unsupported keystone version!"); + } catch (MalformedURLException e) { + throw new HeatBridgeException("Malformed Keystone Endpoint in SO configuration.", e); + } catch (OpenstackClientException osClientEx) { + throw new HeatBridgeException("Client error when authenticating with the Openstack V3.", osClientEx); + } + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java new file mode 100644 index 0000000000..a0f1f0798f --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java @@ -0,0 +1,275 @@ +/* + * Copyright (C) 2018 Bell Canada. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.so.heatbridge.helpers; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.apache.commons.collections.CollectionUtils; +import org.onap.aai.domain.yang.Flavor; +import org.onap.aai.domain.yang.Image; +import org.onap.aai.domain.yang.Relationship; +import org.onap.aai.domain.yang.RelationshipData; +import org.onap.aai.domain.yang.RelationshipList; +import org.onap.aai.domain.yang.SriovVf; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.heatbridge.constants.HeatBridgeConstants; +import org.openstack4j.model.compute.Server; + +/** + * This class provides wrapper methods to manage creation of AAI objects and extracting objects from AAI and + * transforming into required objects. + */ +public class AaiHelper { + + /** + * Build vserver relationship object to entities: pserver, vf-module, image, flavor + * + * @param cloudOwner AAI cloudOwner value + * @param cloudRegionId AAI cloud-region identifier + * @param genericVnfId AAI generic-vnf identifier + * @param vfModuleId AAI vf-module identifier + * @param server Openstack Server object + */ + public RelationshipList getVserverRelationshipList(final String cloudOwner, final String cloudRegionId, final String + genericVnfId, final String vfModuleId, final Server server) { + RelationshipList relationshipList = new RelationshipList(); + List<Relationship> relationships = relationshipList.getRelationship(); + + // vserver to pserver relationship + Relationship pserverRelationship = buildRelationship(HeatBridgeConstants.AAI_PSERVER, + ImmutableMap.<String, String>builder() + .put(HeatBridgeConstants.AAI_PSERVER_HOSTNAME, server.getHypervisorHostname()) + .build()); + relationships.add(pserverRelationship); + + // vserver to vf-module relationship + Relationship vfModuleRelationship = buildRelationship(HeatBridgeConstants.AAI_VF_MODULE, + ImmutableMap.<String, String>builder() + .put(HeatBridgeConstants.AAI_GENERIC_VNF_ID, genericVnfId) + .put(HeatBridgeConstants.AAI_VF_MODULE_ID, vfModuleId) + .build()); + relationships.add(vfModuleRelationship); + + // vserver to image relationship + Relationship imageRel = buildRelationship(HeatBridgeConstants.AAI_IMAGE, + ImmutableMap.<String, String>builder() + .put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner) + .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId) + .put(HeatBridgeConstants.AAI_IMAGE_ID, server.getImage().getId()) + .build()); + relationships.add(imageRel); + + // vserver to flavor relationship + Relationship flavorRel = buildRelationship(HeatBridgeConstants.AAI_FLAVOR, + ImmutableMap.<String, String>builder() + .put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner) + .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId) + .put(HeatBridgeConstants.AAI_FLAVOR_ID, server.getFlavor().getId()) + .build()); + relationships.add(flavorRel); + return relationshipList; + } + + public RelationshipList getLInterfaceRelationshipList(final String pserverName, final String pIfName, + final String pfPciId) { + RelationshipList relationshipList = new RelationshipList(); + List<Relationship> relationships = relationshipList.getRelationship(); + + // sriov-vf to sriov-pf relationship + Relationship sriovPfRelationship = buildRelationship(HeatBridgeConstants.AAI_SRIOV_PF, + ImmutableMap.<String, String>builder() + .put(HeatBridgeConstants.AAI_PSERVER_HOSTNAME, pserverName) + .put(HeatBridgeConstants.AAI_P_INTERFACE_NAME, pIfName) + .put(HeatBridgeConstants.AAI_SRIOV_PF_PCI_ID, pfPciId) + .build()); + relationships.add(sriovPfRelationship); + + return relationshipList; + } + + /** + * Transform Openstack Server object to AAI Vserver object + * + * @param serverId Openstack server identifier + * @param server Openstack server object + * @return AAI Vserver object + */ + public Vserver buildVserver(final String serverId, final Server server) { + Vserver vserver = new Vserver(); + vserver.setInMaint(false); + vserver.setIsClosedLoopDisabled(false); + vserver.setVserverId(serverId); + vserver.setVserverName(server.getName()); + vserver.setVserverName2(server.getName()); + vserver.setProvStatus(server.getStatus().value()); + server.getLinks().stream().filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY)) + .findFirst().ifPresent(link -> vserver.setVserverSelflink(link.getHref())); + return vserver; + } + + /** + * Transform Openstack Image object to AAI Image object + * + * @param image Openstack Image object + * @return AAI Image object + */ + public Image buildImage(final org.openstack4j.model.compute.Image image) { + Image aaiImage = new Image(); + aaiImage.setImageId(image.getId()); + aaiImage.setImageName(image.getName()); + aaiImage.setImageOsDistro(HeatBridgeConstants.OS_UNKNOWN_KEY); + aaiImage.setImageOsVersion(HeatBridgeConstants.OS_UNKNOWN_KEY); + image.getLinks().stream().filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY)) + .findFirst().ifPresent(link -> aaiImage.setImageSelflink(link.getHref())); + return aaiImage; + } + + /** + * Transform Openstack Flavor object to AAI Flavor object + * + * @param flavor Openstack Flavor object + * @return AAI Flavor object + */ + public Flavor buildFlavor(final org.openstack4j.model.compute.Flavor flavor) { + Flavor aaiFlavor = new Flavor(); + aaiFlavor.setFlavorId(flavor.getId()); + aaiFlavor.setFlavorName(flavor.getName()); + flavor.getLinks().stream().filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY)) + .findFirst().ifPresent(link -> aaiFlavor.setFlavorSelflink(link.getHref())); + return aaiFlavor; + } + + /** + * Extract a list of flavors URI associated with the list of vservers + * + * @param vservers List of vserver AAI objects + * @return a list of related flavor related-links + */ + public List<String> getFlavorsUriFromVserver(final List<Vserver> vservers) { + List<String> flavorUris = new ArrayList<>(); + vservers.forEach(vserver -> flavorUris.addAll( + filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_FLAVOR))); + return flavorUris; + } + + /** + * Extract a list of images URI associated with the list of vservers + * + * @param vservers List of vserver AAI objects + * @return a list of related image related-links + */ + public List<String> getImagesUriFromVserver(final List<Vserver> vservers) { + List<String> imageUris = new ArrayList<>(); + vservers.forEach(vserver -> imageUris.addAll( + filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_IMAGE))); + return imageUris; + } + + /** + * From the list vserver objects build a map of compute hosts's name and the PCI IDs linked to it. + * + * @param vservers List of vserver AAI objects + * @return a map of compute names to the PCI ids associated with the compute + */ + public Map<String, List<String>> getPserverToPciIdMap(final List<Vserver> vservers) { + Map<String, List<String>> pserverToPciIdMap = new HashMap<>(); + for(Vserver vserver : vservers) { + if(vserver.getLInterfaces() != null) { + List<String> pciIds = vserver.getLInterfaces().getLInterface() + .stream() + .filter(lInterface -> lInterface.getSriovVfs() != null + && CollectionUtils.isNotEmpty(lInterface.getSriovVfs().getSriovVf())) + .flatMap(lInterface -> lInterface.getSriovVfs().getSriovVf().stream()) + .map(SriovVf::getPciId) + .collect(Collectors.toList()); + if (CollectionUtils.isNotEmpty(pciIds)) { + List<String> matchingPservers = extractRelationshipDataValue(vserver.getRelationshipList(), + HeatBridgeConstants.AAI_PSERVER, HeatBridgeConstants.AAI_PSERVER_HOSTNAME); + Preconditions.checkState(matchingPservers != null && matchingPservers.size() == 1, + "Invalid pserver relationships for vserver: " + vserver.getVserverName()); + pserverToPciIdMap.put(matchingPservers.get(0), pciIds); + } + } + } + return pserverToPciIdMap; + } + + /** + * Extract from relationship-list object all the relationship-value that match the related-to and + * relationship-key fields. + * + * @param relationshipListObj AAI relationship-list object + * @param relatedToProperty related-to value + * @param relationshipKey relationship-key value + * @return relationship-value matching the key requested for the relationship object of type related-to property + */ + private List<String> extractRelationshipDataValue(final RelationshipList relationshipListObj, + final String relatedToProperty, final String relationshipKey) { + if (relationshipListObj != null && relationshipListObj.getRelationship() != null) { + return relationshipListObj.getRelationship().stream() + .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty)) + .map(Relationship::getRelationshipData) + .flatMap(Collection::stream) + .filter(data -> data.getRelationshipKey() != null && relationshipKey.equals(data.getRelationshipKey())) + .map(RelationshipData::getRelationshipValue) + .collect(Collectors.toList()); + } + return new ArrayList<>(); + } + + /** + * Extract and filter the related-links to all objects that match the type specified by the filter property + * + * @param relationshipListObj AAI object representing relationship object + * @param relatedToProperty Value identifying the type of AAI object for related-to field + * @return a list of related-links filtered by the specified related-to property + */ + private List<String> filterRelatedLinksByRelatedToProperty(final RelationshipList relationshipListObj, + final String relatedToProperty) { + if (relationshipListObj != null && relationshipListObj.getRelationship() != null) { + return relationshipListObj.getRelationship().stream() + .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty)) + .map(Relationship::getRelatedLink) + .collect(Collectors.toList()); + } + return new ArrayList<>(); + } + + /** + * Build the relationship object + * + * @param relatedTo Related to entity value + * @param relationshipKeyValues Key value pairs of relationship data + * @return AAI Relationship object + */ + private Relationship buildRelationship(final String relatedTo, final Map<String, String> relationshipKeyValues) { + Relationship relationship = new Relationship(); + relationship.setRelatedTo(relatedTo); + relationshipKeyValues.keySet().forEach(k -> { + RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey(k); + relationshipData.setRelationshipValue(relationshipKeyValues.get(k)); + relationship.getRelationshipData().add(relationshipData); + }); + return relationship; + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackAccess.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackAccess.java new file mode 100644 index 0000000000..fd5dabc784 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackAccess.java @@ -0,0 +1,120 @@ +/*- + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.so.heatbridge.openstack.api; + +import org.openstack4j.model.common.Identifier; + +/** + * Object handling OpenStack API access information. + */ +public class OpenstackAccess { + private final String baseUrl; + private final String tenantId; + private final String user; + private final String password; + private final String region; + private String domainName; + private String projectName; + + public OpenstackAccess(OpenstackAccessBuilder builder) { + this.baseUrl = builder.baseUrl; + this.tenantId = builder.tenantId; + this.user = builder.user; + this.password = builder.password; + this.region = builder.region; + this.domainName = builder.domainName; + this.projectName = builder.projectName; + } + + public String getUrl() { + return baseUrl; + } + + public String getTenantId() { + return tenantId; + } + + public String getUser() { + return user; + } + + public String getPassword() { + return password; + } + + public String getRegion() { + return region; + } + + public Identifier getDomainNameIdentifier() { + return Identifier.byName(domainName); + } + + public String getProjectName() { + return projectName; + } + + public static class OpenstackAccessBuilder { + + private String baseUrl; + private String tenantId; + private String user; + private String password; + private String region; + private String domainName; + private String projectName; + + public OpenstackAccessBuilder setBaseUrl(final String baseUrl) { + this.baseUrl = baseUrl; + return this; + } + + public OpenstackAccessBuilder setTenantId(final String tenantId) { + this.tenantId = tenantId; + return this; + } + + public OpenstackAccessBuilder setUser(final String user) { + this.user = user; + return this; + } + + public OpenstackAccessBuilder setPassword(final String password) { + this.password = password; + return this; + } + + public OpenstackAccessBuilder setRegion(final String region) { + this.region = region; + return this; + } + + public OpenstackAccessBuilder setDomainName(final String domainName) { + this.domainName = domainName; + return this; + } + + public OpenstackAccessBuilder setProjectName(final String projectName) { + this.projectName = projectName; + return this; + } + + public OpenstackAccess build() { + return new OpenstackAccess(this); + } + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java new file mode 100644 index 0000000000..143e33581d --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClient.java @@ -0,0 +1,69 @@ +/*- + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.so.heatbridge.openstack.api; + +import java.util.List; +import java.util.Map; +import org.openstack4j.model.compute.Server; +import org.openstack4j.model.heat.Resource; +import org.openstack4j.model.network.Network; +import org.openstack4j.model.network.Port; + +public interface OpenstackClient { + + /** + * Get a server object by server ID + * @param serverId Unique server-name (simple name) or server-id (UUID) + * @return Server object + */ + Server getServerById(String serverId); + + /** + * Get a port object by port ID + * @param portId Unique UUID of the port. + * @return Port object. + */ + Port getPortById(String portId); + + /** + * Returns a list of all ports we have the right to see + * @return List of all Openstack ports + */ + List<Port> getAllPorts(); + + /** + * Returns a list of all the resources for the stack + * @param stackId Stack name or unique UUID + * @param nestingDepth The recursion level for which resources will be listed. + * @return List of Openstack Stack resources + */ + List<Resource> getStackBasedResources(String stackId, int nestingDepth); + + /** + * Get a network instance by network ID + * @param networkId Unique UUID of the network. + * @return Network object. + */ + Network getNetworkById(String networkId); + + /** + * List networks by filtering parameters + * @param filterParams key-value pairs for filtering params + * @return List of filtered Network objects + */ + List<Network> listNetworksByFilter(Map<String, String> filterParams); +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientException.java new file mode 100644 index 0000000000..a062ca826d --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientException.java @@ -0,0 +1,29 @@ +/*- + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.so.heatbridge.openstack.api; + +public class OpenstackClientException extends Exception { + private static final long serialVersionUID = -5514207977226960180L; + + public OpenstackClientException(final String message) { + super(message); + } + + public OpenstackClientException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java new file mode 100644 index 0000000000..ebd4753323 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackClientImpl.java @@ -0,0 +1,69 @@ +/*- + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.so.heatbridge.openstack.api; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; +import org.openstack4j.api.OSClient; +import org.openstack4j.model.compute.Server; +import org.openstack4j.model.heat.Resource; +import org.openstack4j.model.network.Network; +import org.openstack4j.model.network.Port; + +abstract class OpenstackClientImpl implements OpenstackClient { + @Override + public Server getServerById(String serverId) { + return getClient().compute().servers().get(serverId); + } + + @Override + public Port getPortById(String portId) { + return getClient().networking().port().get(portId); + } + + @Override + public List<Port> getAllPorts() { return (List<Port>)getClient().networking().port().list(); } + + @Override + public List<Resource> getStackBasedResources(String stackId, int nestingDepth) { + return getClient().heat() + .resources() + .list(stackId, nestingDepth) + .stream() + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + @Override + public Network getNetworkById(String networkId) { + return getClient().networking().network().get(networkId); + } + + @Override + public List<Network> listNetworksByFilter(Map<String, String> filterParams) { + return (List<Network>) getClient().networking().network().list(filterParams); + } + + /** + * Retrieves the specific client to utilize. + * @return The specific client to utilize + */ + protected abstract OSClient getClient(); + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV2ClientImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV2ClientImpl.java new file mode 100644 index 0000000000..760be72b3f --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV2ClientImpl.java @@ -0,0 +1,37 @@ +/*- + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.so.heatbridge.openstack.api; + +import org.openstack4j.api.OSClient; +import org.openstack4j.api.OSClient.OSClientV2; + +public class OpenstackV2ClientImpl extends OpenstackClientImpl { + + private OSClientV2 client; + + public OpenstackV2ClientImpl(OSClientV2 client) { + this.client = client; + } + + /** + * {@inheritDoc} + */ + protected OSClient getClient() { + return client; + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV3ClientImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV3ClientImpl.java new file mode 100644 index 0000000000..dddd82ce6a --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/api/OpenstackV3ClientImpl.java @@ -0,0 +1,37 @@ +/*- + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.so.heatbridge.openstack.api; + +import org.openstack4j.api.OSClient; +import org.openstack4j.api.OSClient.OSClientV3; + +public class OpenstackV3ClientImpl extends OpenstackClientImpl { + + private OSClientV3 client; + + public OpenstackV3ClientImpl(OSClientV3 client) { + this.client = client; + } + + /** + * {@inheritDoc} + */ + protected OSClient getClient() { + return client; + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactory.java new file mode 100644 index 0000000000..5019eec09b --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactory.java @@ -0,0 +1,27 @@ +/*- + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.so.heatbridge.openstack.factory; + +import org.onap.so.heatbridge.openstack.api.OpenstackAccess; +import org.onap.so.heatbridge.openstack.api.OpenstackClient; +import org.onap.so.heatbridge.openstack.api.OpenstackClientException; + +public interface OpenstackClientFactory { + + OpenstackClient createOpenstackV3Client(OpenstackAccess osAccess) throws OpenstackClientException; + + OpenstackClient createOpenstackV2Client(OpenstackAccess osAccess) throws OpenstackClientException; +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java new file mode 100644 index 0000000000..72b3795053 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/openstack/factory/OpenstackClientFactoryImpl.java @@ -0,0 +1,74 @@ +/*- + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.so.heatbridge.openstack.factory; + +import com.google.common.base.Preconditions; +import org.onap.so.heatbridge.openstack.api.OpenstackAccess; +import org.onap.so.heatbridge.openstack.api.OpenstackClient; +import org.onap.so.heatbridge.openstack.api.OpenstackClientException; +import org.onap.so.heatbridge.openstack.api.OpenstackV2ClientImpl; +import org.onap.so.heatbridge.openstack.api.OpenstackV3ClientImpl; +import org.openstack4j.api.OSClient.OSClientV2; +import org.openstack4j.api.OSClient.OSClientV3; +import org.openstack4j.api.exceptions.AuthenticationException; +import org.openstack4j.openstack.OSFactory; + +public class OpenstackClientFactoryImpl implements OpenstackClientFactory { + + @Override + public OpenstackClient createOpenstackV3Client(OpenstackAccess osAccess) throws OpenstackClientException { + Preconditions.checkNotNull(osAccess.getUrl(), "Keystone-v3 Auth: endpoint not set."); + Preconditions.checkNotNull(osAccess.getUser(), "Keystone-v3 Auth: username not set."); + Preconditions.checkNotNull(osAccess.getPassword(), "Keystone-v3 Auth: password not set."); + Preconditions.checkNotNull(osAccess.getDomainNameIdentifier(), "Keystone-v3 Auth: domain not set."); + Preconditions.checkNotNull(osAccess.getRegion(), "Keystone-v3 Auth: region not set."); + + OSClientV3 client; + try { + client = OSFactory.builderV3() + .endpoint(osAccess.getUrl()) + .credentials(osAccess.getUser(), osAccess.getPassword(), osAccess.getDomainNameIdentifier()) + .authenticate() + .useRegion(osAccess.getRegion()); + return new OpenstackV3ClientImpl(client); + } catch (AuthenticationException exception) { + throw new OpenstackClientException("Failed to authenticate with Keystone-v3: " + osAccess.getUrl(), exception); + } + } + + @Override + public OpenstackClient createOpenstackV2Client(OpenstackAccess osAccess) throws OpenstackClientException { + Preconditions.checkNotNull(osAccess.getUrl(), "Keystone-v2 Auth: endpoint not set."); + Preconditions.checkNotNull(osAccess.getUser(), "Keystone-v2 Auth: username not set."); + Preconditions.checkNotNull(osAccess.getPassword(), "Keystone-v2 Auth: password not set."); + Preconditions.checkNotNull(osAccess.getTenantId(), "Keystone-v2 Auth: domain not set."); + Preconditions.checkNotNull(osAccess.getRegion(), "Keystone-v2 Auth: region not set."); + + OSClientV2 client; + try { + client = OSFactory.builderV2() + .endpoint(osAccess.getUrl()) + .credentials(osAccess.getUser(), osAccess.getPassword()) + .tenantId(osAccess.getTenantId()) + .authenticate() + .useRegion(osAccess.getRegion()); + return new OpenstackV2ClientImpl(client); + } catch (AuthenticationException exception) { + throw new OpenstackClientException("Failed to authenticate with Keystone-v2.0: " + osAccess.getUrl(), + exception); + } + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java new file mode 100644 index 0000000000..7daa8c2c71 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/utils/HeatBridgeUtils.java @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.so.heatbridge.utils; + +import com.google.common.base.Preconditions; +import com.google.common.base.Strings; +import java.util.Optional; +import javax.annotation.Nonnull; + +public class HeatBridgeUtils { + + private HeatBridgeUtils() { + throw new IllegalStateException("Trying to instantiate a utility class."); + } + + /** + * IaaS naming convention for compute/p-interface to openstack/physical-network name mapping + */ + private static final String OS_SIDE_SHARED_SRIOV_PREFIX = "shared-"; + private static final String OS_SIDE_DEDICATED_SRIOV_PREFIX = "dedicated-"; + private static final String COMPUTE_SIDE_SHARED_SRIOV_PREFIX = "sriov-s-"; + private static final String COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX = "sriov-d-"; + + public static Optional<String> getMatchingPserverPifName(@Nonnull final String physicalNetworkName) { + Preconditions.checkState(!Strings.isNullOrEmpty(physicalNetworkName), "Physical network name is null or " + + "empty!"); + if (physicalNetworkName.contains(OS_SIDE_DEDICATED_SRIOV_PREFIX)) { + return Optional + .of(physicalNetworkName.replace(OS_SIDE_DEDICATED_SRIOV_PREFIX, COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX)); + } else if (physicalNetworkName.contains(OS_SIDE_SHARED_SRIOV_PREFIX)) { + return Optional + .of(physicalNetworkName.replace(OS_SIDE_SHARED_SRIOV_PREFIX, COMPUTE_SIDE_SHARED_SRIOV_PREFIX)); + } + return Optional.empty(); + } + + public static Optional<String> getMatchingPhysicalNetworkName(final String pserverPinterfaceName) { + if (pserverPinterfaceName.contains(COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX)) { + return Optional + .of(pserverPinterfaceName.replace(COMPUTE_SIDE_DEDICATED_SRIOV_PREFIX, OS_SIDE_DEDICATED_SRIOV_PREFIX)); + } else if (pserverPinterfaceName.contains(COMPUTE_SIDE_SHARED_SRIOV_PREFIX)) { + return Optional + .of(pserverPinterfaceName.replace(COMPUTE_SIDE_SHARED_SRIOV_PREFIX, OS_SIDE_SHARED_SRIOV_PREFIX)); + } + return Optional.empty(); + } +} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java index 5eea46d09f..987e4cf76d 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java @@ -26,6 +26,7 @@ import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; import java.io.File; +import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; @@ -42,6 +43,7 @@ import org.onap.aai.domain.yang.LInterface; import org.onap.aai.domain.yang.LInterfaces; import org.onap.aai.domain.yang.Vserver; import org.onap.so.openstack.utils.MsoHeatUtils; +import org.onap.so.openstack.utils.MsoNeutronUtils; import org.skyscreamer.jsonassert.JSONAssert; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -49,6 +51,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.woorea.openstack.heat.model.Resource; import com.woorea.openstack.heat.model.Resources; import com.woorea.openstack.heat.model.Stack; +import com.woorea.openstack.quantum.model.Port; @RunWith(MockitoJUnitRunner.Silent.class) @@ -61,6 +64,9 @@ public class HeatStackAuditTest extends HeatStackAudit { private MsoHeatUtils msoHeatUtilsMock; @Mock + private MsoNeutronUtils neutronUtilsMock; + + @Mock private AuditVServer auditVserver; private static final String cloudRegion = "cloudRegion"; @@ -72,10 +78,32 @@ public class HeatStackAuditTest extends HeatStackAudit { private ObjectMapper stackObjectMapper = new ObjectMapper().configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); + private List<Optional<Port>> portList = new ArrayList<>(); + @Before public void setup() throws Exception{ resources= objectMapper.readValue(new File("src/test/resources/GetResources.json"), Resources.class); + Port neutronPort1 =stackObjectMapper.readValue(new File("src/test/resources/NeutronPort1.json"), Port.class); + doReturn(Optional.of(neutronPort1)).when(neutronUtilsMock).getNeutronPort("7ee06d9d-3d18-411c-9d3e-aec930f70413", cloudRegion,tenantId); + Port neutronPort2 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort2.json"), Port.class); + doReturn(Optional.of(neutronPort2)).when(neutronUtilsMock).getNeutronPort("27391d94-33af-474a-927d-d409249e8fd3", cloudRegion,tenantId); + Port neutronPort3 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort3.json"), Port.class); + doReturn(Optional.of(neutronPort3)).when(neutronUtilsMock).getNeutronPort("fdeedf37-c01e-4ab0-bdd6-8d5fc4913943", cloudRegion,tenantId); + Port neutronPort4 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort4.json"), Port.class); + doReturn(Optional.of(neutronPort4)).when(neutronUtilsMock).getNeutronPort("8d93f63e-e972-48c7-ad98-b2122da47315", cloudRegion,tenantId); + Port neutronPort5 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort5.json"), Port.class); + doReturn(Optional.of(neutronPort5)).when(neutronUtilsMock).getNeutronPort("0594a2f2-7ea4-42eb-abc2-48ea49677fca", cloudRegion,tenantId); + Port neutronPort6 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort6.json"), Port.class); + doReturn(Optional.of(neutronPort6)).when(neutronUtilsMock).getNeutronPort("00bb8407-650e-48b5-b919-33b88d6f8fe3", cloudRegion,tenantId); + + portList.add(Optional.empty()); + portList.add(Optional.of(neutronPort1)); + portList.add(Optional.of(neutronPort2)); + portList.add(Optional.of(neutronPort3)); + portList.add(Optional.of(neutronPort4)); + portList.add(Optional.of(neutronPort5)); + portList.add(Optional.of(neutronPort6)); } @Test @@ -111,13 +139,13 @@ public class HeatStackAuditTest extends HeatStackAudit { vServer1.setLInterfaces(vServer1Linterfaces); LInterface ssc_1_trusted_port_0 = new LInterface(); - ssc_1_trusted_port_0.setInterfaceId("d2f51f82-0ec2-4581-bd1a-d2a82073e52b"); + ssc_1_trusted_port_0.setInterfaceId("7ee06d9d-3d18-411c-9d3e-aec930f70413"); vServer1.getLInterfaces().getLInterface().add(ssc_1_trusted_port_0); LInterface ssc_1_mgmt_port_1 = new LInterface(); - ssc_1_mgmt_port_1.setInterfaceId("07f5b14c-147a-4d14-8c94-a9e94dbc097b"); + ssc_1_mgmt_port_1.setInterfaceId("fdeedf37-c01e-4ab0-bdd6-8d5fc4913943"); vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_1); LInterface ssc_1_mgmt_port_0 = new LInterface(); @@ -187,7 +215,7 @@ public class HeatStackAuditTest extends HeatStackAudit { Resources service1ResourceQuerySubInt3 = objectMapper.readValue(new File("src/test/resources/Service1SubInterface2Resources.json"), Resources.class); doReturn(service1ResourceQuerySubInt3).when(msoHeatUtilsMock).executeHeatClientRequest("/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c/resources", cloudRegion,tenantId, Resources.class); - Set<Vserver> vServersToAudit = heatStackAudit.createVserverSet(resources, novaResources); + Set<Vserver> vServersToAudit = heatStackAudit.createVserverSet(resources, novaResources,portList); Set<Vserver> vserversWithSubInterfaces = heatStackAudit.processSubInterfaces(cloudRegion,tenantId,resourceGroups, vServersToAudit); String actualValue = objectMapper.writeValueAsString(vserversWithSubInterfaces); @@ -219,7 +247,7 @@ public class HeatStackAuditTest extends HeatStackAudit { vServer1.setLInterfaces(vServer1Linterfaces); LInterface ssc_1_trusted_port_0 = new LInterface(); - ssc_1_trusted_port_0.setInterfaceId("d2f51f82-0ec2-4581-bd1a-d2a82073e52b"); + ssc_1_trusted_port_0.setInterfaceId("7ee06d9d-3d18-411c-9d3e-aec930f70413"); vServer1.getLInterfaces().getLInterface().add(ssc_1_trusted_port_0); LInterface ssc_1_service1_port_0 = new LInterface(); @@ -227,7 +255,7 @@ public class HeatStackAuditTest extends HeatStackAudit { vServer1.getLInterfaces().getLInterface().add(ssc_1_service1_port_0); LInterface ssc_1_mgmt_port_1 = new LInterface(); - ssc_1_mgmt_port_1.setInterfaceId("07f5b14c-147a-4d14-8c94-a9e94dbc097b"); + ssc_1_mgmt_port_1.setInterfaceId("fdeedf37-c01e-4ab0-bdd6-8d5fc4913943"); vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_1); LInterface ssc_1_mgmt_port_0 = new LInterface(); @@ -244,7 +272,7 @@ public class HeatStackAuditTest extends HeatStackAudit { expectedVservers.add(vServer1); - Set<Vserver> actualVservers = heatStackAudit.createVserverSet(resources, novaResources); + Set<Vserver> actualVservers = heatStackAudit.createVserverSet(resources, novaResources,portList); assertThat(actualVservers, sameBeanAs(expectedVservers)); } diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java new file mode 100644 index 0000000000..3c777e17cb --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/heatbridge/HeatBridgeImplTest.java @@ -0,0 +1,375 @@ +/* + * Copyright (C) 2018 Bell Canada. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.so.heatbridge; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +import org.apache.commons.io.FileUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.aai.domain.yang.LInterface; +import org.onap.aai.domain.yang.PInterface; +import org.onap.aai.domain.yang.SriovPf; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.AAISingleTransactionClient; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.client.graphinventory.exceptions.BulkProcessFailed; +import org.onap.so.db.catalog.beans.CloudIdentity; +import org.onap.so.heatbridge.constants.HeatBridgeConstants; +import org.onap.so.heatbridge.openstack.api.OpenstackClient; +import org.onap.so.heatbridge.openstack.api.OpenstackClientException; +import org.openstack4j.model.compute.Flavor; +import org.openstack4j.model.compute.Image; +import org.openstack4j.model.compute.Server; +import org.openstack4j.model.compute.Server.Status; +import org.openstack4j.model.heat.Resource; +import org.openstack4j.model.network.Network; +import org.openstack4j.model.network.NetworkType; +import org.openstack4j.model.network.Port; +import org.openstack4j.openstack.heat.domain.HeatResource; +import org.openstack4j.openstack.heat.domain.HeatResource.Resources; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; + + +@RunWith(MockitoJUnitRunner.class) +public class HeatBridgeImplTest { + + private static final String CLOUD_OWNER = "CloudOwner"; + private static final String REGION_ID = "RegionOne"; + private static final String TENANT_ID = "7320ec4a5b9d4589ba7c4412ccfd290f"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Mock + private OpenstackClient osClient; + + private CloudIdentity cloudIdentity = new CloudIdentity(); + + @Mock + private AAIResourcesClient resourcesClient; + @Mock + private AAISingleTransactionClient transaction; + + private HeatBridgeImpl heatbridge; + + @Before + public void setUp() throws HeatBridgeException, OpenstackClientException, BulkProcessFailed { + + when(resourcesClient.beginSingleTransaction()).thenReturn(transaction); + heatbridge = new HeatBridgeImpl(resourcesClient, cloudIdentity, CLOUD_OWNER, REGION_ID, TENANT_ID); + } + + @Ignore + @Test + public void testQueryNestedHeatStackResources() throws HeatBridgeException { + // Arrange + String heatStackId = "1234567"; + List<Resource> expectedResourceList = (List<Resource>) extractTestStackResources(); + when(osClient.getStackBasedResources(heatStackId, HeatBridgeConstants.OS_DEFAULT_HEAT_NESTING)) + .thenReturn(expectedResourceList); + + // Act + List<Resource> resourceList = heatbridge.queryNestedHeatStackResources(heatStackId); + + // Assert + verify(osClient).getStackBasedResources(heatStackId, HeatBridgeConstants.OS_DEFAULT_HEAT_NESTING); + assertEquals(resourceList, expectedResourceList); + } + + @Test + public void testExtractStackResourceIdsByResourceType() throws HeatBridgeException { + // Arrange + List<Resource> expectedResourceList = (List<Resource>) extractTestStackResources(); + List<String> expectedServerIds = Arrays.asList("43c2159b-2c04-46ac-bda5-594110cae2d3", + "7cff109a-b2b7-4933-97b4-ec44a8365568"); + + // Act + List<String> serverIds = heatbridge + .extractStackResourceIdsByResourceType(expectedResourceList, HeatBridgeConstants.OS_SERVER_RESOURCE_TYPE); + + // Assert + assertEquals(expectedServerIds, serverIds); + } + + @Ignore + @Test + public void testGetAllOpenstackServers() { + // Arrange + List<Resource> stackResources = (List<Resource>) extractTestStackResources(); + + Server server1 = mock(Server.class); + Server server2 = mock(Server.class); + List<Server> expectedServers = Arrays.asList(server1, server2); + + when(osClient.getServerById("43c2159b-2c04-46ac-bda5-594110cae2d3")).thenReturn(server1); + when(osClient.getServerById("7cff109a-b2b7-4933-97b4-ec44a8365568")).thenReturn(server2); + + // Act + List<Server> servers = heatbridge.getAllOpenstackServers(stackResources); + + // Assert + assertEquals(expectedServers, servers); + } + + @Ignore + @Test + public void testExtractOpenstackImagesFromServers() { + // Arrange + Server server1 = mock(Server.class); + Server server2 = mock(Server.class); + List<Server> servers = Arrays.asList(server1, server2); + + Image image1 = mock(Image.class); + Image image2 = mock(Image.class); + when(image1.getId()).thenReturn("1"); + when(image2.getId()).thenReturn("1"); + List<Image> expectedDistinctImages = Collections.singletonList(image1); + + when(server1.getImage()).thenReturn(image1); + when(server2.getImage()).thenReturn(image2); + + // Act + List<Image> images = heatbridge.extractOpenstackImagesFromServers(servers); + + // Assert + assertEquals(expectedDistinctImages, images); + } + + @Ignore + @Test + public void testExtractOpenstackFlavorsFromServers() { + // Arrange + Server server1 = mock(Server.class); + Server server2 = mock(Server.class); + List<Server> servers = Arrays.asList(server1, server2); + + Flavor flavor1 = mock(Flavor.class); + Flavor flavor2 = mock(Flavor.class); + when(flavor1.getId()).thenReturn("1"); + when(flavor2.getId()).thenReturn("2"); + List<Flavor> expectedFlavors = Arrays.asList(flavor1, flavor2); + + when(server1.getFlavor()).thenReturn(flavor1); + when(server2.getFlavor()).thenReturn(flavor2); + + // Act + List<Flavor> flavors = heatbridge.extractOpenstackFlavorsFromServers(servers); + + // Assert + assertEquals(expectedFlavors, flavors); + } + + @Test + public void testUpdateVserversToAai() throws HeatBridgeException { + // Arrange + Server server1 = mock(Server.class); + + when(server1.getId()).thenReturn("test-server1-id"); + when(server1.getHypervisorHostname()).thenReturn("test-hypervisor"); + when(server1.getName()).thenReturn("test-server1-name"); + when(server1.getStatus()).thenReturn(Status.ACTIVE); + when(server1.getLinks()).thenReturn(new ArrayList<>()); + + Server server2 = mock(Server.class); + when(server2.getId()).thenReturn("test-server2-id"); + when(server2.getHypervisorHostname()).thenReturn("test-hypervisor"); + when(server2.getName()).thenReturn("test-server2-name"); + when(server2.getStatus()).thenReturn(Status.ACTIVE); + when(server2.getLinks()).thenReturn(new ArrayList<>()); + + List<Server> servers = Arrays.asList(server1, server2); + + Image image = mock(Image.class); + when(server1.getImage()).thenReturn(image); + when(server2.getImage()).thenReturn(image); + when(image.getId()).thenReturn("test-image-id"); + + Flavor flavor = mock(Flavor.class); + when(server1.getFlavor()).thenReturn(flavor); + when(server2.getFlavor()).thenReturn(flavor); + when(flavor.getId()).thenReturn("test-flavor-id"); + + + // Act + heatbridge.buildAddVserversToAaiAction("test-genericVnf-id", "test-vfModule-id", servers); + + // Assert + ArgumentCaptor<AAIResourceUri> captor = ArgumentCaptor.forClass(AAIResourceUri.class); + verify(transaction, times(2)).create(captor.capture(), any(Vserver.class)); + + List<AAIResourceUri> uris = captor.getAllValues(); + assertEquals(AAIUriFactory.createResourceUri( + AAIObjectType.VSERVER, CLOUD_OWNER, REGION_ID, TENANT_ID, server1.getId()), uris.get(0)); + assertEquals(AAIUriFactory.createResourceUri( + AAIObjectType.VSERVER, CLOUD_OWNER, REGION_ID, TENANT_ID, server2.getId()), uris.get(1)); + + } + + @Test + public void testUpdateImagesToAai() throws HeatBridgeException { + // Arrange + Image image1 = mock(Image.class); + when(image1.getId()).thenReturn("test-image1-id"); + when(image1.getName()).thenReturn("test-image1-name"); + when(image1.getLinks()).thenReturn(new ArrayList<>()); + + Image image2 = mock(Image.class); + when(image2.getId()).thenReturn("test-image2-id"); + when(image2.getName()).thenReturn("test-image2-name"); + when(image2.getLinks()).thenReturn(new ArrayList<>()); + + List<Image> images = Arrays.asList(image1, image2); + + // Act #1 + heatbridge.buildAddImagesToAaiAction(images); + + // Assert #1 + verify(transaction, times(2)).create(any(AAIResourceUri.class), any(org.onap.aai.domain.yang.Image.class)); + + // Act #2 + heatbridge.buildAddImagesToAaiAction(images); + + // Assert #2 + verify(transaction, times(4)).create(any(AAIResourceUri.class), any(org.onap.aai.domain.yang.Image.class)); + } + + @Test + public void testUpdateFlavorsToAai() throws HeatBridgeException { + // Arrange + Flavor flavor1 = mock(Flavor.class); + when(flavor1.getId()).thenReturn("test-flavor1-id"); + when(flavor1.getName()).thenReturn("test-flavor1-name"); + when(flavor1.getLinks()).thenReturn(new ArrayList<>()); + + Flavor flavor2 = mock(Flavor.class); + when(flavor2.getId()).thenReturn("test-flavor2-id"); + when(flavor2.getName()).thenReturn("test-flavor2-name"); + when(flavor2.getLinks()).thenReturn(new ArrayList<>()); + + List<Flavor> flavors = Arrays.asList(flavor1, flavor2); + + // Act #1 + heatbridge.buildAddFlavorsToAaiAction(flavors); + + // Assert #1 + verify(transaction, times(2)).create(any(AAIResourceUri.class), any(org.onap.aai.domain.yang.Flavor.class)); + + // Act #2 + heatbridge.buildAddFlavorsToAaiAction(flavors); + + // Assert #2 + verify(transaction, times(4)).create(any(AAIResourceUri.class), any(org.onap.aai.domain.yang.Flavor.class)); + } + + @Ignore + @Test + public void testUpdateVserverLInterfacesToAai() throws HeatBridgeException { + // Arrange + List<Resource> stackResources = (List<Resource>) extractTestStackResources(); + Port port = mock(Port.class); + when(port.getId()).thenReturn("test-port-id"); + when(port.getName()).thenReturn("test-port-name"); + when(port.getvNicType()).thenReturn(HeatBridgeConstants.OS_SRIOV_PORT_TYPE); + when(port.getMacAddress()).thenReturn("78:4f:43:68:e2:78"); + when(port.getNetworkId()).thenReturn("890a203a-23gg-56jh-df67-731656a8f13a"); + when(port.getDeviceId()).thenReturn("test-device-id"); + when(port.getVifDetails()) + .thenReturn(ImmutableMap.of(HeatBridgeConstants.OS_VLAN_NETWORK_KEY, "2345")); + String pfPciId = "0000:08:00.0"; + when(port.getProfile()).thenReturn(ImmutableMap.of(HeatBridgeConstants.OS_PCI_SLOT_KEY, pfPciId, + HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY, "physical_network_id")); + + Network network = mock(Network.class); + when(network.getId()).thenReturn("test-network-id"); + when(network.getNetworkType()).thenReturn(NetworkType.VLAN); + when(network.getProviderSegID()).thenReturn("2345"); + + when(osClient.getPortById("212a203a-9764-4f42-84ea-731536a8f13a")).thenReturn(port); + when(osClient.getPortById("387e3904-8948-43d1-8635-b6c2042b54da")).thenReturn(port); + when(osClient.getPortById("70a09dfd-f1c5-4bc8-bd8f-dc539b8d662a")).thenReturn(port); + when(osClient.getPortById("12f88b4d-c8a4-4fbd-bcb4-7e36af02430b")).thenReturn(port); + when(osClient.getPortById("c54b9f45-b413-4937-bbe4-3c8a5689cfc9")).thenReturn(port); + when(osClient.getNetworkById(anyString())).thenReturn(network); + + SriovPf sriovPf = new SriovPf(); + sriovPf.setPfPciId(pfPciId); + PInterface pIf = mock(PInterface.class); + when(pIf.getInterfaceName()).thenReturn("test-port-id"); + when(resourcesClient.get(eq(PInterface.class), any(AAIResourceUri.class))).thenReturn(Optional.of(pIf)); + + // Act + heatbridge.buildAddVserverLInterfacesToAaiAction(stackResources, Arrays.asList("1", "2")); + + // Assert + verify(transaction, times(5)).create(any(AAIResourceUri.class), any(LInterface.class)); + verify(osClient, times(5)).getPortById(anyString()); + verify(osClient, times(5)).getNetworkById(anyString()); + } + + private List<? extends Resource> extractTestStackResources() { + List<HeatResource> stackResources = null; + try { + stackResources = MAPPER.readValue(readTestResourceFile("stack-resources.json"), Resources.class) + .getList(); + assertNotNull(stackResources); + assertFalse(stackResources.isEmpty()); + } catch (IOException e) { + Assert.fail("Failed to extract test stack resources."); + } + return stackResources; + } + + private String readTestResourceFile(String filePath) { + String content = null; + String pathname = Objects.requireNonNull(getClass().getClassLoader().getResource(filePath)).getFile(); + File file = new File(pathname); + try { + content = Objects.requireNonNull(FileUtils.readFileToString(file, Charset.defaultCharset())); + } catch (IOException e) { + Assert.fail(String.format("Failed to read test resource file (%s)", filePath)); + } + return content; + } +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/GetResources.json b/adapters/mso-openstack-adapters/src/test/resources/GetResources.json index 22e66d41bb..3366ce4a05 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/GetResources.json +++ b/adapters/mso-openstack-adapters/src/test/resources/GetResources.json @@ -1,6 +1,6 @@ { - "resources": [ - { + "resources": [ + { "links": [ { "href": "https://orchestration.com:8004/v1/99cecb7b19dc4690960761abd0fe2413/stacks/zdyh3brlba05_addon/03840be2-7ce6-4e38-a748-dbd59a798732/resources/vlbagent_eph_aff_id", @@ -22,207 +22,208 @@ "resource_type": "OS::Heat::RandomString", "updated_time": "2019-02-07T22:56:12Z" }, + { + "links": [ + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_trusted_port_0", + "rel": "self" + }, + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_trusted_port_0", + "physical_resource_id": "7ee06d9d-3d18-411c-9d3e-aec930f70413", + "required_by": [ + "ssc_server_1" + ], + "resource_name": "ssc_1_trusted_port_0", + "resource_status": "CREATE_COMPLETE", + "resource_status_reason": "state changed", + "resource_type": "OS::Neutron::Port", + "updated_time": "2019-01-23T19:34:15Z" + }, + { + "links": [ + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_service1_port_0", + "rel": "self" + }, + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_service1_port_0", + "physical_resource_id": "36551a08-592c-4329-ab75-6c594420754c", + "required_by": [ + "ssc_1_subint_service1_port_0_subinterfaces", + "ssc_server_1" + ], + "resource_name": "ssc_1_service1_port_0", + "resource_status": "CREATE_COMPLETE", + "resource_status_reason": "state changed", + "resource_type": "OS::Neutron::Port", + "updated_time": "2019-01-23T19:34:15Z" + }, + { + "links": [ + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_subint_service2_port_0_subinterfaces", + "rel": "self" + }, + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + }, + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst/447a9b41-714e-434b-b1d0-6cce8d9f0f0c", + "rel": "nested" + } + ], + "logical_resource_id": "ssc_1_subint_service2_port_0_subinterfaces", + "physical_resource_id": "447a9b41-714e-434b-b1d0-6cce8d9f0f0c", + "required_by": [], + "resource_name": "ssc_1_subint_service2_port_0_subinterfaces", + "resource_status": "CREATE_COMPLETE", + "resource_status_reason": "state changed", + "resource_type": "OS::Heat::ResourceGroup", + "updated_time": "2019-01-23T19:34:15Z" + }, + { + "links": [ + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_mgmt_port_1", + "rel": "self" + }, + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_mgmt_port_1", + "physical_resource_id": "fdeedf37-c01e-4ab0-bdd6-8d5fc4913943", + "required_by": [ + "ssc_server_1" + ], + "resource_name": "ssc_1_mgmt_port_1", + "resource_status": "CREATE_COMPLETE", + "resource_status_reason": "state changed", + "resource_type": "OS::Neutron::Port", + "updated_time": "2019-01-23T19:34:15Z" + }, + { + "links": [ + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_mgmt_port_0", + "rel": "self" + }, { - "resource_name": "ssc_1_trusted_port_0", - "links": [ - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_trusted_port_0", - "rel": "self" - }, - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", - "rel": "stack" - } - ], - "logical_resource_id": "ssc_1_trusted_port_0", - "resource_status": "CREATE_COMPLETE", - "updated_time": "2019-01-23T19:34:15Z", - "required_by": [ - "ssc_server_1" - ], - "resource_status_reason": "state changed", - "physical_resource_id": "d2f51f82-0ec2-4581-bd1a-d2a82073e52b", - "resource_type": "OS::Neutron::Port" - }, - { - "resource_name": "ssc_1_service1_port_0", - "links": [ - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_service1_port_0", - "rel": "self" - }, - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", - "rel": "stack" - } - ], - "logical_resource_id": "ssc_1_service1_port_0", - "resource_status": "CREATE_COMPLETE", - "updated_time": "2019-01-23T19:34:15Z", - "required_by": [ - "ssc_1_subint_service1_port_0_subinterfaces", - "ssc_server_1" - ], - "resource_status_reason": "state changed", - "physical_resource_id": "27391d94-33af-474a-927d-d409249e8fd3", - "resource_type": "OS::Neutron::Port" - }, - { - "resource_name": "ssc_1_subint_service2_port_0_subinterfaces", - "links": [ - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_subint_service2_port_0_subinterfaces", - "rel": "self" - }, - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", - "rel": "stack" - }, - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst/447a9b41-714e-434b-b1d0-6cce8d9f0f0c", - "rel": "nested" - } - ], - "logical_resource_id": "ssc_1_subint_service2_port_0_subinterfaces", - "resource_status": "CREATE_COMPLETE", - "updated_time": "2019-01-23T19:34:15Z", - "required_by": [], - "resource_status_reason": "state changed", - "physical_resource_id": "447a9b41-714e-434b-b1d0-6cce8d9f0f0c", - "resource_type": "OS::Heat::ResourceGroup" - }, - { - "resource_name": "ssc_1_mgmt_port_1", - "links": [ - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_mgmt_port_1", - "rel": "self" - }, - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", - "rel": "stack" - } - ], - "logical_resource_id": "ssc_1_mgmt_port_1", - "resource_status": "CREATE_COMPLETE", - "updated_time": "2019-01-23T19:34:15Z", - "required_by": [ - "ssc_server_1" - ], - "resource_status_reason": "state changed", - "physical_resource_id": "07f5b14c-147a-4d14-8c94-a9e94dbc097b", - "resource_type": "OS::Neutron::Port" - }, - { - "resource_name": "ssc_1_mgmt_port_0", - "links": [ - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_mgmt_port_0", - "rel": "self" - }, - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", - "rel": "stack" - } - ], - "logical_resource_id": "ssc_1_mgmt_port_0", - "resource_status": "CREATE_COMPLETE", - "updated_time": "2019-01-23T19:34:15Z", - "required_by": [ - "ssc_server_1" - ], - "resource_status_reason": "state changed", - "physical_resource_id": "8d93f63e-e972-48c7-ad98-b2122da47315", - "resource_type": "OS::Neutron::Port" - }, - { - "resource_name": "ssc_1_service2_port_0", - "links": [ - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_service2_port_0", - "rel": "self" - }, - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", - "rel": "stack" - } - ], - "logical_resource_id": "ssc_1_service2_port_0", - "resource_status": "CREATE_COMPLETE", - "updated_time": "2019-01-23T19:34:15Z", - "required_by": [ - "ssc_1_subint_service2_port_0_subinterfaces", - "ssc_server_1" - ], - "resource_status_reason": "state changed", - "physical_resource_id": "0594a2f2-7ea4-42eb-abc2-48ea49677fca", - "resource_type": "OS::Neutron::Port" - }, - { - "resource_name": "ssc_1_int_ha_port_0", - "links": [ - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_int_ha_port_0", - "rel": "self" - }, - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", - "rel": "stack" - } - ], - "logical_resource_id": "ssc_1_int_ha_port_0", - "resource_status": "CREATE_COMPLETE", - "updated_time": "2019-01-23T19:34:15Z", - "required_by": [ - "ssc_server_1" - ], - "resource_status_reason": "state changed", - "physical_resource_id": "00bb8407-650e-48b5-b919-33b88d6f8fe3", - "resource_type": "OS::Neutron::Port" - }, - { - "resource_name": "ssc_server_1", - "links": [ - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_server_1", - "rel": "self" - }, - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", - "rel": "stack" - } - ], - "logical_resource_id": "ssc_server_1", - "resource_status": "CREATE_COMPLETE", - "updated_time": "2019-01-23T19:34:15Z", - "required_by": [], - "resource_status_reason": "state changed", - "physical_resource_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", - "resource_type": "OS::Nova::Server" - }, - { - "resource_name": "ssc_1_subint_service1_port_0_subinterfaces", - "links": [ - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_subint_service1_port_0_subinterfaces", - "rel": "self" - }, - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", - "rel": "stack" - }, - { - "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672", - "rel": "nested" - } - ], - "logical_resource_id": "ssc_1_subint_service1_port_0_subinterfaces", - "resource_status": "CREATE_COMPLETE", - "updated_time": "2019-01-23T19:34:15Z", - "required_by": [], - "resource_status_reason": "state changed", - "physical_resource_id": "31d0647a-6043-49a4-81b6-ccab29380672", - "resource_type": "OS::Heat::ResourceGroup" + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_mgmt_port_0", + "physical_resource_id": "8d93f63e-e972-48c7-ad98-b2122da47315", + "required_by": [ + "ssc_server_1" + ], + "resource_name": "ssc_1_mgmt_port_0", + "resource_status": "CREATE_COMPLETE", + "resource_status_reason": "state changed", + "resource_type": "OS::Neutron::Port", + "updated_time": "2019-01-23T19:34:15Z" + }, + { + "links": [ + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_service2_port_0", + "rel": "self" + }, + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" } - ] + ], + "logical_resource_id": "ssc_1_service2_port_0", + "physical_resource_id": "0594a2f2-7ea4-42eb-abc2-48ea49677fca", + "required_by": [ + "ssc_1_subint_service2_port_0_subinterfaces", + "ssc_server_1" + ], + "resource_name": "ssc_1_service2_port_0", + "resource_status": "CREATE_COMPLETE", + "resource_status_reason": "state changed", + "resource_type": "OS::Neutron::Port", + "updated_time": "2019-01-23T19:34:15Z" + }, + { + "links": [ + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_int_ha_port_0", + "rel": "self" + }, + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_1_int_ha_port_0", + "physical_resource_id": "00bb8407-650e-48b5-b919-33b88d6f8fe3", + "required_by": [ + "ssc_server_1" + ], + "resource_name": "ssc_1_int_ha_port_0", + "resource_status": "CREATE_COMPLETE", + "resource_status_reason": "state changed", + "resource_type": "OS::Neutron::Port", + "updated_time": "2019-01-23T19:34:15Z" + }, + { + "links": [ + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_server_1", + "rel": "self" + }, + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + } + ], + "logical_resource_id": "ssc_server_1", + "physical_resource_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "required_by": [], + "resource_name": "ssc_server_1", + "resource_status": "CREATE_COMPLETE", + "resource_status_reason": "state changed", + "resource_type": "OS::Nova::Server", + "updated_time": "2019-01-23T19:34:15Z" + }, + { + "links": [ + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34/resources/ssc_1_subint_service1_port_0_subinterfaces", + "rel": "self" + }, + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001/75e046b1-cf7d-4590-91e7-a6079f83fd34", + "rel": "stack" + }, + { + "href": "https://orchestration.com:8004/v1/ea2d13cc98b44d60a6f94bdcb2738f9e/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672", + "rel": "nested" + } + ], + "logical_resource_id": "ssc_1_subint_service1_port_0_subinterfaces", + "physical_resource_id": "31d0647a-6043-49a4-81b6-ccab29380672", + "required_by": [], + "resource_name": "ssc_1_subint_service1_port_0_subinterfaces", + "resource_status": "CREATE_COMPLETE", + "resource_status_reason": "state changed", + "resource_type": "OS::Heat::ResourceGroup", + "updated_time": "2019-01-23T19:34:15Z" + } + ] } + diff --git a/adapters/mso-openstack-adapters/src/test/resources/NeutronPort1.json b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort1.json new file mode 100644 index 0000000000..e4bd83c21d --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort1.json @@ -0,0 +1,41 @@ +{ + "port": { + "admin_state_up": true, + "allowed_address_pairs": [ + { + "ip_address": "192.168.1.1", + "mac_address": "" + } + ], + "binding:host_id": "cool.host.com", + "binding:vif_details": { + "vhostuser_mode": "client", + "vhostuser_socket": "/var/run/asdfasdf/asdfasfd-3d", + "vhostuser_vrouter_plug": true + }, + "binding:vif_type": "vhostuser", + "binding:vnic_type": "normal", + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "device_owner": "compute:ddd-daa-ddd", + "fixed_ips": [ + { + "ip_address": "2001:1890:1001:264d::2d:2b", + "subnet_id": "1327b4d5-e0f7-4e95-b019-60caaac751d1" + }, + { + "ip_address": "192.168.1.1", + "subnet_id": "05f0a2e9-e9d9-4cc0-8635-b82d3de2d700" + } + ], + "id": "7ee06d9d-3d18-411c-9d3e-aec930f70413", + "mac_address": "02:7e:e0:6d:9d:3d", + "name": "ibcx0026v_ibcx0026vm003_untrusted_port", + "network_id": "cee81fae-28b9-40a0-985f-181796ae0df6", + "port_security_enabled": true, + "security_groups": [ + "ee45e4fd-b00c-4396-85ee-18d82bd03ef6" + ], + "status": "ACTIVE", + "tenant_id": "a9442388264e4a198e68484e676404e9" + } +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/NeutronPort2.json b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort2.json new file mode 100644 index 0000000000..376a526133 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort2.json @@ -0,0 +1,41 @@ +{ + "port": { + "admin_state_up": true, + "allowed_address_pairs": [ + { + "ip_address": "192.168.1.1", + "mac_address": "" + } + ], + "binding:host_id": "cool.host.com", + "binding:vif_details": { + "vhostuser_mode": "client", + "vhostuser_socket": "/var/run/asdfasdf/asdfasfd-3d", + "vhostuser_vrouter_plug": true + }, + "binding:vif_type": "vhostuser", + "binding:vnic_type": "normal", + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "device_owner": "compute:ddd-daa-ddd", + "fixed_ips": [ + { + "ip_address": "2001:1890:1001:264d::2d:2b", + "subnet_id": "1327b4d5-e0f7-4e95-b019-60caaac751d1" + }, + { + "ip_address": "192.168.1.1", + "subnet_id": "05f0a2e9-e9d9-4cc0-8635-b82d3de2d700" + } + ], + "id": "27391d94-33af-474a-927d-d409249e8fd3", + "mac_address": "02:7e:e0:6d:9d:3d", + "name": "ibcx0026v_ibcx0026vm003_untrusted_port", + "network_id": "cee81fae-28b9-40a0-985f-181796ae0df6", + "port_security_enabled": true, + "security_groups": [ + "ee45e4fd-b00c-4396-85ee-18d82bd03ef6" + ], + "status": "ACTIVE", + "tenant_id": "a9442388264e4a198e68484e676404e9" + } +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/NeutronPort3.json b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort3.json new file mode 100644 index 0000000000..f0549216be --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort3.json @@ -0,0 +1,41 @@ +{ + "port": { + "admin_state_up": true, + "allowed_address_pairs": [ + { + "ip_address": "192.168.1.1", + "mac_address": "" + } + ], + "binding:host_id": "cool.host.com", + "binding:vif_details": { + "vhostuser_mode": "client", + "vhostuser_socket": "/var/run/asdfasdf/asdfasfd-3d", + "vhostuser_vrouter_plug": true + }, + "binding:vif_type": "vhostuser", + "binding:vnic_type": "normal", + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "device_owner": "compute:ddd-daa-ddd", + "fixed_ips": [ + { + "ip_address": "2001:1890:1001:264d::2d:2b", + "subnet_id": "1327b4d5-e0f7-4e95-b019-60caaac751d1" + }, + { + "ip_address": "192.168.1.1", + "subnet_id": "05f0a2e9-e9d9-4cc0-8635-b82d3de2d700" + } + ], + "id": "fdeedf37-c01e-4ab0-bdd6-8d5fc4913943", + "mac_address": "02:7e:e0:6d:9d:3d", + "name": "ibcx0026v_ibcx0026vm003_untrusted_port", + "network_id": "cee81fae-28b9-40a0-985f-181796ae0df6", + "port_security_enabled": true, + "security_groups": [ + "ee45e4fd-b00c-4396-85ee-18d82bd03ef6" + ], + "status": "ACTIVE", + "tenant_id": "a9442388264e4a198e68484e676404e9" + } +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/NeutronPort4.json b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort4.json new file mode 100644 index 0000000000..fa10b0c864 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort4.json @@ -0,0 +1,41 @@ +{ + "port": { + "admin_state_up": true, + "allowed_address_pairs": [ + { + "ip_address": "192.168.1.1", + "mac_address": "" + } + ], + "binding:host_id": "cool.host.com", + "binding:vif_details": { + "vhostuser_mode": "client", + "vhostuser_socket": "/var/run/asdfasdf/asdfasfd-3d", + "vhostuser_vrouter_plug": true + }, + "binding:vif_type": "vhostuser", + "binding:vnic_type": "normal", + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "device_owner": "compute:ddd-daa-ddd", + "fixed_ips": [ + { + "ip_address": "2001:1890:1001:264d::2d:2b", + "subnet_id": "1327b4d5-e0f7-4e95-b019-60caaac751d1" + }, + { + "ip_address": "192.168.1.1", + "subnet_id": "05f0a2e9-e9d9-4cc0-8635-b82d3de2d700" + } + ], + "id": "8d93f63e-e972-48c7-ad98-b2122da47315", + "mac_address": "02:7e:e0:6d:9d:3d", + "name": "ibcx0026v_ibcx0026vm003_untrusted_port", + "network_id": "cee81fae-28b9-40a0-985f-181796ae0df6", + "port_security_enabled": true, + "security_groups": [ + "ee45e4fd-b00c-4396-85ee-18d82bd03ef6" + ], + "status": "ACTIVE", + "tenant_id": "a9442388264e4a198e68484e676404e9" + } +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/NeutronPort5.json b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort5.json new file mode 100644 index 0000000000..54a9ee8404 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort5.json @@ -0,0 +1,41 @@ +{ + "port": { + "admin_state_up": true, + "allowed_address_pairs": [ + { + "ip_address": "192.168.1.1", + "mac_address": "" + } + ], + "binding:host_id": "cool.host.com", + "binding:vif_details": { + "vhostuser_mode": "client", + "vhostuser_socket": "/var/run/asdfasdf/asdfasfd-3d", + "vhostuser_vrouter_plug": true + }, + "binding:vif_type": "vhostuser", + "binding:vnic_type": "normal", + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "device_owner": "compute:ddd-daa-ddd", + "fixed_ips": [ + { + "ip_address": "2001:1890:1001:264d::2d:2b", + "subnet_id": "1327b4d5-e0f7-4e95-b019-60caaac751d1" + }, + { + "ip_address": "192.168.1.1", + "subnet_id": "05f0a2e9-e9d9-4cc0-8635-b82d3de2d700" + } + ], + "id": "0594a2f2-7ea4-42eb-abc2-48ea49677fca", + "mac_address": "02:7e:e0:6d:9d:3d", + "name": "ibcx0026v_ibcx0026vm003_untrusted_port", + "network_id": "cee81fae-28b9-40a0-985f-181796ae0df6", + "port_security_enabled": true, + "security_groups": [ + "ee45e4fd-b00c-4396-85ee-18d82bd03ef6" + ], + "status": "ACTIVE", + "tenant_id": "a9442388264e4a198e68484e676404e9" + } +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/NeutronPort6.json b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort6.json new file mode 100644 index 0000000000..c47dfd755b --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/resources/NeutronPort6.json @@ -0,0 +1,41 @@ +{ + "port": { + "admin_state_up": true, + "allowed_address_pairs": [ + { + "ip_address": "192.168.1.1", + "mac_address": "" + } + ], + "binding:host_id": "cool.host.com", + "binding:vif_details": { + "vhostuser_mode": "client", + "vhostuser_socket": "/var/run/asdfasdf/asdfasfd-3d", + "vhostuser_vrouter_plug": true + }, + "binding:vif_type": "vhostuser", + "binding:vnic_type": "normal", + "device_id": "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "device_owner": "compute:ddd-daa-ddd", + "fixed_ips": [ + { + "ip_address": "2001:1890:1001:264d::2d:2b", + "subnet_id": "1327b4d5-e0f7-4e95-b019-60caaac751d1" + }, + { + "ip_address": "192.168.1.1", + "subnet_id": "05f0a2e9-e9d9-4cc0-8635-b82d3de2d700" + } + ], + "id": "00bb8407-650e-48b5-b919-33b88d6f8fe3", + "mac_address": "02:7e:e0:6d:9d:3d", + "name": "ibcx0026v_ibcx0026vm003_untrusted_port", + "network_id": "cee81fae-28b9-40a0-985f-181796ae0df6", + "port_security_enabled": true, + "security_groups": [ + "ee45e4fd-b00c-4396-85ee-18d82bd03ef6" + ], + "status": "ACTIVE", + "tenant_id": "a9442388264e4a198e68484e676404e9" + } +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/stack-resources.json b/adapters/mso-openstack-adapters/src/test/resources/stack-resources.json new file mode 100644 index 0000000000..6b63895a33 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/resources/stack-resources.json @@ -0,0 +1,441 @@ +{ + "resources": [ + { + "resource_name": "ge_000", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule/d1431cdc-9b29-44fc-98d0-9b3dc1ac246d/resources/ge_000", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule/d1431cdc-9b29-44fc-98d0-9b3dc1ac246d", + "rel": "stack" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-ge_000-t66dxpwq6nb5/deee54a3-08ac-477b-9c09-c798edb40be1", + "rel": "nested" + } + ], + "logical_resource_id": "ge_000", + "resource_status_reason": "state changed", + "updated_time": "2018-04-09T21:09:52Z", + "required_by": [ + "vfw_instance" + ], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "deee54a3-08ac-477b-9c09-c798edb40be1", + "resource_type": "port.yaml" + }, + { + "resource_name": "vfw_instance", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule/d1431cdc-9b29-44fc-98d0-9b3dc1ac246d/resources/vfw_instance", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule/d1431cdc-9b29-44fc-98d0-9b3dc1ac246d", + "rel": "stack" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b", + "rel": "nested" + } + ], + "logical_resource_id": "vfw_instance", + "resource_status_reason": "state changed", + "updated_time": "2018-04-09T21:09:52Z", + "required_by": [], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "54f93b9e-5138-4f3f-bfe0-ee06e1f0877b", + "resource_type": "vfw.yaml" + }, + { + "resource_name": "port", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-ge_000-t66dxpwq6nb5/deee54a3-08ac-477b-9c09-c798edb40be1/resources/port", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-ge_000-t66dxpwq6nb5/deee54a3-08ac-477b-9c09-c798edb40be1", + "rel": "stack" + } + ], + "logical_resource_id": "port", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2018-04-09T21:09:52Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "212a203a-9764-4f42-84ea-731536a8f13a", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "pfe0", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b/resources/pfe0", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b", + "rel": "stack" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-pfe0-kvqmgn7jmiti/1325e04b-e836-4a13-bb2e-f34923d97ad7", + "rel": "nested" + } + ], + "logical_resource_id": "pfe0", + "resource_status_reason": "state changed", + "updated_time": "2018-04-09T21:09:54Z", + "required_by": [ + "re0" + ], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "1325e04b-e836-4a13-bb2e-f34923d97ad7", + "resource_type": "fpc.yaml" + }, + { + "resource_name": "fpc_internal_port", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b/resources/fpc_internal_port", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b", + "rel": "stack" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-fpc_internal_port-gbnyc4w7mb5b/4e920f39-9784-417e-9331-d75e2e37cc51", + "rel": "nested" + } + ], + "logical_resource_id": "fpc_internal_port", + "resource_status_reason": "state changed", + "updated_time": "2018-04-09T21:09:54Z", + "required_by": [ + "pfe0" + ], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "4e920f39-9784-417e-9331-d75e2e37cc51", + "resource_type": "re_pfe_port.yaml" + }, + { + "resource_name": "re-fpc-affinity-grp", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b/resources/re-fpc-affinity-grp", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b", + "rel": "stack" + } + ], + "logical_resource_id": "re-fpc-affinity-grp", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2018-04-09T21:09:54Z", + "required_by": [ + "pfe0", + "re0" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "3aa37238-f8ff-4c96-b56a-8903bae28a60", + "resource_type": "OS::Nova::ServerGroup" + }, + { + "resource_name": "re0", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b/resources/re0", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b", + "rel": "stack" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re0-73oifso3xntc/0915e27e-428d-4d2c-a67b-abbce18081b2", + "rel": "nested" + } + ], + "logical_resource_id": "re0", + "resource_status_reason": "state changed", + "updated_time": "2018-04-09T21:09:54Z", + "required_by": [], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "0915e27e-428d-4d2c-a67b-abbce18081b2", + "resource_type": "re.yaml" + }, + { + "resource_name": "re_external_port", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b/resources/re_external_port", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b", + "rel": "stack" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re_external_port-3okiee3zocr7/f58c65e3-a72e-4b2d-a295-cb40324d6b4c", + "rel": "nested" + } + ], + "logical_resource_id": "re_external_port", + "resource_status_reason": "state changed", + "updated_time": "2018-04-09T21:09:54Z", + "required_by": [ + "re0" + ], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "f58c65e3-a72e-4b2d-a295-cb40324d6b4c", + "resource_type": "port.yaml" + }, + { + "resource_name": "fpc_external_port", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b/resources/fpc_external_port", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b", + "rel": "stack" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-fpc_external_port-5vumcqp7hkbn/979e47c9-c15a-428e-ad73-af922029ee37", + "rel": "nested" + } + ], + "logical_resource_id": "fpc_external_port", + "resource_status_reason": "state changed", + "updated_time": "2018-04-09T21:09:54Z", + "required_by": [ + "pfe0", + "re0" + ], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "979e47c9-c15a-428e-ad73-af922029ee37", + "resource_type": "port.yaml" + }, + { + "resource_name": "re_internal_port", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b/resources/re_internal_port", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b", + "rel": "stack" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re_internal_port-u4txbvemndci/0aebfd9d-ad97-43b1-a67b-b2b5340738d2", + "rel": "nested" + } + ], + "logical_resource_id": "re_internal_port", + "resource_status_reason": "state changed", + "updated_time": "2018-04-09T21:09:54Z", + "required_by": [ + "re0" + ], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "0aebfd9d-ad97-43b1-a67b-b2b5340738d2", + "resource_type": "re_pfe_port.yaml" + }, + { + "resource_name": "re_pfe_network", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b/resources/re_pfe_network", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam/54f93b9e-5138-4f3f-bfe0-ee06e1f0877b", + "rel": "stack" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re_pfe_network-2wmjvgzrhtvs/290fc2fd-cd1d-47d0-90eb-2ece7c009b29", + "rel": "nested" + } + ], + "logical_resource_id": "re_pfe_network", + "resource_status_reason": "state changed", + "updated_time": "2018-04-09T21:09:54Z", + "required_by": [ + "fpc_internal_port", + "re_internal_port" + ], + "resource_status": "CREATE_COMPLETE", + "physical_resource_id": "290fc2fd-cd1d-47d0-90eb-2ece7c009b29", + "resource_type": "bridge_int.yaml" + }, + { + "resource_name": "fpc", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-pfe0-kvqmgn7jmiti/1325e04b-e836-4a13-bb2e-f34923d97ad7/resources/fpc", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-pfe0-kvqmgn7jmiti/1325e04b-e836-4a13-bb2e-f34923d97ad7", + "rel": "stack" + } + ], + "logical_resource_id": "fpc", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2018-04-09T21:09:58Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "43c2159b-2c04-46ac-bda5-594110cae2d3", + "resource_type": "OS::Nova::Server" + }, + { + "resource_name": "port", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-fpc_internal_port-gbnyc4w7mb5b/4e920f39-9784-417e-9331-d75e2e37cc51/resources/port", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-fpc_internal_port-gbnyc4w7mb5b/4e920f39-9784-417e-9331-d75e2e37cc51", + "rel": "stack" + } + ], + "logical_resource_id": "port", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2018-04-09T21:09:56Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "387e3904-8948-43d1-8635-b6c2042b54da", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "re", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re0-73oifso3xntc/0915e27e-428d-4d2c-a67b-abbce18081b2/resources/re", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re0-73oifso3xntc/0915e27e-428d-4d2c-a67b-abbce18081b2", + "rel": "stack" + } + ], + "logical_resource_id": "re", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2018-04-09T21:10:36Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "7cff109a-b2b7-4933-97b4-ec44a8365568", + "resource_type": "OS::Nova::Server" + }, + { + "resource_name": "port", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re_external_port-3okiee3zocr7/f58c65e3-a72e-4b2d-a295-cb40324d6b4c/resources/port", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re_external_port-3okiee3zocr7/f58c65e3-a72e-4b2d-a295-cb40324d6b4c", + "rel": "stack" + } + ], + "logical_resource_id": "port", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2018-04-09T21:09:55Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "70a09dfd-f1c5-4bc8-bd8f-dc539b8d662a", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "port", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-fpc_external_port-5vumcqp7hkbn/979e47c9-c15a-428e-ad73-af922029ee37/resources/port", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-fpc_external_port-5vumcqp7hkbn/979e47c9-c15a-428e-ad73-af922029ee37", + "rel": "stack" + } + ], + "logical_resource_id": "port", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2018-04-09T21:09:55Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "12f88b4d-c8a4-4fbd-bcb4-7e36af02430b", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "port", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re_internal_port-u4txbvemndci/0aebfd9d-ad97-43b1-a67b-b2b5340738d2/resources/port", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re_internal_port-u4txbvemndci/0aebfd9d-ad97-43b1-a67b-b2b5340738d2", + "rel": "stack" + } + ], + "logical_resource_id": "port", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2018-04-09T21:09:56Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "c54b9f45-b413-4937-bbe4-3c8a5689cfc9", + "resource_type": "OS::Neutron::Port" + }, + { + "resource_name": "bridge_network_subnet", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re_pfe_network-2wmjvgzrhtvs/290fc2fd-cd1d-47d0-90eb-2ece7c009b29/resources/bridge_network_subnet", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re_pfe_network-2wmjvgzrhtvs/290fc2fd-cd1d-47d0-90eb-2ece7c009b29", + "rel": "stack" + } + ], + "logical_resource_id": "bridge_network_subnet", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2018-04-09T21:09:55Z", + "required_by": [], + "resource_status_reason": "state changed", + "physical_resource_id": "5ffd8c02-6913-4b67-adba-74e78c2bbe40", + "resource_type": "OS::Neutron::Subnet" + }, + { + "resource_name": "bridge_network", + "links": [ + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re_pfe_network-2wmjvgzrhtvs/290fc2fd-cd1d-47d0-90eb-2ece7c009b29/resources/bridge_network", + "rel": "self" + }, + { + "href": "http://10.10.10.10:8004/v1/7320ec4a5b9d4589ba7c4412ccfd290f/stacks/ClosedLoop_vFW_VfModule-vfw_instance-tw3i5ile2nam-re_pfe_network-2wmjvgzrhtvs/290fc2fd-cd1d-47d0-90eb-2ece7c009b29", + "rel": "stack" + } + ], + "logical_resource_id": "bridge_network", + "resource_status": "CREATE_COMPLETE", + "updated_time": "2018-04-09T21:09:55Z", + "required_by": [ + "bridge_network_subnet" + ], + "resource_status_reason": "state changed", + "physical_resource_id": "5ad95036-8daf-4379-a59c-865f35976cd4", + "resource_type": "OS::Neutron::Net" + } + ] +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml index 56d425745f..7e866f9008 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-adapter-api/pom.xml @@ -44,6 +44,7 @@ <sourceFolder>src/gen/java/main</sourceFolder> <withXml>true</withXml> <useRxJava2>true</useRxJava2> + <serializableModel>true</serializableModel> </configOptions> </configuration> </execution> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml index 4554835b33..2e1fc97336 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/pom.xml @@ -76,5 +76,10 @@ <artifactId>mso-adapters-rest-interface</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.onap.so.adapters</groupId> + <artifactId>mso-vnfm-adapter-api</artifactId> + <version>${project.version}</version> + </dependency> </dependencies> </project> diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterController.java index 4dabec3e9b..b14ead0c4f 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterController.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterController.java @@ -21,14 +21,101 @@ package org.onap.so.adapters.vnfmadapter.rest; import static org.onap.so.adapters.vnfmadapter.Constants.BASE_URL; +import java.util.UUID; +import javax.validation.Valid; +import javax.ws.rs.core.MediaType; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.vnfmadapter.v1.model.CreateVnfRequest; +import org.onap.vnfmadapter.v1.model.CreateVnfResponse; +import org.onap.vnfmadapter.v1.model.DeleteVnfResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; +import io.swagger.annotations.ApiParam; /** * Controller for handling requests to the VNFM (Virtual Network Function Manager) adapter REST API. */ @Controller -@RequestMapping(value = BASE_URL) +@RequestMapping(value = BASE_URL, produces = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}, + consumes = {MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public class VnfmAdapterController { + private static final Logger logger = LoggerFactory.getLogger(VnfmAdapterController.class); + + @PostMapping(value = "/vnfs/{vnfId}") + public ResponseEntity<CreateVnfResponse> vnfCreate( + @ApiParam(value = "The identifier of the VNF. This must be the vnf-id of an existing generic-vnf in AAI.", + required = true) @PathVariable("vnfId") final String vnfId, + @ApiParam(value = "VNF creation parameters", + required = true) @Valid @RequestBody final CreateVnfRequest createVnfRequest, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies a single top level invocation of ONAP", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.REQUEST_ID, + required = false) final String requestId, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies the client application user agent or user invoking the API", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.PARTNER_NAME, + required = false) final String partnerName, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies a single invocation of a single component", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.INVOCATION_ID, + required = false) final String invocationId) { + + setLoggingMDCs(requestId, partnerName, invocationId); + + logger.info("REST request vnfCreate with body: {}", createVnfRequest); + + final CreateVnfResponse response = new CreateVnfResponse(); + response.setJobId(UUID.randomUUID().toString()); + clearLoggingMDCs(); + return new ResponseEntity<>(response, HttpStatus.ACCEPTED); + } + + @DeleteMapping(value = "/vnfs/{vnfId}") + public ResponseEntity<DeleteVnfResponse> vnfDelete( + @ApiParam(value = "The identifier of the VNF. This must be the vnf-id of an existing generic-vnf in AAI.", + required = true) @PathVariable("vnfId") final String vnfId, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies a single top level invocation of ONAP", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.REQUEST_ID, + required = false) final String requestId, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies the client application user agent or user invoking the API", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.PARTNER_NAME, + required = false) final String partnerName, + @ApiParam( + value = "Used to track REST requests for logging purposes. Identifies a single invocation of a single component", + required = false) @RequestHeader(value = ONAPLogConstants.Headers.INVOCATION_ID, + required = false) final String invocationId) { + + setLoggingMDCs(requestId, partnerName, invocationId); + + logger.info("REST request vnfDelete for VNF: {}", vnfId); + + final DeleteVnfResponse response = new DeleteVnfResponse(); + response.setJobId(UUID.randomUUID().toString()); + clearLoggingMDCs(); + return new ResponseEntity<>(response, HttpStatus.ACCEPTED); + } + + private void setLoggingMDCs(final String requestId, final String partnerName, final String invocationId) { + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName); + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); + } + + private void clearLoggingMDCs() { + MDC.clear(); + } + } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java new file mode 100644 index 0000000000..071a330e8b --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.vnfmadapter.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import java.net.URI; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.so.adapters.vnfmadapter.VnfmAdapterApplication; +import org.onap.vnfmadapter.v1.model.CreateVnfRequest; +import org.onap.vnfmadapter.v1.model.CreateVnfResponse; +import org.onap.vnfmadapter.v1.model.DeleteVnfResponse; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = VnfmAdapterApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +public class VnfmAdapterControllerTest { + + @LocalServerPort + private int port; + + private final TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + + @Test + public void createVnf_ValidRequest_Returns202AndJobId() throws Exception { + final CreateVnfRequest createVnfRequest = new CreateVnfRequest(); + final RequestEntity<CreateVnfRequest> request = + RequestEntity.post(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myVnfId")) + .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON) + .header("X-ONAP-RequestId", "myRequestId").header("X-ONAP-InvocationID", "myInvocationId") + .body(createVnfRequest); + final ResponseEntity<CreateVnfResponse> response = restTemplate.exchange(request, CreateVnfResponse.class); + assertEquals(202, response.getStatusCode().value()); + assertNotNull(response.getBody().getJobId()); + } + + @Test + public void createVnf_UnauthorizedUser_Returns401() throws Exception { + final TestRestTemplate restTemplateWrongPassword = new TestRestTemplate("test", "wrongPassword"); + final CreateVnfRequest createVnfRequest = new CreateVnfRequest(); + final RequestEntity<CreateVnfRequest> request = + RequestEntity.post(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myVnfId")) + .accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON) + .header("X-ONAP-RequestId", "myRequestId").header("X-ONAP-InvocationID", "myInvocationId") + .body(createVnfRequest); + final ResponseEntity<CreateVnfResponse> response = + restTemplateWrongPassword.exchange(request, CreateVnfResponse.class); + assertEquals(401, response.getStatusCode().value()); + } + + @Test + public void deleteVnf_ValidRequest_Returns202AndJobId() throws Exception { + final RequestEntity<Void> request = RequestEntity + .delete(new URI("http://localhost:" + port + "/so/vnfm-adapter/v1/vnfs/myVnfId")) + .accept(MediaType.APPLICATION_JSON).header("X-ONAP-RequestId", "myRequestId") + .header("X-ONAP-InvocationID", "myInvocationId").header("Content-Type", "application/json").build(); + final ResponseEntity<DeleteVnfResponse> response = restTemplate.exchange(request, DeleteVnfResponse.class); + assertEquals(202, response.getStatusCode().value()); + assertNotNull(response.getBody().getJobId()); + } + +} diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java index ef0b4921e4..5af427a81a 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java @@ -1487,8 +1487,6 @@ public class ToscaResourceInstaller { List<NodeTemplate> cvfcList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(vfTemplate, SdcTypes.CVFC); for(NodeTemplate cvfcTemplate : cvfcList) { - - CvnfcCustomization existingCvnfcCustomization = findExistingCvfc(existingCvnfcSet, cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); if(vfModuleMemberName != null && vfModuleMemberName.equalsIgnoreCase(cvfcTemplate.getName())){ @@ -1529,13 +1527,8 @@ public class ToscaResourceInstaller { // This check is needed incase the VFC subcategory is something other than Abstract. In that case we want to skip adding that record to our DB. if(vnfcCustomization.getModelCustomizationUUID() != null){ - CvnfcCustomization cvnfcCustomization = null; - - if(existingCvnfcCustomization != null){ - cvnfcCustomization = existingCvnfcCustomization; - } - else{ - + CvnfcCustomization cvnfcCustomization = new CvnfcCustomization(); + cvnfcCustomization = new CvnfcCustomization(); cvnfcCustomization.setModelCustomizationUUID(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); cvnfcCustomization.setModelInstanceName(cvfcTemplate.getName()); @@ -1562,7 +1555,6 @@ public class ToscaResourceInstaller { cvnfcCustomizations.add(cvnfcCustomization); existingCvnfcSet.add(cvnfcCustomization); - } //***************************************************************************************************************************************** //* Extract Fabric Configuration @@ -1586,18 +1578,15 @@ public class ToscaResourceInstaller { VnfVfmoduleCvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization = createVfCnvfConfigCustomization(fabricTemplate, toscaResourceStructure, vnfResource, vfModuleCustomization, cvnfcCustomization, fabricConfig, vfTemplate, vfModuleMemberName); - vnfVfmoduleCvnfcConfigurationCustomizations.add(vnfVfmoduleCvnfcConfigurationCustomization); } - + cvnfcCustomization.setVnfVfmoduleCvnfcConfigurationCustomization(vnfVfmoduleCvnfcConfigurationCustomizations); } } } - } - vfModuleCustomization.setCvnfcCustomization(cvnfcCustomizations); vfModuleCustomization.setVnfVfmoduleCvnfcConfigurationCustomization(vnfVfmoduleCvnfcConfigurationCustomizations); @@ -1609,7 +1598,7 @@ public class ToscaResourceInstaller { ConfigurationResource configResource, NodeTemplate vfTemplate, String vfModuleMemberName) { Metadata fabricMetadata = fabricTemplate.getMetaData(); - + VnfVfmoduleCvnfcConfigurationCustomization vfModuleToCvnfc = new VnfVfmoduleCvnfcConfigurationCustomization(); vfModuleToCvnfc.setConfigurationResource(configResource); diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java b/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java index de28ca2446..0d75c56c58 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/util/ASDCNotificationLogging.java @@ -323,9 +323,67 @@ public class ASDCNotificationLogging { buffer.append(System.lineSeparator()); } + buffer.append(System.lineSeparator()); + buffer.append("VF Module Customization Properties:"); + buffer.append(System.lineSeparator()); + buffer.append("Model Customization UUID:"); + buffer.append(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULECUSTOMIZATIONUUID))); + buffer.append(System.lineSeparator()); } + List<NodeTemplate> vfConfigList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(vfNodeTemplate, SdcTypes.CONFIGURATION); + + if(vfConfigList != null){ + for (NodeTemplate configNodeTemplate : vfConfigList) { + + buffer.append(System.lineSeparator()); + buffer.append(System.lineSeparator()); + buffer.append("Fabric Configuration Properties:"); + buffer.append(System.lineSeparator()); + + buffer.append("Model Name:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + buffer.append(System.lineSeparator()); + buffer.append("Model UUID:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + buffer.append(System.lineSeparator()); + buffer.append("Description:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + buffer.append(System.lineSeparator()); + buffer.append("Version:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + buffer.append(System.lineSeparator()); + buffer.append("InvariantUuid:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + buffer.append(System.lineSeparator()); + buffer.append("Tosca Node Type:"); + buffer.append(configNodeTemplate.getType()); + + buffer.append(System.lineSeparator()); + buffer.append(System.lineSeparator()); + buffer.append("Fabric Configuration Customization Properties:"); + buffer.append(System.lineSeparator()); + + buffer.append("Model Customization UUID:"); + buffer.append(configNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + buffer.append(System.lineSeparator()); + buffer.append("Model Instance Name:"); + buffer.append(configNodeTemplate.getName()); + buffer.append(System.lineSeparator()); + buffer.append("NFFunction:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); + buffer.append(System.lineSeparator()); + buffer.append("NFRole:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)); + buffer.append(System.lineSeparator()); + buffer.append("NFType:"); + buffer.append(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(configNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); + buffer.append(System.lineSeparator()); + + } + } + List<NodeTemplate> cvfcList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(vfNodeTemplate, SdcTypes.CVFC); for(NodeTemplate cvfcTemplate : cvfcList) { @@ -523,6 +581,7 @@ public class ASDCNotificationLogging { buffer.append(System.lineSeparator()); } + List<Group> groupList = toscaResourceStructure.getSdcCsarHelper().getGroupsOfOriginOfNodeTemplateByToscaGroupType(crNode, "org.openecomp.groups.NetworkCollection"); diff --git a/asdc-controller/src/test/resources/schema.sql b/asdc-controller/src/test/resources/schema.sql index 5f78c85c98..aef33c3aed 100644 --- a/asdc-controller/src/test/resources/schema.sql +++ b/asdc-controller/src/test/resources/schema.sql @@ -801,38 +801,62 @@ UPDATE CASCADE) ENGINE = InnoDB AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = l CREATE TABLE IF NOT EXISTS vnf_vfmodule_cvnfc_configuration_customization ( - `ID` INT(11) NOT NULL AUTO_INCREMENT, - `MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `VF_MODULE_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `CVNFC_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, - `CONFIGURATION_TYPE` VARCHAR(200) NULL, - `CONFIGURATION_ROLE` VARCHAR(200) NULL, - `CONFIGURATION_FUNCTION` VARCHAR(200) NULL, - `POLICY_NAME` VARCHAR(200) NULL, - `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - `CONFIGURATION_MODEL_UUID` VARCHAR(200) NOT NULL, - PRIMARY KEY (`ID`), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__configuration_idx` (`CONFIGURATION_MODEL_UUID` ASC), - UNIQUE INDEX `UK_vnf_vfmodule_cvnfc_configuration_customization` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC , `VF_MODULE_MODEL_CUSTOMIZATION_UUID` ASC , `CVNFC_MODEL_CUSTOMIZATION_UUID` ASC , `MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__cvnfc_cust1_idx` (`CVNFC_MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__vf_module_cust_idx` (`VF_MODULE_MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__vnf_res_cust_idx` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC), - CONSTRAINT `fk_vnf_vfmod_cvnfc_config_cust__configuration_resource` FOREIGN KEY (`CONFIGURATION_MODEL_UUID`) - REFERENCES `configuration` (`MODEL_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_cvnfc_configuration_customization__cvnfc_customization1` FOREIGN KEY (`CVNFC_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `cvnfc_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_vnf_configuration_cvnfc_customization__vf_module_customiza1` FOREIGN KEY (`VF_MODULE_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `vf_module_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_vfmodule_cvnfc_configuration_customization__vnf_resource_c1` FOREIGN KEY (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=INNODB AUTO_INCREMENT=20654 DEFAULT CHARACTER SET=LATIN1; + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + `MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, + `CONFIGURATION_TYPE` VARCHAR(200) NULL, + `CONFIGURATION_ROLE` VARCHAR(200) NULL, + `CONFIGURATION_FUNCTION` VARCHAR(200) NULL, + `POLICY_NAME` VARCHAR(200) NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `CONFIGURATION_MODEL_UUID` VARCHAR(200) NOT NULL, + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) DEFAULT NULL, + `VF_MODULE_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) DEFAULT NULL, + `CVNFC_CUSTOMIZATION_ID` INT(11) DEFAULT NULL, + PRIMARY KEY (`ID`), + INDEX `fk_vnf_vfmodule_cvnfc_config_cust__configuration_idx` (`CONFIGURATION_MODEL_UUID` ASC), + + CONSTRAINT `fk_vnf_vfmod_cvnfc_config_cust__configuration_resource` FOREIGN KEY (`CONFIGURATION_MODEL_UUID`) + REFERENCES `configuration` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = INNODB AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = LATIN1; + +CREATE TABLE IF NOT EXISTS `pnf_resource` ( + `ORCHESTRATION_MODE` varchar(20) NOT NULL DEFAULT 'HEAT', + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) DEFAULT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `MODEL_NAME` varchar(200) DEFAULT NULL, + `TOSCA_NODE_TYPE` varchar(200) DEFAULT NULL, + `RESOURCE_CATEGORY` varchar(200) DEFAULT NULL, + `RESOURCE_SUB_CATEGORY` varchar(200) DEFAULT NULL, + PRIMARY KEY (`MODEL_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + +CREATE TABLE IF NOT EXISTS `pnf_resource_customization` ( + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `NF_TYPE` varchar(200) DEFAULT NULL, + `NF_ROLE` varchar(200) DEFAULT NULL, + `NF_FUNCTION` varchar(200) DEFAULT NULL, + `NF_NAMING_CODE` varchar(200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `PNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, + `MULTI_STAGE_DESIGN` varchar(20) DEFAULT NULL, + `RESOURCE_INPUT` varchar(2000) DEFAULT NULL, + `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, + PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), + KEY `fk_pnf_resource_customization__pnf_resource1_idx` (`PNF_RESOURCE_MODEL_UUID`), + CONSTRAINT `fk_pnf_resource_customization__pnf_resource1` FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) REFERENCES `pnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +CREATE TABLE IF NOT EXISTS `pnf_resource_customization_to_service` ( + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `RESOURCE_MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`SERVICE_MODEL_UUID`,`RESOURCE_MODEL_CUSTOMIZATION_UUID`) +)ENGINE=InnoDB DEFAULT CHARSET=latin1; --------START Request DB SCHEMA -------- CREATE DATABASE requestdb; USE requestdb; diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy index dba6a1a2bb..484be19137 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/AbstractServiceTaskProcessor.groovy @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -32,111 +34,15 @@ import org.onap.so.bpmn.core.UrnPropertiesReader import org.onap.so.bpmn.core.WorkflowException import org.onap.so.client.aai.AAIResourcesClient import org.springframework.web.util.UriUtils +import org.slf4j.Logger +import org.slf4j.LoggerFactory import groovy.json.JsonSlurper public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcessor { - public MsoUtils utils = new MsoUtils() - - - /** - * Logs a message at the ERROR level. - * @param message the message - */ - public void logError(String message) { - log('ERROR', message, null, "true") - } - - /** - * Logs a message at the ERROR level. - * @param message the message - * @param cause the cause (stracktrace will be included in the output) - */ - public void logError(String message, Throwable cause) { - log('ERROR', message, cause, "true") - } - - /** - * Logs a message at the WARN level. - * @param message the message - */ - public void logWarn(String message) { - log('WARN', message, null, "true") - } - - /** - * Logs a message at the WARN level. - * @param message the message - * @param cause the cause (stracktrace will be included in the output) - */ - public void logWarn(String message, Throwable cause) { - log('WARN', message, cause, "true") - } - - /** - * Logs a message at the DEBUG level. - * @param message the message - * @param isDebugLogEnabled a flag indicating if DEBUG level is enabled - */ - public void logDebug(String message, String isDebugLogEnabled) { - log('DEBUG', message, null, isDebugLogEnabled) - } + private static final Logger logger = LoggerFactory.getLogger( MsoUtils.class); - /** - * Logs a message at the DEBUG level. - * @param message the message - * @param cause the cause (stracktrace will be included in the output) - * @param isDebugLogEnabled a flag indicating if DEBUG level is enabled - */ - public void logDebug(String message, Throwable cause, String isDebugLogEnabled) { - log('DEBUG', message, cause, isDebugLogEnabled) - } - - /** - * Logs a message at the specified level. - * @param level the level (DEBUG, INFO, WARN, ERROR) - * @param message the message - * @param isLevelEnabled a flag indicating if the level is enabled - * (used only at the DEBUG level) - */ - public void log(String level, String message, String isLevelEnabled) { - log(level, message, null, isLevelEnabled) - } - - /** - * Logs a message at the specified level. - * @param level the level (DEBUG, INFO, WARN, ERROR) - * @param message the message - * @param cause the cause (stracktrace will be included in the output) - * @param isLevelEnabled a flag indicating if the level is enabled - * (used only at the DEBUG level) - */ - public void log(String level, String message, Throwable cause, String isLevelEnabled) { - if (cause == null) { - utils.log(level, message, isLevelEnabled); - } else { - StringWriter stringWriter = new StringWriter(); - PrintWriter printWriter = new PrintWriter(stringWriter); - printWriter.println(message); - cause.printStackTrace(printWriter); - utils.log(level, stringWriter.toString(), isLevelEnabled); - printWriter.close(); - } - } - - /** - * Logs a WorkflowException at the ERROR level with the specified message. - * @param execution the execution - */ - public void logWorkflowException(DelegateExecution execution, String message) { - def workflowException = execution.getVariable("WorkflowException") - - if (workflowException == null) { - logError(message); - } else { - logError(message + ": " + workflowException) - } - } + public MsoUtils utils = new MsoUtils() /** * Saves the WorkflowException in the execution to the specified variable, @@ -173,7 +79,7 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess ', requredVariables=' + requiredVariables + ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) + logger.debug('Entered ' + method) String processKey = getProcessKey(execution) def prefix = execution.getVariable("prefix") @@ -236,13 +142,13 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess serviceInstanceId = (String) execution.getVariable("mso-service-instance-id") } - logDebug('Incoming message: ' + System.lineSeparator() + request, isDebugLogEnabled) - logDebug('Exited ' + method, isDebugLogEnabled) + logger.debug('Incoming message: ' + System.lineSeparator() + request) + logger.debug('Exited ' + method) return request } catch (BpmnError e) { throw e } catch (Exception e) { - logError('Caught exception in ' + method, e) + logger.error('Caught exception in ' + method, e) exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message") } } @@ -258,7 +164,7 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess 'execution=' + execution.getId() + ')' def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + method, isDebugLogEnabled) + logger.debug('Entered ' + method) String processKey = getProcessKey(execution); def prefix = execution.getVariable("prefix") @@ -278,8 +184,8 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess def parsed = jsonSlurper.parseText(request) - logDebug('Incoming message: ' + System.lineSeparator() + request, isDebugLogEnabled) - logDebug('Exited ' + method, isDebugLogEnabled) + logger.debug('Incoming message: ' + System.lineSeparator() + request) + logger.debug('Exited ' + method) return parsed } @@ -309,10 +215,10 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess } if (String.valueOf(execution.getVariable(processKey + "WorkflowResponseSent")).equals("true")) { - logDebug("Sync response has already been sent for " + processKey, isDebugLogEnabled) + logger.debug("Sync response has already been sent for " + processKey) }else{ - logDebug("Building " + processKey + " response ", isDebugLogEnabled) + logger.debug("Building " + processKey + " response ") int intResponseCode; @@ -337,11 +243,10 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess execution.setVariable(processKey + "Status", status); execution.setVariable("WorkflowResponse", response) - logDebug("Sending response for " + processKey + logger.debug("Sending response for " + processKey + " ResponseCode=" + intResponseCode + " Status=" + status - + " Response=\n" + response, - isDebugLogEnabled) + + " Response=\n" + response) // TODO: ensure that this flow was invoked asynchronously? @@ -362,7 +267,7 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess } } catch (Exception ex) { - logError("Unable to send workflow response to client ....", ex) + logger.error("Unable to send workflow response to client ....", ex) } } @@ -432,7 +337,7 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess def element = utils.getNodeXml(xml, elementName, false) if (element.trim().isEmpty()) { def msg = 'Required element \'' + elementName + '\' is missing or empty' - logError(msg) + logger.error(msg) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } else { return element @@ -454,7 +359,7 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess def elementText = utils.getNodeText(xml, elementName) if ((elementText == null) || (elementText.isEmpty())) { def msg = 'Required element \'' + elementName + '\' is missing or empty' - logError(msg) + logger.error(msg) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) } else { return elementText @@ -569,9 +474,9 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess String prefix = execution.getVariable('prefix') def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered SetSuccessIndicator Method', isDebugLogEnabled) + logger.debug('Entered SetSuccessIndicator Method') execution.setVariable(prefix+'SuccessIndicator', isSuccess) - logDebug('Outgoing SuccessIndicator is: ' + execution.getVariable(prefix+'SuccessIndicator') + '', isDebugLogEnabled) + logger.debug('Outgoing SuccessIndicator is: ' + execution.getVariable(prefix+'SuccessIndicator') + '') } /** @@ -579,14 +484,14 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess * */ public void sendSyncError(DelegateExecution execution) { - def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') String requestId = execution.getVariable("mso-request-id") - logDebug('sendSyncError, requestId: ' + requestId, isDebugEnabled) + logger.debug('sendSyncError, requestId: ' + requestId) WorkflowException workflowExceptionObj = execution.getVariable("WorkflowException") if (workflowExceptionObj != null) { String errorMessage = workflowExceptionObj.getErrorMessage() def errorCode = workflowExceptionObj.getErrorCode() - logDebug('sendSyncError, requestId: ' + requestId + ' | errorMessage: ' + errorMessage + ' | errorCode: ' + errorCode, isDebugEnabled) + logger.debug('sendSyncError, requestId: ' + requestId + ' | errorMessage: ' + errorMessage + ' | errorCode: ' + errorCode) sendWorkflowResponse(execution, errorCode, errorMessage) } } @@ -602,27 +507,27 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess DelegateExecution execution = (DelegateExecution) args[0] def classAndMethod = getClass().getSimpleName() + '.' + methodName + '(execution=' + execution.getId() + ')' - def isDebugEnabled = execution.getVariable('isDebugLogEnabled') + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logDebug('Entered ' + classAndMethod, isDebugEnabled) - logDebug('Received parameters: ' + args, isDebugEnabled) + logger.debug('Entered ' + classAndMethod) + logger.debug('Received parameters: ' + args) try{ def methodToCall = this.metaClass.getMetaMethod(methodName, args) - logDebug('Method to call: ' + methodToCall, isDebugEnabled) + logger.debug('Method to call: ' + methodToCall) methodToCall?.invoke(this, args) } catch(BpmnError bpmnError) { - logDebug('Rethrowing BpmnError ' + bpmnError.getMessage(), isDebugEnabled) + logger.debug('Rethrowing BpmnError ' + bpmnError.getMessage()) throw bpmnError } catch(Exception e) { e.printStackTrace() - logDebug('Unexpected error encountered - ' + e.getMessage(), isDebugEnabled) + logger.debug('Unexpected error encountered - ' + e.getMessage()) (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, e.getMessage()) } finally { - logDebug('Exited ' + classAndMethod, isDebugEnabled) + logger.debug('Exited ' + classAndMethod) } } } @@ -718,8 +623,8 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess def disableRollback = execution.getVariable("disableRollback") def defaultRollback = UrnPropertiesReader.getVariable("mso.rollback", execution).toBoolean() - logDebug('disableRollback: ' + disableRollback, isDebugLogEnabled) - logDebug('defaultRollback: ' + defaultRollback, isDebugLogEnabled) + logger.debug('disableRollback: ' + disableRollback) + logger.debug('defaultRollback: ' + defaultRollback) def rollbackEnabled @@ -727,7 +632,7 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess // get from default urn settings for mso_rollback disableRollback = !defaultRollback rollbackEnabled = defaultRollback - logDebug('disableRollback is null or empty!', isDebugLogEnabled) + logger.debug('disableRollback is null or empty!') } else { if(disableRollback == true) { @@ -742,7 +647,7 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess } execution.setVariable(prefix+"backoutOnFailure", rollbackEnabled) - logDebug('rollbackEnabled (aka backoutOnFailure): ' + rollbackEnabled, isDebugLogEnabled) + logger.debug('rollbackEnabled (aka backoutOnFailure): ' + rollbackEnabled) } public void setBasicDBAuthHeader(DelegateExecution execution, isDebugLogEnabled) { @@ -752,7 +657,7 @@ public abstract class AbstractServiceTaskProcessor implements ServiceTaskProcess execution.setVariable("BasicAuthHeaderValueDB",encodedString) } catch (IOException ex) { String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() - utils.log("DEBUG", dataErrorMessage, isDebugLogEnabled) + logger.debug(dataErrorMessage) (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } } 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 0d9b3c5b94..d5b0b31a39 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 @@ -51,13 +51,13 @@ class CatalogDbUtils { private static final Logger logger = LoggerFactory.getLogger( CatalogDbUtils.class); private HttpClientFactory httpClientFactory - private MsoUtils msoUtils - private JsonUtils jsonUtils + private MsoUtils utils + private JsonUtils jsonUtils static private String defaultDbAdapterVersion = "v2" - CatalogDbUtils(HttpClientFactory httpClientFactory, MsoUtils msoUtils, JsonUtils jsonUtils) { + CatalogDbUtils(HttpClientFactory httpClientFactory, JsonUtils jsonUtils) { this.httpClientFactory = httpClientFactory - this.msoUtils = msoUtils + this.utils = new MsoUtils() this.jsonUtils = jsonUtils } @@ -105,7 +105,7 @@ class CatalogDbUtils { } } catch (Exception e) { - msoUtils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + logger.error("Exception in Querying Catalog DB: " + e.message) throw e } @@ -488,7 +488,7 @@ class CatalogDbUtils { } } catch (Exception e) { - msoUtils.log("ERROR", "Exception in Querying Catalog DB: " + e.message) + logger.error("Exception in Querying Catalog DB: " + e.message) throw e } @@ -500,13 +500,13 @@ class CatalogDbUtils { String encodedString = null try { String basicAuthValueDB = UrnPropertiesReader.getVariable("mso.adapters.db.auth", execution) - msoUtils.log("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB) + logger.debug("DEBUG", " Obtained BasicAuth userid password for Catalog DB adapter: " + basicAuthValueDB) - encodedString = msoUtils.getBasicAuth(basicAuthValueDB, UrnPropertiesReader.getVariable("mso.msoKey", execution)) + encodedString = utils.getBasicAuth(basicAuthValueDB, UrnPropertiesReader.getVariable("mso.msoKey", execution)) execution.setVariable("BasicAuthHeaderValueDB",encodedString) } catch (IOException ex) { String dataErrorMessage = " Unable to encode Catalog DB user/password string - " + ex.getMessage() - msoUtils.log("ERROR", dataErrorMessage) + logger.error(dataErrorMessage) } return encodedString } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsFactory.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsFactory.groovy index faa0037169..bf7d07cbb3 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsFactory.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsFactory.groovy @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2018 NOKIA. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -26,6 +28,6 @@ import org.onap.so.client.HttpClientFactory public class CatalogDbUtilsFactory { CatalogDbUtils create() { - return new CatalogDbUtils(new HttpClientFactory(), new MsoUtils(), new JsonUtils()) + return new CatalogDbUtils(new HttpClientFactory(), new JsonUtils()) } } diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy index c2e4ee4454..92c1579aa0 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/MsoUtils.groovy @@ -290,7 +290,7 @@ class MsoUtils { } } - def log(logmode,logtxt,isDebugLogEnabled="false"){ + def private log(logmode,logtxt,isDebugLogEnabled="false"){ if ("INFO"==logmode) { logger.info(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), logtxt, "BPMN"); } else if ("WARN"==logmode) { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java index ba3ab7f315..c6e7668f22 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/bbobjects/GenericVnf.java @@ -143,8 +143,28 @@ public class GenericVnf implements Serializable, ShallowCopy<GenericVnf> { private String nfFunction; @JsonProperty("nf-role") private String nfRole; + @JsonProperty("CDS_BLUEPRINT_NAME") + private String blueprintName; + @JsonProperty("CDS_BLUEPRINT_VERSION") + private String blueprintVersion; + public String getBlueprintName() { + return blueprintName; + } + + public void setBlueprintName(String blueprintName) { + this.blueprintName = blueprintName; + } + + public String getBlueprintVersion() { + return blueprintVersion; + } + + public void setBlueprintVersion(String blueprintVersion) { + this.blueprintVersion = blueprintVersion; + } + public String getNfFunction() { return nfFunction; } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java index 36a6bf37d9..88ed5d37d9 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/BBInputSetupUtils.java @@ -146,7 +146,7 @@ public class BBInputSetupUtils { } public VnfVfmoduleCvnfcConfigurationCustomization getVnfVfmoduleCvnfcConfigurationCustomizationByActionAndIsALaCarteAndRequestScopeAndCloudOwner(String vnfCustomizationUuid, - String vfModuleCustomizationUuid, String cvnfcCustomizationUuid) { + String vfModuleCustomizationUuid, String cvnfcCustomizationUuid){ return catalogDbClient.getVnfVfmoduleCvnfcConfigurationCustomizationByVnfCustomizationUuidAndVfModuleCustomizationUuidAndCvnfcCustomizationUuid(vnfCustomizationUuid, vfModuleCustomizationUuid, cvnfcCustomizationUuid); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java index d2d321f8f4..260a9420c8 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java @@ -46,7 +46,10 @@ public class ExtractPojosForBB { private static final Logger logger = LoggerFactory.getLogger(ExtractPojosForBB.class); - public <T> T extractByKey(BuildingBlockExecution execution, ResourceKey key, String value) + public <T> T extractByKey(BuildingBlockExecution execution, ResourceKey key) throws BBObjectNotFoundException { + return extractByKey(execution, key, execution.getLookupMap().get(key)); + } + protected <T> T extractByKey(BuildingBlockExecution execution, ResourceKey key, String value) throws BBObjectNotFoundException { Optional<T> result = Optional.empty(); @@ -59,39 +62,39 @@ public class ExtractPojosForBB { result = lookupObjectInList(gBBInput.getCustomer().getServiceSubscription().getServiceInstances(), value); break; case GENERIC_VNF_ID: - serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); result = lookupObjectInList(serviceInstance.getVnfs(), value); break; case NETWORK_ID: - serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); result = lookupObjectInList(serviceInstance.getNetworks(), value); break; case VOLUME_GROUP_ID: - vnf = extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + vnf = extractByKey(execution, ResourceKey.GENERIC_VNF_ID); result = lookupObjectInList(vnf.getVolumeGroups(), value); break; case VF_MODULE_ID: - vnf = extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + vnf = extractByKey(execution, ResourceKey.GENERIC_VNF_ID); result = lookupObjectInList(vnf.getVfModules(), value); break; case ALLOTTED_RESOURCE_ID: - serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); result = lookupObjectInList(serviceInstance.getAllottedResources(), value); break; case CONFIGURATION_ID: - serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); result = lookupObjectInList(serviceInstance.getConfigurations(), value); break; case VPN_ID: - serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); result = lookupObjectInList(gBBInput.getCustomer().getVpnBindings(), value); break; case VPN_BONDING_LINK_ID: - serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); result = lookupObjectInList(serviceInstance.getVpnBondingLinks(),value); break; case INSTANCE_GROUP_ID: - serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); result = lookupObjectInList(serviceInstance.getInstanceGroups(), value); break; default: diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java new file mode 100644 index 0000000000..29abe4413b --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java @@ -0,0 +1,192 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.client.cds; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.onap.ccsdk.apps.controllerblueprints.common.api.ActionIdentifiers; +import org.onap.ccsdk.apps.controllerblueprints.common.api.CommonHeader; +import org.onap.ccsdk.apps.controllerblueprints.common.api.EventType; +import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceInput; +import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceOutput; +import org.onap.so.client.PreconditionFailedException; +import org.onap.so.client.RestPropertiesLoader; +import org.onap.so.client.cds.beans.AbstractCDSPropertiesBean; +import org.onap.so.client.exception.ExceptionBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Struct; +import com.google.protobuf.Struct.Builder; +import com.google.protobuf.util.JsonFormat; + +import io.grpc.Status; + +/** + * Util class to support Call to CDS client + * + */ +@Component +public class AbstractCDSProcessingBBUtils implements CDSProcessingListener { + + private static final Logger logger = LoggerFactory.getLogger(AbstractCDSProcessingBBUtils.class); + + private static final String SUCCESS = "Success"; + private static final String FAILED = "Failed"; + private static final String PROCESSING = "Processing"; + + private final AtomicReference<String> cdsResponse = new AtomicReference<>(); + + @Autowired + private ExceptionBuilder exceptionUtil; + + /** + * Extracting data from execution object and building the ExecutionServiceInput + * Object + * + * @param execution + * DelegateExecution object + */ + public void constructExecutionServiceInputObject(DelegateExecution execution) { + logger.trace("Start AbstractCDSProcessingBBUtils.preProcessRequest "); + + try { + AbstractCDSPropertiesBean executionObject = (AbstractCDSPropertiesBean) execution + .getVariable("executionObject"); + + String payload = executionObject.getRequestObject(); + + CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(executionObject.getOriginatorId()) + .setRequestId(executionObject.getRequestId()).setSubRequestId(executionObject.getSubRequestId()) + .build(); + ActionIdentifiers actionIdentifiers = ActionIdentifiers.newBuilder() + .setBlueprintName(executionObject.getBlueprintName()) + .setBlueprintVersion(executionObject.getBlueprintVersion()) + .setActionName(executionObject.getActionName()).setMode(executionObject.getMode()).build(); + + Builder struct = Struct.newBuilder(); + try { + JsonFormat.parser().merge(payload, struct); + } catch (InvalidProtocolBufferException e) { + logger.error("Failed to parse received message. blueprint({}:{}) for action({}). {}", + executionObject.getBlueprintVersion(), executionObject.getBlueprintName(), + executionObject.getActionName(), e); + } + + ExecutionServiceInput executionServiceInput = ExecutionServiceInput.newBuilder() + .setCommonHeader(commonHeader).setActionIdentifiers(actionIdentifiers).setPayload(struct.build()) + .build(); + + execution.setVariable("executionServiceInput", executionServiceInput); + + } catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } + + /** + * get the executionServiceInput object from execution and send a request to CDS + * Client and wait for TIMEOUT period + * + * @param execution + * DelegateExecution object + */ + public void sendRequestToCDSClient(DelegateExecution execution) { + + logger.trace("Start AbstractCDSProcessingBBUtils.sendRequestToCDSClient "); + try { + CDSProperties props = RestPropertiesLoader.getInstance().getNewImpl(CDSProperties.class); + if (props == null) { + throw new PreconditionFailedException( + "No RestProperty.CDSProperties implementation found on classpath, can't create client."); + } + + ExecutionServiceInput executionServiceInput = (ExecutionServiceInput) execution + .getVariable("executionServiceInput"); + + CDSProcessingListener cdsProcessingListener = new AbstractCDSProcessingBBUtils(); + + CDSProcessingClient cdsClient = new CDSProcessingClient(cdsProcessingListener); + CountDownLatch countDownLatch = cdsClient.sendRequest(executionServiceInput); + + try { + countDownLatch.await(props.getTimeout(), TimeUnit.SECONDS); + } catch (InterruptedException ex) { + logger.error("Caught exception in sendRequestToCDSClient in AbstractCDSProcessingBBUtils : ", ex); + } finally { + cdsClient.close(); + } + + if (cdsResponse != null) { + execution.setVariable("CDSStatus", cdsResponse.get()); + } + + } catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } + + /** + * Get Response from CDS Client + * + */ + @Override + public void onMessage(ExecutionServiceOutput message) { + logger.info("Received notification from CDS: {}", message); + EventType eventType = message.getStatus().getEventType(); + + switch (eventType) { + + case EVENT_COMPONENT_FAILURE: + // failed processing with failure + cdsResponse.set(FAILED); + break; + case EVENT_COMPONENT_PROCESSING: + // still processing + cdsResponse.set(PROCESSING); + break; + case EVENT_COMPONENT_EXECUTED: + // done with async processing + cdsResponse.set(SUCCESS); + break; + default: + cdsResponse.set(FAILED); + break; + } + + } + + /** + * On error at CDS, log the error + */ + @Override + public void onError(Throwable t) { + Status status = Status.fromThrowable(t); + logger.error("Failed processing blueprint {}", status, t); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/AbstractCDSPropertiesBean.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/AbstractCDSPropertiesBean.java new file mode 100644 index 0000000000..4b645984cf --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/AbstractCDSPropertiesBean.java @@ -0,0 +1,89 @@ +package org.onap.so.client.cds.beans; + +import java.io.Serializable; + +public class AbstractCDSPropertiesBean implements Serializable { + + private static final long serialVersionUID = -4800522372460352963L; + + private String blueprintName; + + private String blueprintVersion; + + private String requestObject; + + private String originatorId; + + private String requestId; + + private String subRequestId; + + private String actionName; + + private String mode; + + public String getBlueprintName() { + return blueprintName; + } + + public void setBlueprintName(String blueprintName) { + this.blueprintName = blueprintName; + } + + public String getBlueprintVersion() { + return blueprintVersion; + } + + public void setBlueprintVersion(String blueprintVersion) { + this.blueprintVersion = blueprintVersion; + } + + public String getRequestObject() { + return requestObject; + } + + public void setRequestObject(String requestObject) { + this.requestObject = requestObject; + } + + public String getOriginatorId() { + return originatorId; + } + + public void setOriginatorId(String originatorId) { + this.originatorId = originatorId; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getSubRequestId() { + return subRequestId; + } + + public void setSubRequestId(String subRequestId) { + this.subRequestId = subRequestId; + } + + public String getActionName() { + return actionName; + } + + public void setActionName(String actionName) { + this.actionName = actionName; + } + + public String getMode() { + return mode; + } + + public void setMode(String mode) { + this.mode = mode; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java new file mode 100644 index 0000000000..bdb9161735 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnf.java @@ -0,0 +1,112 @@ +package org.onap.so.client.cds.beans; + +import java.util.HashMap; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"service-instance-id", +"pnf-id", +"pnf-name", +"service-model-uuid", +"pnf-customization-uuid" +}) + +public class ConfigAssignPropertiesForPnf { + + @JsonProperty("service-instance-id") + private String serviceInstanceId; + + @JsonProperty("pnf-id") + private String pnfId; + + @JsonProperty("pnf-name") + private String pnfName; + + @JsonProperty("service-model-uuid") + private String serviceModelUuid; + + @JsonProperty("pnf-customization-uuid") + private String pnfCustomizationUuid; + + @JsonIgnore + private Map<String, Object> userParam = new HashMap<String, Object>(); + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getPnfId() { + return pnfId; + } + + public void setPnfId(String pnfId) { + this.pnfId = pnfId; + } + + public String getPnfName() { + return pnfName; + } + + public void setPnfName(String pnfName) { + this.pnfName = pnfName; + } + + public String getServiceModelUuid() { + return serviceModelUuid; + } + + public void setServiceModelUuid(String serviceModelUuid) { + this.serviceModelUuid = serviceModelUuid; + } + + public String getPnfCustomizationUuid() { + return pnfCustomizationUuid; + } + + public void setPnfCustomizationUuid(String pnfCustomizationUuid) { + this.pnfCustomizationUuid = pnfCustomizationUuid; + } + + public Map<String, Object> getUserParam() { + return this.userParam; + } + + public void setUserParam(String name, Object value) { + this.userParam.put(name, value); + } + + @Override + public String toString() { + + final StringBuilder sb = new StringBuilder("{"); + sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\""); + sb.append(", \"pnf-id\":").append("\"").append(pnfId).append("\""); + sb.append(", \"pnf-name\":").append("\"").append(pnfName).append("\""); + sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\""); + sb.append(", \"pnf-customization-uuid\":").append("\"").append(pnfCustomizationUuid).append("\""); + for (Map.Entry<String, Object> entry : userParam.entrySet()) { + sb.append(","); + sb.append("\""); + sb.append(entry.getKey()); + sb.append("\""); + sb.append(":"); + sb.append("\""); + sb.append(entry.getValue()); + sb.append("\""); + } + sb.append('}'); + + return sb.toString(); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java new file mode 100644 index 0000000000..1ce26d8585 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnf.java @@ -0,0 +1,112 @@ +package org.onap.so.client.cds.beans; + +import java.util.HashMap; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"service-instance-id", +"vnf-id", +"vnf-name", +"service-model-uuid", +"vnf-customization-uuid" +}) + +public class ConfigAssignPropertiesForVnf { + + @JsonProperty("service-instance-id") + private String serviceInstanceId; + + @JsonProperty("vnf-id") + private String vnfId; + + @JsonProperty("vnf-name") + private String vnfName; + + @JsonProperty("service-model-uuid") + private String serviceModelUuid; + + @JsonProperty("vnf-customization-uuid") + private String vnfCustomizationUuid; + + @JsonIgnore + private Map<String, Object> userParam = new HashMap<String, Object>(); + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getVnfId() { + return vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + public String getVnfName() { + return vnfName; + } + + public void setVnfName(String vnfName) { + this.vnfName = vnfName; + } + + public String getServiceModelUuid() { + return serviceModelUuid; + } + + public void setServiceModelUuid(String serviceModelUuid) { + this.serviceModelUuid = serviceModelUuid; + } + + public String getVnfCustomizationUuid() { + return vnfCustomizationUuid; + } + + public void setVnfCustomizationUuid(String vnfCustomizationUuid) { + this.vnfCustomizationUuid = vnfCustomizationUuid; + } + + public Map<String, Object> getUserParam() { + return this.userParam; + } + + public void setUserParam(String name, Object value) { + this.userParam.put(name, value); + } + + @Override + public String toString() { + + final StringBuilder sb = new StringBuilder("{"); + sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\""); + sb.append(", \"vnf-id\":").append("\"").append(vnfId).append("\""); + sb.append(", \"vnf-name\":").append("\"").append(vnfName).append("\""); + sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\""); + sb.append(", \"vnf-customization-uuid\":").append("\"").append(vnfCustomizationUuid).append("\""); + for (Map.Entry<String, Object> entry : userParam.entrySet()) { + sb.append(","); + sb.append("\""); + sb.append(entry.getKey()); + sb.append("\""); + sb.append(":"); + sb.append("\""); + sb.append(entry.getValue()); + sb.append("\""); + } + sb.append('}'); + + return sb.toString(); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnf.java new file mode 100644 index 0000000000..b96847f422 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnf.java @@ -0,0 +1,46 @@ +package org.onap.so.client.cds.beans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"config-assign-properties", +"resolution-key" +}) + +public class ConfigAssignRequestPnf { + @JsonProperty("resolution-key") + private String resolutionKey; + @JsonProperty("config-assign-properties") + private ConfigAssignPropertiesForPnf configAssignPropertiesForPnf; + + public String getResolutionKey() { + return resolutionKey; + } + + public void setResolutionKey(String resolutionKey) { + this.resolutionKey = resolutionKey; + } + + public ConfigAssignPropertiesForPnf getConfigAssignPropertiesForPnf() { + return configAssignPropertiesForPnf; + } + + public void setConfigAssignPropertiesForPnf(ConfigAssignPropertiesForPnf configAssignPropertiesForPnf) { + this.configAssignPropertiesForPnf = configAssignPropertiesForPnf; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("{\"config-assign-request\":{"); + sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\""); + sb.append(", \"config-assign-properties\":").append(configAssignPropertiesForPnf.toString()); + sb.append('}'); + sb.append('}'); + + return sb.toString(); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnf.java new file mode 100644 index 0000000000..b3a9601e2e --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnf.java @@ -0,0 +1,45 @@ + +package org.onap.so.client.cds.beans; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"config-assign-properties", +"resolution-key" +}) +public class ConfigAssignRequestVnf { + @JsonProperty("resolution-key") + private String resolutionKey; + @JsonProperty("config-assign-properties") + private ConfigAssignPropertiesForVnf configAssignPropertiesForVnf; + + public String getResolutionKey() { + return resolutionKey; + } + + public void setResolutionKey(String resolutionKey) { + this.resolutionKey = resolutionKey; + } + + public ConfigAssignPropertiesForVnf getConfigAssignPropertiesForVnf() { + return configAssignPropertiesForVnf; + } + + public void setConfigAssignPropertiesForVnf(ConfigAssignPropertiesForVnf configAssignPropertiesForVnf) { + this.configAssignPropertiesForVnf = configAssignPropertiesForVnf; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("{\"config-assign-request\":{"); + sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\""); + sb.append(", \"config-assign-properties\":").append(configAssignPropertiesForVnf.toString()); + sb.append('}'); + sb.append('}'); + + return sb.toString(); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnf.java new file mode 100644 index 0000000000..b8fb5b96bd --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnf.java @@ -0,0 +1,88 @@ +package org.onap.so.client.cds.beans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"service-instance-id", +"pnf-id", +"pnf-name", +"service-model-uuid", +"pnf-customization-uuid" +}) + +public class ConfigDeployPropertiesForPnf { + + @JsonProperty("service-instance-id") + private String serviceInstanceId; + + @JsonProperty("pnf-id") + private String pnfId; + + @JsonProperty("pnf-name") + private String pnfName; + + @JsonProperty("service-model-uuid") + private String serviceModelUuid; + + @JsonProperty("pnf-customization-uuid") + private String pnfCustomizationUuid; + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getPnfId() { + return pnfId; + } + + public void setPnfId(String pnfId) { + this.pnfId = pnfId; + } + + public String getPnfName() { + return pnfName; + } + + public void setPnfName(String pnfName) { + this.pnfName = pnfName; + } + + public String getServiceModelUuid() { + return serviceModelUuid; + } + + public void setServiceModelUuid(String serviceModelUuid) { + this.serviceModelUuid = serviceModelUuid; + } + + public String getPnfCustomizationUuid() { + return pnfCustomizationUuid; + } + + public void setPnfCustomizationUuid(String pnfCustomizationUuid) { + this.pnfCustomizationUuid = pnfCustomizationUuid; + } + + @Override + public String toString() { + + final StringBuilder sb = new StringBuilder("{"); + sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\""); + sb.append(", \"pnf-id\":").append("\"").append(pnfId).append("\""); + sb.append(", \"pnf-name\":").append("\"").append(pnfName).append("\""); + sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\""); + sb.append(", \"pnf-customization-uuid\":").append("\"").append(pnfCustomizationUuid).append("\""); + + sb.append('}'); + + return sb.toString(); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnf.java new file mode 100644 index 0000000000..ca2530b541 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnf.java @@ -0,0 +1,87 @@ +package org.onap.so.client.cds.beans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"service-instance-id", +"vnf-id", +"vnf-name", +"service-model-uuid", +"vnf-customization-uuid" +}) +public class ConfigDeployPropertiesForVnf { + + @JsonProperty("service-instance-id") + private String serviceInstanceId; + + @JsonProperty("vnf-id") + private String vnfId; + + @JsonProperty("vnf-name") + private String vnfName; + + @JsonProperty("service-model-uuid") + private String serviceModelUuid; + + @JsonProperty("vnf-customization-uuid") + private String vnfCustomizationUuid; + + public String getServiceInstanceId() { + return serviceInstanceId; + } + + public void setServiceInstanceId(String serviceInstanceId) { + this.serviceInstanceId = serviceInstanceId; + } + + public String getVnfId() { + return vnfId; + } + + public void setVnfId(String vnfId) { + this.vnfId = vnfId; + } + + public String getVnfName() { + return vnfName; + } + + public void setVnfName(String vnfName) { + this.vnfName = vnfName; + } + + public String getServiceModelUuid() { + return serviceModelUuid; + } + + public void setServiceModelUuid(String serviceModelUuid) { + this.serviceModelUuid = serviceModelUuid; + } + + public String getVnfCustomizationUuid() { + return vnfCustomizationUuid; + } + + public void setVnfCustomizationUuid(String vnfCustomizationUuid) { + this.vnfCustomizationUuid = vnfCustomizationUuid; + } + + @Override + public String toString() { + + final StringBuilder sb = new StringBuilder("{"); + sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\""); + sb.append(", \"vnf-id\":").append("\"").append(vnfId).append("\""); + sb.append(", \"vnf-name\":").append("\"").append(vnfName).append("\""); + sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\""); + sb.append(", \"vnf-customization-uuid\":").append("\"").append(vnfCustomizationUuid).append("\""); + + sb.append('}'); + + return sb.toString(); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnf.java new file mode 100644 index 0000000000..4635008d3f --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnf.java @@ -0,0 +1,46 @@ +package org.onap.so.client.cds.beans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"config-deploy-properties", +"resolution-key" +}) +public class ConfigDeployRequestPnf { + @JsonProperty("resolution-key") + private String resolutionKey; + + @JsonProperty("config-deploy-properties") + private ConfigDeployPropertiesForPnf configDeployPropertiesForPnf; + + public String getResolutionKey() { + return resolutionKey; + } + + public void setResolutionKey(String resolutionKey) { + this.resolutionKey = resolutionKey; + } + + public ConfigDeployPropertiesForPnf getConfigDeployPropertiesForPnf() { + return configDeployPropertiesForPnf; + } + + public void setConfigDeployPropertiesForPnf(ConfigDeployPropertiesForPnf configDeployPropertiesForPnf) { + this.configDeployPropertiesForPnf = configDeployPropertiesForPnf; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("{\"config-deploy-request\":{"); + sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\""); + sb.append(", \"config-deploy-properties\":").append(configDeployPropertiesForPnf.toString()); + sb.append('}'); + sb.append('}'); + + return sb.toString(); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnf.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnf.java new file mode 100644 index 0000000000..53b956d3c4 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnf.java @@ -0,0 +1,46 @@ +package org.onap.so.client.cds.beans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ +"config-deploy-properties", +"resolution-key" +}) +public class ConfigDeployRequestVnf { + @JsonProperty("resolution-key") + private String resolutionKey; + + @JsonProperty("config-deploy-properties") + private ConfigDeployPropertiesForVnf configDeployPropertiesForVnf; + + public String getResolutionKey() { + return resolutionKey; + } + + public void setResolutionKey(String resolutionKey) { + this.resolutionKey = resolutionKey; + } + + public ConfigDeployPropertiesForVnf getConfigDeployPropertiesForVnf() { + return configDeployPropertiesForVnf; + } + + public void setConfigDeployPropertiesForVnf(ConfigDeployPropertiesForVnf configDeployPropertiesForVnf) { + this.configDeployPropertiesForVnf = configDeployPropertiesForVnf; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("{\"config-deploy-request\":{"); + sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\""); + sb.append(", \"config-deploy-properties\":").append(configDeployPropertiesForVnf.toString()); + sb.append('}'); + sb.append('}'); + + return sb.toString(); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/CDSPropertiesImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/CDSPropertiesImpl.java index 1967e5a1ce..d1888b17df 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/CDSPropertiesImpl.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/restproperties/CDSPropertiesImpl.java @@ -30,6 +30,7 @@ public class CDSPropertiesImpl implements CDSProperties { private static final String ENDPOINT = "cds.endpoint"; private static final String PORT = "cds.port"; private static final String AUTH = "cds.auth"; + private static final String TIMEOUT = "cds.timeout"; public CDSPropertiesImpl() { // Needed for service loader @@ -74,4 +75,9 @@ public class CDSPropertiesImpl implements CDSProperties { public boolean mapNotFoundToEmpty() { return false; } + + @Override + public int getTimeout() { + return Integer.parseInt(Objects.requireNonNull(UrnPropertiesReader.getVariable(TIMEOUT))); + } } diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsTest.groovy index d6a7cf0634..d7438f80f9 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/CatalogDbUtilsTest.groovy @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2018 Nokia. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -51,7 +53,6 @@ class CatalogDbUtilsTest { private static final String RESPONSE_FROM_CATALOG_DB = "{\"serviceVnfs\": [{\"name\": \"service1\"," + "\"vfModules\": [{\"name\": \"module1\", \"isBase\":true, \"initialCount\":1}]}]}" private HttpClientFactory httpClientFactoryMock - private MsoUtils msoUtilsMock private JsonUtils jsonUtilsMock private HttpClient httpClientMock private DelegateExecutionFake executionFake @@ -61,11 +62,10 @@ class CatalogDbUtilsTest { @Before void setUp() { httpClientFactoryMock = mock(HttpClientFactory.class) - msoUtilsMock = mock(MsoUtils.class) jsonUtilsMock = mock(JsonUtils.class) httpClientMock = mock(HttpClient.class) executionFake = new DelegateExecutionFake() - testedObject = new CatalogDbUtils(httpClientFactoryMock, msoUtilsMock, jsonUtilsMock) + testedObject = new CatalogDbUtils(httpClientFactoryMock, jsonUtilsMock) } @Test diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModuleTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModuleTest.groovy index 21441b9b73..60385a7990 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModuleTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/PrepareUpdateAAIVfModuleTest.groovy @@ -34,7 +34,6 @@ import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.MockitoAnnotations import org.mockito.runners.MockitoJUnitRunner -import org.onap.so.bpmn.mock.StubResponseAAI import static org.mockito.Mockito.* diff --git a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnfTest.groovy b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnfTest.groovy index 2bd5181c31..6a4d53654b 100644 --- a/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnfTest.groovy +++ b/bpmn/MSOCommonBPMN/src/test/groovy/org/onap/so/bpmn/common/scripts/UpdateAAIGenericVnfTest.groovy @@ -37,7 +37,6 @@ import org.mockito.MockitoAnnotations import org.mockito.runners.MockitoJUnitRunner import org.onap.so.bpmn.core.WorkflowException import org.onap.so.bpmn.mock.FileUtil -import org.onap.so.bpmn.mock.StubResponseAAI import static com.github.tomakehurst.wiremock.client.WireMock.* import static org.mockito.ArgumentMatchers.any diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java index d5b5cde99b..bf98648dbc 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java @@ -352,7 +352,7 @@ public class BuildingBlockTestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -370,7 +370,7 @@ public class BuildingBlockTestDataSetup{ Collection collection = null; try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); collection = serviceInstance.getCollection(); if (collection == null) { @@ -445,7 +445,7 @@ public class BuildingBlockTestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -490,7 +490,7 @@ public class BuildingBlockTestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -525,7 +525,7 @@ public class BuildingBlockTestDataSetup{ GenericVnf genericVnf = null; try { - genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); } catch(BBObjectNotFoundException e) { genericVnf = setGenericVnf(); } @@ -553,7 +553,7 @@ public class BuildingBlockTestDataSetup{ GenericVnf genericVnf = null; try { - genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); } catch(BBObjectNotFoundException e) { genericVnf = setGenericVnf(); } @@ -617,7 +617,7 @@ public class BuildingBlockTestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -684,7 +684,7 @@ public class BuildingBlockTestDataSetup{ configurations.add(config); ServiceInstance serviceInstance = new ServiceInstance(); try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/MockResource.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/MockResource.java deleted file mode 100644 index b9a413fc96..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/MockResource.java +++ /dev/null @@ -1,207 +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.mock; - -import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; - -import java.util.HashMap; -import java.util.Map; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Response; - -import com.github.tomakehurst.wiremock.WireMockServer; -import com.github.tomakehurst.wiremock.client.WireMock; - -/** - * - * Mock Resource which is used to start, stop the WireMock Server - * Also up to 50 mock properties can be added at run-time to change the properties used in transformers such as sdnc_delay in SDNCAdapterMockTransformer - * You can also selectively setup a stub (use reset before setting up), reset all stubs - */ -@Path("/server") -public class MockResource { - - private boolean started = false; - private final Integer defaultPort = 28090; - private WireMockServer wireMockServer = null; - private static Map<String,String> mockProperties = new HashMap<>(); - - public static String getMockProperties(String key) { - return mockProperties.get(key); - } - - private synchronized void initMockServer(int portNumber) { - String path = "src/test/resources/" + "__files/sdncSimResponse.xml"; - path = path.substring(0,path.indexOf("__files/")); - - wireMockServer = new WireMockServer(wireMockConfig().port(portNumber).extensions("org.onap.so.bpmn.mock.SDNCAdapterMockTransformer") - .extensions("org.onap.so.bpmn.mock.SDNCAdapterNetworkTopologyMockTransformer") - .extensions("org.onap.so.bpmn.mock.VnfAdapterCreateMockTransformer") - .extensions("org.onap.so.bpmn.mock.VnfAdapterDeleteMockTransformer") - .extensions("org.onap.so.bpmn.mock.VnfAdapterUpdateMockTransformer") - .extensions("org.onap.so.bpmn.mock.VnfAdapterRollbackMockTransformer") - .extensions("org.onap.so.bpmn.mock.VnfAdapterQueryMockTransformer")); - //.withRootDirectory(path)); - //Mocks were failing - commenting out for now, both mock and transformers seem to work fine - WireMock.configureFor("localhost", portNumber); - wireMockServer.start(); -// StubResponse.setupAllMocks(); - started= true; - } - - public static void main(String [] args) { - MockResource mockresource = new MockResource(); - mockresource.start(28090); - mockresource.reset(); -// mockresource.setupStub("MockCreateTenant"); - } - - /** - * Starts the wiremock server in default port - * @return - */ - @GET - @Path("/start") - @Produces("application/json") - public Response start() { - return startMockServer(defaultPort); - } - - private Response startMockServer(int port) { - if (!started) { - initMockServer(defaultPort); - System.out.println("Started Mock Server in port " + port); - return Response.status(200).entity("Started Mock Server in port " + port).build(); - } else { - return Response.status(200).entity("Mock Server is already running").build(); - } - } - - /** - * Starts the wiremock server in a different port - * @param portNumber - * @return - */ - @GET - @Path("/start/{portNumber}") - @Produces("application/json") - public Response start(@PathParam("portNumber") Integer portNumber) { - if (portNumber == null) portNumber = defaultPort; - return startMockServer(portNumber); - } - - - /** - * Stop the wiremock server - * @return - */ - @GET - @Path("/stop") - @Produces("application/json") - public synchronized Response stop() { - if (wireMockServer.isRunning()) { - wireMockServer.stop(); - started = false; - return Response.status(200).entity("Stopped Mock Server in port ").build(); - } - return Response.status(200).entity("Mock Server is not running").build(); - } - - - /** - * Return list of mock properties - * @return - */ - @GET - @Path("/properties") - @Produces("application/json") - public Response getProperties() { - return Response.status(200).entity(mockProperties).build(); - } - - /** - * Update a particular mock property at run-time - * @param name - * @param value - * @return - */ - @POST - @Path("/properties/{name}/{value}") - public Response updateProperties(@PathParam("name") String name, @PathParam("value") String value) { - if (mockProperties.size() > 50) return Response.serverError().build(); - mockProperties.put(name, value); - return Response.status(200).build(); - } - - /** - * Reset all stubs - * @return - */ - @GET - @Path("/reset") - @Produces("application/json") - public Response reset() { - WireMock.reset(); - return Response.status(200).entity("Wiremock stubs are reset").build(); - } - - - /** - * Setup a stub selectively - * Prior to use, make sure that stub method is available in StubResponse class - * @param methodName - * @return - */ - - // commenting for now until we figure out a way to use new StubResponse classes to setupStubs -// @GET -// @Path("/stub/{methodName}") -// @Produces("application/json") -// public Response setupStub(@PathParam("methodName") String methodName) { -// -// @SuppressWarnings("rawtypes") -// Class params[] = {}; -// Object paramsObj[] = {}; -// -// try { -// Method thisMethod = StubResponse.class.getDeclaredMethod(methodName, params); -// try { -// thisMethod.invoke(StubResponse.class, paramsObj); -// } catch (IllegalAccessException | IllegalArgumentException -// | InvocationTargetException e) { -// return Response.status(200).entity("Error invoking " + methodName ).build(); -// } -// } catch (NoSuchMethodException | SecurityException e) { -// return Response.status(200).entity("Stub " + methodName + " not found...").build(); -// } -// return Response.status(200).entity("Successfully invoked " + methodName).build(); -// } - - - public static Map<String,String> getMockProperties(){ - return mockProperties; - } -} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/SDNCAdapterAsyncTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/SDNCAdapterAsyncTransformer.java deleted file mode 100644 index 8515307394..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/SDNCAdapterAsyncTransformer.java +++ /dev/null @@ -1,156 +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.mock; - -import javax.ws.rs.core.UriBuilder; - -import org.onap.so.client.HttpClient; -import org.onap.so.client.HttpClientFactory; -import org.onap.so.utils.TargetEntity; - -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.common.BinaryFile; -import com.github.tomakehurst.wiremock.common.FileSource; -import com.github.tomakehurst.wiremock.extension.Parameters; -import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer; -import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.http.ResponseDefinition; - -/** - * - * Simulates SDNC Adapter Callback response - * - */ -public class SDNCAdapterAsyncTransformer extends ResponseDefinitionTransformer { - - private String syncResponse; - private String callbackResponseWrapper; - - public SDNCAdapterAsyncTransformer() { - syncResponse = FileUtil.readResourceFile("__files/StandardSDNCSynchResponse.xml"); - callbackResponseWrapper = FileUtil.readResourceFile("__files/sdncCallbackSoapWrapper.xml"); - } - - @Override - public String getName() { - return "sdnc-adapter-vf-module-assign"; - } - - /** - * Grab the incoming request xml,extract the request id and replace the stub response with the incoming request id - * so that callback response can be correlated - * - * Mock Resource can be used to add dynamic properties. If sdnc_delay is not in the list by default waits for 300ms before - * the callback response is sent - */ - @Override - public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, - FileSource fileSource, Parameters parameters) { - - String requestBody = request.getBodyAsString(); - - String callbackUrl = requestBody.substring(requestBody.indexOf("<sdncadapter:CallbackUrl>")+25, requestBody.indexOf("</sdncadapter:CallbackUrl>")); - String requestId = requestBody.substring(requestBody.indexOf("<sdncadapter:RequestId>")+23, requestBody.indexOf("</sdncadapter:RequestId>")); - - System.out.println("responseDefinition: " + responseDefinition); - - // For this mock, the mapped response body is the Async callback (since the sync response is generic for all requests) - String sdncResponse = responseDefinition.getBody(); - System.out.println("sdncResponse:" + sdncResponse); - - if (sdncResponse == null) { - // Body wasn't specified. Check for a body file - String bodyFileName = responseDefinition.getBodyFileName(); - System.out.println("bodyFileName" + bodyFileName); - if (bodyFileName != null) { - System.out.println("fileSource Class: " + fileSource.getClass().getName()); - BinaryFile bodyFile = fileSource.getBinaryFileNamed(bodyFileName); - byte[] responseFile = bodyFile.readContents(); - sdncResponse = new String(responseFile); - System.out.println("sdncResponse(2):" + sdncResponse); - } - } - - // Next substitute the SDNC response into the callbackResponse (SOAP wrapper). - // Also, replace the request ID wherever it appears - String callbackResponse = callbackResponseWrapper.replace("SDNC_RESPONSE_DATA", sdncResponse).replaceAll("SDNC_REQUEST_ID", requestId); - - Object sdncDelay = MockResource.getMockProperties().get("sdnc_delay"); - int delay = 2000; - if (sdncDelay != null) { - delay = Integer.parseInt(sdncDelay.toString()); - } - - //Kick off callback thread - System.out.println("callback Url:" + callbackUrl + ":delay:" + delay); - CallbackResponseThread calbackResponseThread = new CallbackResponseThread(callbackUrl,callbackResponse, delay); - calbackResponseThread.start(); - - //return 200 OK with empty body - return ResponseDefinitionBuilder - .like(responseDefinition).but() - .withStatus(200).withBody(syncResponse).withHeader("Content-Type", "text/xml") - .build(); - } - - @Override - public boolean applyGlobally() { - return false; - } - - /** - * - * Callback response thread which sends the callback response asynchronously - * - */ - private class CallbackResponseThread extends Thread { - - private String callbackUrl; - private String payLoad; - private int delay; - - public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { - this.callbackUrl = callbackUrl; - this.payLoad = payLoad; - this.delay = delay; - } - - public void run () { - try { - //Delay sending callback response - sleep(delay); - } catch (InterruptedException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - try { - HttpClient client = new HttpClientFactory().newTextXmlClient( - UriBuilder.fromUri(callbackUrl).build().toURL(), - TargetEntity.SDNC_ADAPTER); - client.post(payLoad); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } -} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/SDNCAdapterMockTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/SDNCAdapterMockTransformer.java deleted file mode 100644 index 11788be76e..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/SDNCAdapterMockTransformer.java +++ /dev/null @@ -1,148 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.mock; - -import javax.ws.rs.core.UriBuilder; - -import org.onap.so.client.HttpClient; -import org.onap.so.client.HttpClientFactory; -import org.onap.so.utils.TargetEntity; - -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.common.FileSource; -import com.github.tomakehurst.wiremock.extension.Parameters; -import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer; -import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.http.ResponseDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Simulates SDNC Adapter Callback response - * - */ -public class SDNCAdapterMockTransformer extends ResponseDefinitionTransformer { - - private static final Logger logger = LoggerFactory.getLogger(SDNCAdapterMockTransformer.class); - private String callbackResponse; - private String requestId; - - public SDNCAdapterMockTransformer() { - callbackResponse = FileUtil.readResourceFile("__files/sdncSimResponse.xml"); - } - - public SDNCAdapterMockTransformer(String requestId) { - this.requestId = requestId; - } - - @Override - public String getName() { - return "sdnc-adapter-transformer"; - } - - /** - * Grab the incoming request xml,extract the request id and replace the stub response with the incoming request id - * so that callback response can be correlated - * - * Mock Resource can be used to add dynamic properties. If sdnc_delay is not in the list by default waits for 300ms before - * the callback response is sent - */ - @Override - public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, - FileSource fileSource, Parameters parameters) { - String requestBody = request.getBodyAsString(); - - String callbackUrl = requestBody.substring(requestBody.indexOf("<sdncadapter:CallbackUrl>")+25, requestBody.indexOf("</sdncadapter:CallbackUrl>")); - String requestId = requestBody.substring(requestBody.indexOf("<sdncadapter:RequestId>")+23, requestBody.indexOf("</sdncadapter:RequestId>")); - - callbackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); - logger.info("callbackResponse:" + callbackResponse); - - if (this.requestId != null) { - callbackResponse = callbackResponse.replace(this.requestId, requestId); - } else { - callbackResponse = callbackResponse.replace("testRequestId", requestId); - } - - - Object sdncDelay = MockResource.getMockProperties().get("sdnc_delay"); - int delay = 300; - if (sdncDelay != null) { - delay = Integer.parseInt(sdncDelay.toString()); - } - - //Kick off callback thread - logger.info("callback Url:" + callbackUrl + ":delay:" + delay); - CallbackResponseThread calbackResponseThread = new CallbackResponseThread(callbackUrl,callbackResponse, delay); - calbackResponseThread.start(); - - //return 200 OK with empty body - return ResponseDefinitionBuilder - .like(responseDefinition).but() - .withStatus(200).withBody("").withHeader("Content-Type", "text/xml") - .build(); - } - - @Override - public boolean applyGlobally() { - return false; - } - - /** - * - * Callback response thread which sends the callback response asynchronously - * - */ - private class CallbackResponseThread extends Thread { - - private String callbackUrl; - private String payLoad; - private int delay; - - public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { - this.callbackUrl = callbackUrl; - this.payLoad = payLoad; - this.delay = delay; - } - - public void run () { - try { - //Delay sending callback response - sleep(delay); - } catch (InterruptedException e1) { - logger.debug("Exception :", e1); - } - logger.debug("Sending callback response:" + callbackUrl); - try { - HttpClient client = new HttpClientFactory().newTextXmlClient( - UriBuilder.fromUri(callbackUrl).build().toURL(), - TargetEntity.SDNC_ADAPTER); - client.post(payLoad); - } catch (Exception e) { - logger.debug("Exception :", e); - } - } - - } -} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/SDNCAdapterNetworkTopologyMockTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/SDNCAdapterNetworkTopologyMockTransformer.java deleted file mode 100644 index 344c3b521d..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/SDNCAdapterNetworkTopologyMockTransformer.java +++ /dev/null @@ -1,141 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.mock; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; - -import org.onap.so.client.HttpClient; -import org.onap.so.client.HttpClientFactory; -import org.onap.so.utils.TargetEntity; - -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.common.FileSource; -import com.github.tomakehurst.wiremock.extension.Parameters; -import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer; -import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.http.ResponseDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class SDNCAdapterNetworkTopologyMockTransformer extends ResponseDefinitionTransformer { - - private static final Logger logger = LoggerFactory.getLogger(SDNCAdapterNetworkTopologyMockTransformer.class); - - private String callbackResponse; - private String requestId; - - public SDNCAdapterNetworkTopologyMockTransformer() { - callbackResponse = ""; // FileUtil.readResourceFile("__files/sdncDeleteNetworkTopologySimResponse.xml"); - } - - public SDNCAdapterNetworkTopologyMockTransformer(String requestId) { - this.requestId = requestId; - } - - @Override - public String getName() { - return "network-topology-operation-transformer"; - } - - @Override - public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, FileSource fileSource, Parameters parameters) { - String requestBody = request.getBodyAsString(); - - String callbackUrl = requestBody.substring(requestBody.indexOf("<sdncadapter:CallbackUrl>")+25, requestBody.indexOf("</sdncadapter:CallbackUrl>")); - String requestId = requestBody.substring(requestBody.indexOf("<sdncadapter:RequestId>")+23, requestBody.indexOf("</sdncadapter:RequestId>")); - logger.info("request callbackUrl : " + callbackUrl); - logger.info("request requestId : " + requestId); - - logger.info("file path/name : " + responseDefinition.getBodyFileName()); - callbackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); - // extract Response responseRequestId - String responseRequestId = callbackResponse.substring(callbackResponse.indexOf("<RequestId>")+11, callbackResponse.indexOf("</RequestId>")); - logger.info("response requestId: " + responseRequestId); - logger.info("callbackResponse (before): " + callbackResponse); - callbackResponse = callbackResponse.replace(responseRequestId, requestId); - if (this.requestId != null) { - callbackResponse = callbackResponse.replace(this.requestId, requestId); - } else { - callbackResponse = callbackResponse.replace(responseRequestId, requestId); - } - logger.info("callbackResponse (after):" + callbackResponse); - - Object sdncDelay = MockResource.getMockProperties().get("sdnc_delay"); - int delay = 300; - if (sdncDelay != null) { - delay = Integer.parseInt(sdncDelay.toString()); - } - - //Kick off callback thread - logger.info("(NetworkTopologyMockTransformer) callback Url:" + callbackUrl + ":delay:" + delay); - CallbackResponseThread calbackResponseThread = new CallbackResponseThread(callbackUrl,callbackResponse, delay); - calbackResponseThread.start(); - - //return 200 OK with body - return ResponseDefinitionBuilder - .like(responseDefinition).but() - .withStatus(200).withBody(callbackResponse).withHeader("Content-Type", "text/xml") - .build(); - } - - @Override - public boolean applyGlobally() { - return false; - } - - private class CallbackResponseThread extends Thread { - - private String callbackUrl; - private String payLoad; - private int delay; - - public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { - this.callbackUrl = callbackUrl; - this.payLoad = payLoad; - this.delay = delay; - } - - public void run () { - try { - //Delay sending callback response - sleep(delay); - } catch (InterruptedException e1) { - // TODO Auto-generated catch block - logger.debug("Exception :", e1); - } - logger.debug("Sending callback response to url: {}", callbackUrl); - try { - HttpClient client = new HttpClientFactory() - .newTextXmlClient(UriBuilder.fromUri(callbackUrl).build().toURL(), TargetEntity.SDNC_ADAPTER); - Response response = client.post(payLoad); - logger.debug("Successfully posted callback? Status: {}", response.getStatus()); - } catch (Exception e) { - // TODO Auto-generated catch block - logger.debug("catch error in - request.post() "); - logger.debug("Exception :", e); - } - } - - } -} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSDNCAdapter.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSDNCAdapter.java index e0c51b794c..66dc1f9910 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSDNCAdapter.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseSDNCAdapter.java @@ -80,29 +80,6 @@ public class StubResponseSDNCAdapter { .withBodyFile(responseFile))); } - public static void mockSDNCAdapterSimulator(String responseFile) { - MockResource mockResource = new MockResource(); - mockResource.updateProperties("sdnc_delay", "300"); - stubFor(post(urlEqualTo("/SDNCAdapter")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "application/soap+xml") - .withTransformers("sdnc-adapter-transformer") - .withBodyFile(responseFile))); - } - - public static void mockSDNCAdapterSimulator(String responseFile, String requestContaining) { - MockResource mockResource = new MockResource(); - mockResource.updateProperties("sdnc_delay", "300"); - stubFor(post(urlEqualTo("/SDNCAdapter")) - .withRequestBody(containing(requestContaining)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "application/soap+xml") - .withTransformers("sdnc-adapter-transformer") - .withBodyFile(responseFile))); - } - public static void mockSDNCAdapterRest() { stubFor(post(urlEqualTo("/SDNCAdapter/v1/sdnc/services")) .willReturn(aResponse() @@ -133,17 +110,4 @@ public class StubResponseSDNCAdapter { .withHeader("Content-Type", "application/json"))); } - public static void mockSDNCAdapterTopology(String responseFile, String requestContaining) { - MockResource mockResource = new MockResource(); - mockResource.updateProperties("sdnc_delay", "300"); - stubFor(post(urlEqualTo("/SDNCAdapter")) - .withRequestBody(containing(requestContaining)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "text/xml") - .withTransformers("network-topology-operation-transformer") - .withBodyFile(responseFile))); - } - - } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseVNFAdapter.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseVNFAdapter.java index 91ecbd23b4..75283515af 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseVNFAdapter.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/StubResponseVNFAdapter.java @@ -53,29 +53,6 @@ public class StubResponseVNFAdapter { .willReturn(aResponse() .withStatus(500))); } - - public static void mockVNFAdapterTransformer(String transformer, String responseFile) { - MockResource mockResource = new MockResource(); - mockResource.updateProperties("vnf_delay", "300"); - stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "application/soap+xml") - .withTransformers(transformer) - .withBodyFile(responseFile))); - } - - public static void mockVNFAdapterTransformer(String transformer, String responseFile, String requestContaining) { - MockResource mockResource = new MockResource(); - mockResource.updateProperties("vnf_delay", "300"); - stubFor(post(urlEqualTo("/vnfs/VnfAdapterAsync")) - .withRequestBody(containing(requestContaining)) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "application/soap+xml") - .withTransformers(transformer) - .withBodyFile(responseFile))); - } public static void mockVNFPost(String vfModuleId, int statusCode, String vnfId) { stubFor(post(urlEqualTo("/services/rest/v1/vnfs" + vnfId + "/vf-modules" + vfModuleId)) diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterAsyncTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterAsyncTransformer.java deleted file mode 100644 index e190535e7e..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterAsyncTransformer.java +++ /dev/null @@ -1,167 +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.mock; - -import javax.ws.rs.core.UriBuilder; - -import org.onap.so.client.HttpClient; -import org.onap.so.client.HttpClientFactory; -import org.onap.so.utils.TargetEntity; - -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.common.BinaryFile; -import com.github.tomakehurst.wiremock.common.FileSource; -import com.github.tomakehurst.wiremock.extension.Parameters; -import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer; -import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.http.ResponseDefinition; - -/** - * - * Simulates VNF Adapter Asynch Callback response. - * This should work for any of the operations. - * - * This transformer uses the mapped message as the asynchronous response. - * By definition, the async API sends a 202 (with no body) in the sync response. - * - */ -public class VnfAdapterAsyncTransformer extends ResponseDefinitionTransformer { - - public VnfAdapterAsyncTransformer() { - } - - @Override - public String getName() { - return "vnf-adapter-async"; - } - - /** - * Grab the incoming request, extract properties to be copied to the response - * (request id, vnf id, vf module ID, message ID). Then fetch the actual response - * body from its FileSource, make the replacements. - * - * The sync response is an empty 202 response. - * The transformed mapped response file is sent asynchronously after a delay. - * - * Mock Resource can be used to add dynamic properties. If vnf_delay is not in the list by - * default waits for 5s before the callback response is sent - */ - @Override - public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, - FileSource fileSource, Parameters parameters) { - - String requestBody = request.getBodyAsString(); - - // Note: Should recognize both XML and JSON. But current BPMN uses XML. - String notificationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>")); - - String vnfId = requestBody.substring(requestBody.indexOf("<vnfId>")+7, requestBody.indexOf("</vnfId>")); - String vfModuleId = requestBody.substring(requestBody.indexOf("<vfModuleId>")+12, requestBody.indexOf("</vfModuleId>")); - String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>")); - String requestId = requestBody.substring(requestBody.indexOf("<requestId>")+11, requestBody.indexOf("</requestId>")); - - System.out.println("responseDefinition: " + responseDefinition); - - // For this mock, the mapped response body is the Async callback (since the sync response is generic for all requests) - String vnfResponse = responseDefinition.getBody(); - System.out.println("VNF Response:" + vnfResponse); - - if (vnfResponse == null) { - // Body wasn't specified. Check for a body file - String bodyFileName = responseDefinition.getBodyFileName(); - System.out.println("bodyFileName" + bodyFileName); - if (bodyFileName != null) { - System.out.println("fileSource Class: " + fileSource.getClass().getName()); - BinaryFile bodyFile = fileSource.getBinaryFileNamed(bodyFileName); - byte[] responseFile = bodyFile.readContents(); - vnfResponse = new String(responseFile); - System.out.println("vnfResponse(2):" + vnfResponse); - } - } - - // Transform the SDNC response to escape < and > - vnfResponse = vnfResponse.replaceAll ("VNF_ID", vnfId); - vnfResponse = vnfResponse.replaceAll ("VF_MODULE_ID", vfModuleId); - vnfResponse = vnfResponse.replaceAll ("REQUEST_ID", requestId); - vnfResponse = vnfResponse.replaceAll ("MESSAGE_ID", messageId); - - Object vnfDelay = MockResource.getMockProperties().get("vnf_delay"); - int delay = 5000; - if (vnfDelay != null) { - delay = Integer.parseInt(vnfDelay.toString()); - } - - //Kick off callback thread - System.out.println("notification Url:" + notificationUrl + ":delay:" + delay); - CallbackResponseThread calbackResponseThread = new CallbackResponseThread(notificationUrl,vnfResponse, delay); - calbackResponseThread.start(); - - //return 200 OK with empty body - return ResponseDefinitionBuilder - .like(responseDefinition).but() - .withStatus(202).withBody("").withHeader("Content-Type", "text/xml") - .build(); - } - - @Override - public boolean applyGlobally() { - return false; - } - - /** - * - * Callback response thread which sends the callback response asynchronously - * - */ - private class CallbackResponseThread extends Thread { - - private String callbackUrl; - private String payLoad; - private int delay; - - public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { - this.callbackUrl = callbackUrl; - this.payLoad = payLoad; - this.delay = delay; - } - - public void run () { - try { - //Delay sending callback response - sleep(delay); - } catch (InterruptedException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - try { - HttpClient client = new HttpClientFactory().newTextXmlClient( - UriBuilder.fromUri(callbackUrl).build().toURL(), - TargetEntity.VNF_ADAPTER); - client.post(payLoad); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - } -} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterCreateMockTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterCreateMockTransformer.java deleted file mode 100644 index 362d9508d3..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterCreateMockTransformer.java +++ /dev/null @@ -1,153 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.mock; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; - -import org.onap.so.client.HttpClient; -import org.onap.so.client.HttpClientFactory; -import org.onap.so.utils.TargetEntity; - -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.common.FileSource; -import com.github.tomakehurst.wiremock.extension.Parameters; -import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer; -import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.http.ResponseDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Please describe the VnfAdapterCreateMockTransformer.java class - * - */ -public class VnfAdapterCreateMockTransformer extends ResponseDefinitionTransformer { - - private static final Logger logger = LoggerFactory.getLogger(VnfAdapterCreateMockTransformer.class); - - private String notifyCallbackResponse; - private String ackResponse; - - public VnfAdapterCreateMockTransformer() { - notifyCallbackResponse = FileUtil.readResourceFile("__files/vnfAdapterMocks/vnfCreateSimResponse.xml"); // default response - } - - @Override - public String getName() { - return "vnf-adapter-create-transformer"; - } - - @Override - public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, - FileSource fileSource, Parameters parameters) { - - String requestBody = request.getBodyAsString(); - - String notficationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>")); - String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>")); - String responseMessageId = ""; - String updatedResponse = ""; - - try { - // try supplied response file (if any) - System.out.println(" Supplied fileName: " + responseDefinition.getBodyFileName()); - ackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); - notifyCallbackResponse = ackResponse; - responseMessageId = ackResponse.substring(ackResponse.indexOf("<messageId>")+11, ackResponse.indexOf("</messageId>")); - updatedResponse = ackResponse.replace(responseMessageId, messageId); - } catch (Exception ex) { - logger.debug("Exception :",ex); - System.out.println(" ******* Use default response file in '__files/vnfAdapterMocks/vnfCreateSimResponse.xml'"); - responseMessageId = notifyCallbackResponse.substring(notifyCallbackResponse.indexOf("<messageId>")+11, notifyCallbackResponse.indexOf("</messageId>")); - updatedResponse = notifyCallbackResponse.replace(responseMessageId, messageId); - } - - logger.info("response (mock) messageId : {}", responseMessageId); - logger.info("request (replacement) messageId: {}", messageId); - - logger.info("vnf Response (before): {}", notifyCallbackResponse); - logger.info("vnf Response (after): {}", updatedResponse); - - Object vnfDelay = MockResource.getMockProperties().get("vnf_delay"); - int delay = 300; - if (vnfDelay != null) { - delay = Integer.parseInt(vnfDelay.toString()); - } - - //Kick off callback thread - logger.info("VnfAdapterCreateMockTransformer notficationUrl: {} :delay: {}", notficationUrl, delay); - CallbackResponseThread callbackResponseThread = new CallbackResponseThread(notficationUrl,updatedResponse, delay); - callbackResponseThread.start(); - - return ResponseDefinitionBuilder - .like(responseDefinition).but() - .withStatus(200).withBody(updatedResponse).withHeader("Content-Type", "text/xml") - .build(); - - } - - @Override - public boolean applyGlobally() { - return false; - } - - private class CallbackResponseThread extends Thread { - - private String callbackUrl; - private String payLoad; - private int delay; - - public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { - this.callbackUrl = callbackUrl; - this.payLoad = payLoad; - this.delay = delay; - } - - @SuppressWarnings("deprecation") - public void run () { - try { - //Delay sending callback response - sleep(delay); - } catch (InterruptedException e1) { - // TODO Auto-generated catch block - logger.debug("Exception :",e1); - } - logger.debug("Sending callback response to url: {}", callbackUrl); - try { - HttpClient client = new HttpClientFactory().newTextXmlClient( - UriBuilder.fromUri(callbackUrl).build().toURL(), - TargetEntity.VNF_ADAPTER); - Response response = client.post(payLoad); - logger.debug("Successfully posted callback? Status: {}", response.getStatus()); - } catch (Exception e) { - // TODO Auto-generated catch block - logger.debug("catch error in - request.post() "); - logger.debug("Exception :", e); - } - } - - } - - -} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterDeleteMockTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterDeleteMockTransformer.java deleted file mode 100644 index b67f3dcedd..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterDeleteMockTransformer.java +++ /dev/null @@ -1,149 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.mock; - -import javax.ws.rs.core.UriBuilder; - -import org.onap.so.client.HttpClient; -import org.onap.so.client.HttpClientFactory; -import org.onap.so.utils.TargetEntity; - -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.common.FileSource; -import com.github.tomakehurst.wiremock.extension.Parameters; -import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer; -import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.http.ResponseDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Please describe the VnfAdapterCreateMockTransformer.java class - * - */ -public class VnfAdapterDeleteMockTransformer extends ResponseDefinitionTransformer { - - private static final Logger logger = LoggerFactory.getLogger(VnfAdapterDeleteMockTransformer.class); - - private String notifyCallbackResponse; - private String ackResponse; - - public VnfAdapterDeleteMockTransformer() { - notifyCallbackResponse = FileUtil.readResourceFile("__files/vnfAdapterMocks/vnfDeleteSimResponse.xml"); - } - - @Override - public String getName() { - return "vnf-adapter-delete-transformer"; - } - - @Override - public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, - FileSource fileSource, Parameters parameters) { - - String requestBody = request.getBodyAsString(); - - String notficationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>")); - String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>")); - String responseMessageId = ""; - String updatedResponse = ""; - - try { - // try supplied response file (if any) - logger.info(" Supplied fileName: {}", responseDefinition.getBodyFileName()); - ackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); - notifyCallbackResponse = ackResponse; - responseMessageId = ackResponse.substring(ackResponse.indexOf("<messageId>")+11, ackResponse.indexOf("</messageId>")); - updatedResponse = ackResponse.replace(responseMessageId, messageId); - } catch (Exception ex) { - logger.debug("Exception :",ex); - logger.info(" ******* Use default response file in '__files/vnfAdapterMocks/vnfDeleteSimResponse.xml'"); - responseMessageId = notifyCallbackResponse.substring(notifyCallbackResponse.indexOf("<messageId>")+11, notifyCallbackResponse.indexOf("</messageId>")); - updatedResponse = notifyCallbackResponse.replace(responseMessageId, messageId); - } - - logger.info("response (mock) messageId : {}", responseMessageId); - logger.info("request (replacement) messageId: {}", messageId); - - logger.info("vnf Response (before):{}", notifyCallbackResponse); - logger.info("vnf Response (after):{}", updatedResponse); - - Object vnfDelay = MockResource.getMockProperties().get("vnf_delay"); - int delay = 300; - if (vnfDelay != null) { - delay = Integer.parseInt(vnfDelay.toString()); - } - - //Kick off callback thread - logger.info("VnfAdapterDeleteMockTransformer notficationUrl: {} :delay: {}", notficationUrl, delay); - CallbackResponseThread callbackResponseThread = new CallbackResponseThread(notficationUrl,updatedResponse, delay); - callbackResponseThread.start(); - - return ResponseDefinitionBuilder - .like(responseDefinition).but() - .withStatus(200).withBody(updatedResponse).withHeader("Content-Type", "text/xml") - .build(); - - } - - @Override - public boolean applyGlobally() { - return false; - } - - private class CallbackResponseThread extends Thread { - - private String callbackUrl; - private String payLoad; - private int delay; - - public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { - this.callbackUrl = callbackUrl; - this.payLoad = payLoad; - this.delay = delay; - } - - @SuppressWarnings("deprecation") - public void run () { - try { - //Delay sending callback response - sleep(delay); - } catch (InterruptedException e1) { - // TODO Auto-generated catch block - logger.debug("Exception :",e1); - } - - try { - HttpClient client = new HttpClientFactory().newTextXmlClient( - UriBuilder.fromUri(callbackUrl).build().toURL(), - TargetEntity.VNF_ADAPTER); - client.post(payLoad); - } catch (Exception e) { - // TODO Auto-generated catch block - logger.info("catch error in - request.post() "); - logger.debug("Exception :",e); - } - } - - } -} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterQueryMockTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterQueryMockTransformer.java deleted file mode 100644 index 48ced35810..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterQueryMockTransformer.java +++ /dev/null @@ -1,158 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.mock; - - -import javax.ws.rs.core.UriBuilder; - -import org.onap.so.client.HttpClient; -import org.onap.so.client.HttpClientFactory; -import org.onap.so.utils.TargetEntity; - -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.common.FileSource; -import com.github.tomakehurst.wiremock.extension.Parameters; -import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer; -import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.http.ResponseDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Please describe the VnfAdapterQueryMockTransformer.java class - * - */ - - -public class VnfAdapterQueryMockTransformer extends ResponseDefinitionTransformer{ - - private static final Logger logger = LoggerFactory.getLogger(VnfAdapterQueryMockTransformer - .class); - - private String notifyCallbackResponse; - private String ackResponse; - private String messageId; - - public VnfAdapterQueryMockTransformer() { - notifyCallbackResponse = FileUtil.readResourceFile("__files/vnfAdapterMocks/vnfQuerySimResponse.xml"); - } - - public VnfAdapterQueryMockTransformer(String messageId) { - this.messageId = messageId; - } - - @Override - public String getName() { - return "vnf-adapter-query-transformer"; - } - - @Override - public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, - FileSource fileSource, Parameters parameters) { - - String requestBody = request.getBodyAsString(); - - String notficationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>")); - String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>")); - - String responseMessageId = ""; - String updatedResponse = ""; - - try { - // try supplied response file (if any) - logger.info(" Supplied fileName: {}", responseDefinition.getBodyFileName()); - ackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); - notifyCallbackResponse = ackResponse; - responseMessageId = ackResponse.substring(ackResponse.indexOf("<messageId>")+11, ackResponse.indexOf("</messageId>")); - updatedResponse = ackResponse.replace(responseMessageId, messageId); - } catch (Exception ex) { - logger.debug("Exception :",ex); - logger.info(" ******* Use default response file in '__files/vnfAdapterMocks/vnfQuerySimResponse.xml'"); - responseMessageId = notifyCallbackResponse.substring(notifyCallbackResponse.indexOf("<messageId>")+11, notifyCallbackResponse.indexOf("</messageId>")); - updatedResponse = notifyCallbackResponse.replace(responseMessageId, messageId); - } - - logger.info("response (mock) messageId : {}", responseMessageId); - logger.info("request (replacement) messageId: {}", messageId); - - logger.info("vnf Response (before):{}", notifyCallbackResponse); - logger.info("vnf Response (after):{}", updatedResponse); - - - Object vnfDelay = MockResource.getMockProperties().get("vnf_delay"); - int delay = 300; - if (vnfDelay != null) { - delay = Integer.parseInt(vnfDelay.toString()); - } - - //Kick off callback thread - logger.info("VnfAdapterQueryMockTransformer notficationUrl: {}:delay: {}", notficationUrl, delay); - CallbackResponseThread callbackResponseThread = new CallbackResponseThread(notficationUrl,updatedResponse, delay); - logger.info("Inside Callback" ); - callbackResponseThread.start(); - - return ResponseDefinitionBuilder - .like(responseDefinition).but() - .withStatus(200).withBody(updatedResponse).withHeader("Content-Type", "text/xml") - .build(); - } - - @Override - public boolean applyGlobally() { - return false; - } - - private class CallbackResponseThread extends Thread { - - private String callbackUrl; - private String payLoad; - private int delay; - - public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { - this.callbackUrl = callbackUrl; - this.payLoad = payLoad; - this.delay = delay; - } - - public void run () { - try { - //Delay sending callback response - sleep(delay); - } catch (InterruptedException e1) { - logger.debug("Exception :",e1); - } - - try { - HttpClient client = new HttpClientFactory().newTextXmlClient( - UriBuilder.fromUri(callbackUrl).build().toURL(), - TargetEntity.VNF_ADAPTER); - client.post(payLoad); - } catch (Exception e) { - logger.debug("Exception :",e); - } - } - - } - - -} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterRollbackMockTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterRollbackMockTransformer.java deleted file mode 100644 index edf05422d1..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterRollbackMockTransformer.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.mock; - -import javax.ws.rs.core.UriBuilder; - -import org.onap.so.client.HttpClient; -import org.onap.so.client.HttpClientFactory; -import org.onap.so.utils.TargetEntity; - -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.common.FileSource; -import com.github.tomakehurst.wiremock.extension.Parameters; -import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer; -import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.http.ResponseDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Please describe the VnfAdapterCreateMockTransformer.java class - * - */ -public class VnfAdapterRollbackMockTransformer extends ResponseDefinitionTransformer { - - private static final Logger logger = LoggerFactory.getLogger(VnfAdapterRollbackMockTransformer.class); - - private String notifyCallbackResponse; - private String ackResponse; - private String messageId; - - public VnfAdapterRollbackMockTransformer() { - notifyCallbackResponse = FileUtil.readResourceFile("__files/vnfAdapterMocks/vnfRollbackSimResponse.xml"); - } - - public VnfAdapterRollbackMockTransformer(String messageId) { - this.messageId = messageId; - } - - @Override - public String getName() { - return "vnf-adapter-rollback-transformer"; - } - - @Override - public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, - FileSource fileSource, Parameters parameters) { - - String requestBody = request.getBodyAsString(); - - String notficationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>")); - String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>")); - String responseMessageId = ""; - String updatedResponse = ""; - - try { - // try supplied response file (if any) - logger.info(" Supplied fileName: {}", responseDefinition.getBodyFileName()); - ackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); - notifyCallbackResponse = ackResponse; - responseMessageId = ackResponse.substring(ackResponse.indexOf("<messageId>")+11, ackResponse.indexOf("</messageId>")); - updatedResponse = ackResponse.replace(responseMessageId, messageId); - } catch (Exception ex) { - logger.debug("Exception :",ex); - logger.info(" ******* Use default response file in '__files/vnfAdapterMocks/vnfRollbackSimResponse.xml'"); - responseMessageId = notifyCallbackResponse.substring(notifyCallbackResponse.indexOf("<messageId>")+11, notifyCallbackResponse.indexOf("</messageId>")); - updatedResponse = notifyCallbackResponse.replace(responseMessageId, messageId); - } - - logger.info("response (mock) messageId : {}", responseMessageId); - logger.info("request (replacement) messageId: {}", messageId); - - logger.info("vnf Response (before):{}", notifyCallbackResponse); - logger.info("vnf Response (after):{}", updatedResponse); - - Object vnfDelay = MockResource.getMockProperties().get("vnf_delay"); - int delay = 300; - if (vnfDelay != null) { - delay = Integer.parseInt(vnfDelay.toString()); - } - - //Kick off callback thread - logger.info("VnfAdapterRollbackMockTransformer notficationUrl: {} :delay: {}", notficationUrl, delay); - CallbackResponseThread callbackResponseThread = new CallbackResponseThread(notficationUrl,updatedResponse, delay); - callbackResponseThread.start(); - - return ResponseDefinitionBuilder - .like(responseDefinition).but() - .withStatus(200).withBody(updatedResponse).withHeader("Content-Type", "text/xml") - .build(); - - } - - @Override - public boolean applyGlobally() { - return false; - } - - private class CallbackResponseThread extends Thread { - - private String callbackUrl; - private String payLoad; - private int delay; - - public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { - this.callbackUrl = callbackUrl; - this.payLoad = payLoad; - this.delay = delay; - } - - public void run () { - try { - //Delay sending callback response - sleep(delay); - } catch (InterruptedException e1) { - logger.debug("Exception :",e1); - } - - try { - HttpClient client = new HttpClientFactory().newTextXmlClient( - UriBuilder.fromUri(callbackUrl).build().toURL(), - TargetEntity.VNF_ADAPTER); - client.post(payLoad); - } catch (Exception e) { - logger.info("catch error in - request.post() "); - logger.debug("Exception :", e); - } - } - - } -} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterUpdateMockTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterUpdateMockTransformer.java deleted file mode 100644 index 5693877574..0000000000 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/VnfAdapterUpdateMockTransformer.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF 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.mock; - -import javax.ws.rs.core.UriBuilder; - -import org.onap.so.client.HttpClient; -import org.onap.so.client.HttpClientFactory; -import org.onap.so.utils.TargetEntity; - -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.common.FileSource; -import com.github.tomakehurst.wiremock.extension.Parameters; -import com.github.tomakehurst.wiremock.extension.ResponseDefinitionTransformer; -import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.http.ResponseDefinition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Please describe the VnfAdapterUpdateMockTransformer.java class - * - */ -public class VnfAdapterUpdateMockTransformer extends ResponseDefinitionTransformer { - - private static final Logger logger = LoggerFactory.getLogger(VnfAdapterUpdateMockTransformer.class); - - private String notifyCallbackResponse; - private String requestId; - private String ackResponse; - - public VnfAdapterUpdateMockTransformer() { - notifyCallbackResponse = FileUtil.readResourceFile("vnfAdapter/vnfUpdateSimResponse.xml"); - } - - public VnfAdapterUpdateMockTransformer(String requestId) { - this.requestId = requestId; - } - - @Override - public String getName() { - return "vnf-adapter-update-transformer"; - } - - @Override - public ResponseDefinition transform(Request request, ResponseDefinition responseDefinition, - FileSource fileSource, Parameters parameters) { - - String requestBody = request.getBodyAsString(); - - String notficationUrl = requestBody.substring(requestBody.indexOf("<notificationUrl>")+17, requestBody.indexOf("</notificationUrl>")); - String messageId = requestBody.substring(requestBody.indexOf("<messageId>")+11, requestBody.indexOf("</messageId>")); - String responseMessageId = ""; - String updatedResponse = ""; - - try { - // try supplied response file (if any) - logger.info(" Supplied fileName: {}", responseDefinition.getBodyFileName()); - ackResponse = FileUtil.readResourceFile("__files/" + responseDefinition.getBodyFileName()); - notifyCallbackResponse = ackResponse; - responseMessageId = ackResponse.substring(ackResponse.indexOf("<messageId>")+11, ackResponse.indexOf("</messageId>")); - updatedResponse = ackResponse.replace(responseMessageId, messageId); - } catch (Exception ex) { - logger.debug("Exception :",ex); - logger.info(" ******* Use default response file in 'vnfAdapter/vnfUpdateSimResponse.xml'"); - responseMessageId = notifyCallbackResponse.substring(notifyCallbackResponse.indexOf("<messageId>")+11, notifyCallbackResponse.indexOf("</messageId>")); - updatedResponse = notifyCallbackResponse.replace(responseMessageId, messageId); - } - - logger.info("response (mock) messageId : {}", responseMessageId); - logger.info("request (replacement) messageId: {}", messageId); - - logger.info("vnf Response (before):{}", notifyCallbackResponse); - logger.info("vnf Response (after):{}", updatedResponse); - - Object vnfDelay = MockResource.getMockProperties().get("vnf_delay"); - int delay = 300; - if (vnfDelay != null) { - delay = Integer.parseInt(vnfDelay.toString()); - } - - //Kick off callback thread - logger.info("VnfAdapterUpdateMockTransformer notficationUrl: {} :delay: {}", notficationUrl, delay); - CallbackResponseThread callbackResponseThread = new CallbackResponseThread(notficationUrl,updatedResponse, delay); - callbackResponseThread.start(); - - return ResponseDefinitionBuilder - .like(responseDefinition).but() - .withStatus(200).withBody(updatedResponse).withHeader("Content-Type", "text/xml") - .build(); - - } - - @Override - public boolean applyGlobally() { - return false; - } - - private class CallbackResponseThread extends Thread { - - private String callbackUrl; - private String payLoad; - private int delay; - - public CallbackResponseThread(String callbackUrl, String payLoad, int delay) { - this.callbackUrl = callbackUrl; - this.payLoad = payLoad; - this.delay = delay; - } - - public void run () { - try { - //Delay sending callback response - sleep(delay); - } catch (InterruptedException e1) { - logger.debug("Exception :", e1); - } - - try { - HttpClient client = new HttpClientFactory().newTextXmlClient( - UriBuilder.fromUri(callbackUrl).build().toURL(), - TargetEntity.VNF_ADAPTER); - client.post(payLoad); - } catch (Exception e) { - logger.info("catch error in - request.post() "); - logger.debug("Exception :", e); - } - } - - } -} - diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java index bc41b168ef..5de0903d65 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/servicedecomposition/ExtractPojosForBBTest.java @@ -120,30 +120,29 @@ public class ExtractPojosForBBTest extends BaseTest{ customer.getServiceSubscription().getServiceInstances().add(serviceInstancePend); gBBInput.setCustomer(customer); - ServiceInstance extractServPend = extractPojos.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, "abc"); + ServiceInstance extractServPend = extractPojos.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); assertEquals(extractServPend.getServiceInstanceId(), serviceInstancePend.getServiceInstanceId()); - GenericVnf extractVnfPend = extractPojos.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, "abc"); + GenericVnf extractVnfPend = extractPojos.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); assertEquals(extractVnfPend.getVnfId(), vnfPend.getVnfId()); - L3Network extractNetworkPend = extractPojos.extractByKey(execution, ResourceKey.NETWORK_ID, "abc"); + L3Network extractNetworkPend = extractPojos.extractByKey(execution, ResourceKey.NETWORK_ID); assertEquals(extractNetworkPend.getNetworkId(), networkPend.getNetworkId()); - VolumeGroup extractVolumeGroupPend = extractPojos.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, "abc"); + VolumeGroup extractVolumeGroupPend = extractPojos.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); assertEquals(extractVolumeGroupPend.getVolumeGroupId(), volumeGroupPend.getVolumeGroupId()); AllottedResource extractallotedResourcePend = extractPojos.extractByKey(execution, - ResourceKey.ALLOTTED_RESOURCE_ID, "abc"); + ResourceKey.ALLOTTED_RESOURCE_ID); assertEquals(extractallotedResourcePend.getId(), allotedResourcePend.getId()); - Configuration extractConfigurationPend = extractPojos.extractByKey(execution, ResourceKey.CONFIGURATION_ID, - "abc"); + Configuration extractConfigurationPend = extractPojos.extractByKey(execution, ResourceKey.CONFIGURATION_ID); assertEquals(extractConfigurationPend.getConfigurationId(), configurationPend.getConfigurationId()); - VpnBinding extractVpnBinding = extractPojos.extractByKey(execution, ResourceKey.VPN_ID, "abc"); + VpnBinding extractVpnBinding = extractPojos.extractByKey(execution, ResourceKey.VPN_ID); assertEquals(extractVpnBinding.getVpnId(), vpnBinding.getVpnId()); - VfModule extractVfModulePend = extractPojos.extractByKey(execution, ResourceKey.VF_MODULE_ID, "abc"); + VfModule extractVfModulePend = extractPojos.extractByKey(execution, ResourceKey.VF_MODULE_ID); assertEquals(extractVfModulePend.getVfModuleId(), vfModulePend.getVfModuleId()); - VpnBondingLink extractVpnBondingLinkPend = extractPojos.extractByKey(execution, ResourceKey.VPN_BONDING_LINK_ID, "testVpnBondingLink"); + VpnBondingLink extractVpnBondingLinkPend = extractPojos.extractByKey(execution, ResourceKey.VPN_BONDING_LINK_ID); assertEquals(extractVpnBondingLinkPend.getVpnBondingLinkId(), vpnBondingLinkPend.getVpnBondingLinkId()); - InstanceGroup extractInstanceGroupPend = extractPojos.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID, "test-instance-group-1"); + InstanceGroup extractInstanceGroupPend = extractPojos.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID); assertEquals(instanceGroupPend.getId(), extractInstanceGroupPend.getId()); } @@ -157,7 +156,7 @@ public class ExtractPojosForBBTest extends BaseTest{ customer.getServiceSubscription().getServiceInstances().add(serviceInstance); gBBInput.setCustomer(customer); - extractPojos.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, "abc"); + extractPojos.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } @Test @@ -169,7 +168,7 @@ public class ExtractPojosForBBTest extends BaseTest{ ServiceInstance serviceInstance = new ServiceInstance(); customer.getServiceSubscription().getServiceInstances().add(serviceInstance); gBBInput.setCustomer(customer); - extractPojos.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, "bbb"); + extractPojos.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); } @Test @@ -181,7 +180,7 @@ public class ExtractPojosForBBTest extends BaseTest{ ServiceInstance serviceInstance = new ServiceInstance(); customer.getServiceSubscription().getServiceInstances().add(serviceInstance); gBBInput.setCustomer(customer); - extractPojos.extractByKey(execution, ResourceKey.VF_MODULE_ID, "bbb"); + extractPojos.extractByKey(execution, ResourceKey.VF_MODULE_ID); } @Test @@ -193,7 +192,7 @@ public class ExtractPojosForBBTest extends BaseTest{ ServiceInstance serviceInstance = new ServiceInstance(); customer.getServiceSubscription().getServiceInstances().add(serviceInstance); gBBInput.setCustomer(customer); - extractPojos.extractByKey(execution, ResourceKey.CONFIGURATION_ID, "bbb"); + extractPojos.extractByKey(execution, ResourceKey.CONFIGURATION_ID); } @Test public void allotedError() throws BBObjectNotFoundException { @@ -204,7 +203,7 @@ public class ExtractPojosForBBTest extends BaseTest{ ServiceInstance serviceInstance = new ServiceInstance(); customer.getServiceSubscription().getServiceInstances().add(serviceInstance); gBBInput.setCustomer(customer); - extractPojos.extractByKey(execution, ResourceKey.ALLOTTED_RESOURCE_ID, "bbb"); + extractPojos.extractByKey(execution, ResourceKey.ALLOTTED_RESOURCE_ID); } @Test public void vpnBindingError() throws BBObjectNotFoundException { @@ -214,7 +213,7 @@ public class ExtractPojosForBBTest extends BaseTest{ ServiceInstance serviceInstance = new ServiceInstance(); customer.getServiceSubscription().getServiceInstances().add(serviceInstance); gBBInput.setCustomer(customer); - extractPojos.extractByKey(execution, ResourceKey.VPN_ID, "bbb"); + extractPojos.extractByKey(execution, ResourceKey.VPN_ID); } @Test @@ -225,6 +224,6 @@ public class ExtractPojosForBBTest extends BaseTest{ ServiceInstance serviceInstance = new ServiceInstance(); customer.getServiceSubscription().getServiceInstances().add(serviceInstance); gBBInput.setCustomer(customer); - extractPojos.extractByKey(execution, ResourceKey.VPN_BONDING_LINK_ID, "bbb"); + extractPojos.extractByKey(execution, ResourceKey.VPN_BONDING_LINK_ID); } } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtilsTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtilsTest.java new file mode 100644 index 0000000000..b2812d9bfb --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtilsTest.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.client.cds; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.InjectMocks; +import org.onap.so.client.cds.beans.AbstractCDSPropertiesBean; + +@RunWith(JUnit4.class) +public class AbstractCDSProcessingBBUtilsTest { + @InjectMocks + private AbstractCDSProcessingBBUtils abstractCDSProcessingBBUtils = new AbstractCDSProcessingBBUtils(); + @InjectMocks + AbstractCDSPropertiesBean abstractCDSPropertiesBean = new AbstractCDSPropertiesBean(); + + @Test + public void preProcessRequestTest() throws Exception { + String requestObject = "{\"config-assign-request\":{\"resolution-key\":\"resolutionKey\", \"config-assign-properties\":{\"service-instance-id\":\"serviceInstanceId\", \"vnf-id\":\"vnfId\", \"vnf-name\":\"vnfName\", \"service-model-uuid\":\"serviceModelUuid\", \"vnf-customization-uuid\":\"vnfCustomizationUuid\",\"Instance1\":\"Instance1Value\",\"Instance2\":\"Instance2Value\",\"Param3\":\"Param3Value\"}}}"; + String blueprintName = "blueprintName"; + String blueprintVersion = "blueprintVersion"; + String actionName = "actionName"; + String mode = "mode"; + String requestId = "123456"; + String originatorId = "originatorId"; + String subRequestId = UUID.randomUUID().toString(); + + abstractCDSPropertiesBean.setActionName(actionName); + abstractCDSPropertiesBean.setBlueprintName(blueprintName); + abstractCDSPropertiesBean.setBlueprintVersion(blueprintVersion); + abstractCDSPropertiesBean.setMode(mode); + abstractCDSPropertiesBean.setOriginatorId(originatorId); + abstractCDSPropertiesBean.setRequestId(requestId); + abstractCDSPropertiesBean.setRequestObject(requestObject); + abstractCDSPropertiesBean.setSubRequestId(subRequestId); + + DelegateExecution execution = mock(DelegateExecution.class); + when(execution.getVariable("executionObject")).thenReturn(abstractCDSPropertiesBean); + + abstractCDSProcessingBBUtils.constructExecutionServiceInputObject(execution); + assertTrue(true); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnfTest.java new file mode 100644 index 0000000000..c294124e69 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForPnfTest.java @@ -0,0 +1,70 @@ +package org.onap.so.client.cds.beans; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +public class ConfigAssignPropertiesForPnfTest { + ConfigAssignPropertiesForPnf configAssignPropertiesForPnf = new ConfigAssignPropertiesForPnf(); + private Map<String, Object> userParam = new HashMap<String, Object>(); + private String serviceInstanceId; + private String pnfId; + private String pnfName; + private String serviceModelUuid; + private String pnfCustomizationUuid; + + @Test + public final void testConfigDeployPropertiesForPnfTest() { + userParam.put("Instance1", "instance1value"); + userParam.put("Instance2", "instance2value"); + configAssignPropertiesForPnf.setPnfCustomizationUuid("pnf-customization-uuid"); + configAssignPropertiesForPnf.setPnfId("pnf-id"); + configAssignPropertiesForPnf.setPnfName("pnf-name"); + configAssignPropertiesForPnf.setServiceInstanceId("service-instance-id"); + configAssignPropertiesForPnf.setServiceModelUuid("service-model-uuid"); + configAssignPropertiesForPnf.setUserParam("Instance1", "instance1value"); + configAssignPropertiesForPnf.setUserParam("Instance2", "instance2value"); + + assertNotNull(configAssignPropertiesForPnf.getPnfCustomizationUuid()); + assertNotNull(configAssignPropertiesForPnf.getPnfId()); + assertNotNull(configAssignPropertiesForPnf.getPnfName()); + assertNotNull(configAssignPropertiesForPnf.getServiceInstanceId()); + assertNotNull(configAssignPropertiesForPnf.getServiceModelUuid()); + assertNotNull(configAssignPropertiesForPnf.getUserParam()); + + assertEquals("service-instance-id", configAssignPropertiesForPnf.getServiceInstanceId()); + assertEquals("service-model-uuid", configAssignPropertiesForPnf.getServiceModelUuid()); + assertEquals("pnf-customization-uuid", configAssignPropertiesForPnf.getPnfCustomizationUuid()); + assertEquals("pnf-id", configAssignPropertiesForPnf.getPnfId()); + assertEquals("pnf-name", configAssignPropertiesForPnf.getPnfName()); + assertEquals(userParam, configAssignPropertiesForPnf.getUserParam()); + } + + @Test + public void testtoString() { + final StringBuilder sb = new StringBuilder("{"); + sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\""); + sb.append(", \"pnf-id\":").append("\"").append(pnfId).append("\""); + sb.append(", \"pnf-name\":").append("\"").append(pnfName).append("\""); + sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\""); + sb.append(", \"pnf-customization-uuid\":").append("\"").append(pnfCustomizationUuid).append("\""); + for (Map.Entry<String, Object> entry : userParam.entrySet()) { + sb.append(","); + sb.append("\""); + sb.append(entry.getKey()); + sb.append("\""); + sb.append(":"); + sb.append("\""); + sb.append(entry.getValue()); + sb.append("\""); + } + sb.append('}'); + String Expexted = sb.toString(); + assertEquals(Expexted, configAssignPropertiesForPnf.toString()); + + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnfTest.java new file mode 100644 index 0000000000..8b732af6d0 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignPropertiesForVnfTest.java @@ -0,0 +1,68 @@ +package org.onap.so.client.cds.beans; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +public class ConfigAssignPropertiesForVnfTest { + ConfigAssignPropertiesForVnf configAssignPropertiesForVnf = new ConfigAssignPropertiesForVnf(); + private Map<String, Object> userParam = new HashMap<String, Object>(); + private String serviceInstanceId; + private String vnfId; + private String vnfName; + private String serviceModelUuid; + private String vnfCustomizationUuid; + + @Test + public final void testConfigAssignPropertiesForVnfTest() { + userParam.put("Instance1", "instance1value"); + configAssignPropertiesForVnf.setServiceInstanceId("service-instance-id"); + configAssignPropertiesForVnf.setServiceModelUuid("service-model-uuid"); + configAssignPropertiesForVnf.setVnfCustomizationUuid("vnf-customization-uuid"); + configAssignPropertiesForVnf.setVnfId("vnf-id"); + configAssignPropertiesForVnf.setVnfName("vnf-name"); + configAssignPropertiesForVnf.setUserParam("Instance1", "instance1value"); + + assertNotNull(configAssignPropertiesForVnf.getServiceInstanceId()); + assertNotNull(configAssignPropertiesForVnf.getServiceModelUuid()); + assertNotNull(configAssignPropertiesForVnf.getVnfCustomizationUuid()); + assertNotNull(configAssignPropertiesForVnf.getVnfId()); + assertNotNull(configAssignPropertiesForVnf.getVnfName()); + assertNotNull(configAssignPropertiesForVnf.getUserParam()); + + assertEquals("service-instance-id", configAssignPropertiesForVnf.getServiceInstanceId()); + assertEquals("service-model-uuid", configAssignPropertiesForVnf.getServiceModelUuid()); + assertEquals("vnf-customization-uuid", configAssignPropertiesForVnf.getVnfCustomizationUuid()); + assertEquals("vnf-id", configAssignPropertiesForVnf.getVnfId()); + assertEquals("vnf-name", configAssignPropertiesForVnf.getVnfName()); + assertEquals(userParam, configAssignPropertiesForVnf.getUserParam()); + + } + + @Test + public void testtoString() { + final StringBuilder sb = new StringBuilder("{"); + sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\""); + sb.append(", \"vnf-id\":").append("\"").append(vnfId).append("\""); + sb.append(", \"vnf-name\":").append("\"").append(vnfName).append("\""); + sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\""); + sb.append(", \"vnf-customization-uuid\":").append("\"").append(vnfCustomizationUuid).append("\""); + for (Map.Entry<String, Object> entry : userParam.entrySet()) { + sb.append(","); + sb.append("\""); + sb.append(entry.getKey()); + sb.append("\""); + sb.append(":"); + sb.append("\""); + sb.append(entry.getValue()); + sb.append("\""); + } + sb.append('}'); + String Expexted = sb.toString(); + assertEquals(Expexted, configAssignPropertiesForVnf.toString()); + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnfTest.java new file mode 100644 index 0000000000..e4f062ad05 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestPnfTest.java @@ -0,0 +1,48 @@ +package org.onap.so.client.cds.beans; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +public class ConfigAssignRequestPnfTest { + ConfigAssignRequestPnf configAssignRequestPnf = new ConfigAssignRequestPnf(); + ConfigAssignPropertiesForPnf configAssignPropertiesForPnf = new ConfigAssignPropertiesForPnf(); + private Map<String, Object> userParam = new HashMap<String, Object>(); + private String resolutionKey; + + @Test + public final void testConfigAssignRequestPnfTest() { + configAssignRequestPnf.setResolutionKey("resolution-key"); + configAssignRequestPnf.setConfigAssignPropertiesForPnf(configAssignPropertiesForPnf); + assertNotNull(configAssignRequestPnf.getResolutionKey()); + assertNotNull(configAssignRequestPnf.getConfigAssignPropertiesForPnf()); + + assertEquals("resolution-key", configAssignRequestPnf.getResolutionKey()); + assertEquals(configAssignPropertiesForPnf, configAssignRequestPnf.getConfigAssignPropertiesForPnf()); + } + + @Test + public void testtoString() { + userParam.put("Instance1", "instance1value"); + configAssignPropertiesForPnf.setPnfCustomizationUuid("pnf-customization-uuid"); + configAssignPropertiesForPnf.setPnfId("pnf-id"); + configAssignPropertiesForPnf.setPnfName("pnf-name"); + configAssignPropertiesForPnf.setServiceInstanceId("service-instance-id"); + configAssignPropertiesForPnf.setServiceModelUuid("service-model-uuid"); + configAssignPropertiesForPnf.setUserParam("user_params", userParam); + configAssignRequestPnf.setConfigAssignPropertiesForPnf(configAssignPropertiesForPnf); + final StringBuilder sb = new StringBuilder("{\"config-assign-request\":{"); + sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\""); + sb.append(", \"config-assign-properties\":").append(configAssignPropertiesForPnf.toString()); + sb.append('}'); + sb.append('}'); + String Expexted = sb.toString(); + + assertEquals(Expexted, configAssignRequestPnf.toString()); + + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnfTest.java new file mode 100644 index 0000000000..ad3af47453 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigAssignRequestVnfTest.java @@ -0,0 +1,51 @@ +package org.onap.so.client.cds.beans; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +public class ConfigAssignRequestVnfTest { + ConfigAssignRequestVnf configAssignRequestVnf = new ConfigAssignRequestVnf(); + ConfigAssignPropertiesForVnf configAssignPropertiesForVnf = new ConfigAssignPropertiesForVnf(); + private Map<String, Object> userParam = new HashMap<String, Object>(); + + private String resolutionKey; + + @Test + public final void testConfigAssignRequestVnf() { + configAssignRequestVnf.setResolutionKey("resolution-key"); + configAssignRequestVnf.setConfigAssignPropertiesForVnf(configAssignPropertiesForVnf); + assertNotNull(configAssignRequestVnf.getResolutionKey()); + assertNotNull(configAssignRequestVnf.getConfigAssignPropertiesForVnf()); + + assertEquals("resolution-key", configAssignRequestVnf.getResolutionKey()); + assertEquals(configAssignPropertiesForVnf, configAssignRequestVnf.getConfigAssignPropertiesForVnf()); + + } + + @Test + public void testtoString() { + userParam.put("Instance1", "instance1value"); + configAssignPropertiesForVnf.setServiceInstanceId("service-instance-id"); + configAssignPropertiesForVnf.setServiceModelUuid("service-model-uuid"); + configAssignPropertiesForVnf.setUserParam("user_params", userParam); + configAssignPropertiesForVnf.setVnfCustomizationUuid("vnf-customization-uuid"); + configAssignPropertiesForVnf.setVnfId("vnf-id"); + configAssignPropertiesForVnf.setVnfName("vnf-name"); + configAssignRequestVnf.setConfigAssignPropertiesForVnf(configAssignPropertiesForVnf); + + final StringBuilder sb = new StringBuilder("{\"config-assign-request\":{"); + sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\""); + sb.append(", \"config-assign-properties\":").append(configAssignPropertiesForVnf.toString()); + sb.append('}'); + sb.append('}'); + + String Expexted = sb.toString(); + + assertEquals(Expexted, configAssignRequestVnf.toString()); + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnfTest.java new file mode 100644 index 0000000000..1d771c86d5 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForPnfTest.java @@ -0,0 +1,50 @@ +package org.onap.so.client.cds.beans; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class ConfigDeployPropertiesForPnfTest { + ConfigDeployPropertiesForPnf configDeployPropertiesForPnf = new ConfigDeployPropertiesForPnf(); + private String serviceInstanceId; + private String pnfId; + private String pnfName; + private String serviceModelUuid; + private String pnfCustomizationUuid; + + @Test + public final void testConfigDeployPropertiesForPnfTest() { + configDeployPropertiesForPnf.setServiceInstanceId("service-instance-id"); + configDeployPropertiesForPnf.setServiceModelUuid("service-model-uuid"); + configDeployPropertiesForPnf.setPnfCustomizationUuid("pnf-customization-uuid"); + configDeployPropertiesForPnf.setPnfId("pnf-id"); + configDeployPropertiesForPnf.setPnfName("pnf-name"); + assertNotNull(configDeployPropertiesForPnf.getServiceInstanceId()); + assertNotNull(configDeployPropertiesForPnf.getServiceModelUuid()); + assertNotNull(configDeployPropertiesForPnf.getPnfCustomizationUuid()); + assertNotNull(configDeployPropertiesForPnf.getPnfId()); + assertNotNull(configDeployPropertiesForPnf.getPnfName()); + + assertEquals("service-instance-id", configDeployPropertiesForPnf.getServiceInstanceId()); + assertEquals("service-model-uuid", configDeployPropertiesForPnf.getServiceModelUuid()); + assertEquals("pnf-customization-uuid", configDeployPropertiesForPnf.getPnfCustomizationUuid()); + assertEquals("pnf-id", configDeployPropertiesForPnf.getPnfId()); + assertEquals("pnf-name", configDeployPropertiesForPnf.getPnfName()); + + } + + @Test + public void testtoString() { + final StringBuilder sb = new StringBuilder("{"); + sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\""); + sb.append(", \"pnf-id\":").append("\"").append(pnfId).append("\""); + sb.append(", \"pnf-name\":").append("\"").append(pnfName).append("\""); + sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\""); + sb.append(", \"pnf-customization-uuid\":").append("\"").append(pnfCustomizationUuid).append("\""); + sb.append('}'); + String Expexted = sb.toString(); + assertEquals(Expexted, configDeployPropertiesForPnf.toString()); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnfTest.java new file mode 100644 index 0000000000..47c59b93e9 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployPropertiesForVnfTest.java @@ -0,0 +1,49 @@ +package org.onap.so.client.cds.beans; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class ConfigDeployPropertiesForVnfTest { + ConfigDeployPropertiesForVnf configDeployPropertiesForVnf = new ConfigDeployPropertiesForVnf(); + private String serviceInstanceId; + private String vnfId; + private String vnfName; + private String serviceModelUuid; + private String vnfCustomizationUuid; + + @Test + public final void testConfigDeployPropertiesForVnf() { + configDeployPropertiesForVnf.setServiceInstanceId("service-instance-id"); + configDeployPropertiesForVnf.setServiceModelUuid("service-model-uuid"); + configDeployPropertiesForVnf.setVnfCustomizationUuid("vnf-customization-uuid"); + configDeployPropertiesForVnf.setVnfId("vnf-id"); + configDeployPropertiesForVnf.setVnfName("vnf-name"); + assertNotNull(configDeployPropertiesForVnf.getServiceInstanceId()); + assertNotNull(configDeployPropertiesForVnf.getServiceModelUuid()); + assertNotNull(configDeployPropertiesForVnf.getVnfCustomizationUuid()); + assertNotNull(configDeployPropertiesForVnf.getVnfId()); + assertNotNull(configDeployPropertiesForVnf.getVnfName()); + + assertEquals("service-instance-id", configDeployPropertiesForVnf.getServiceInstanceId()); + assertEquals("service-model-uuid", configDeployPropertiesForVnf.getServiceModelUuid()); + assertEquals("vnf-customization-uuid", configDeployPropertiesForVnf.getVnfCustomizationUuid()); + assertEquals("vnf-id", configDeployPropertiesForVnf.getVnfId()); + assertEquals("vnf-name", configDeployPropertiesForVnf.getVnfName()); + } + + @Test + public void testtoString() { + final StringBuilder sb = new StringBuilder("{"); + sb.append("\"service-instance-id\":").append("\"").append(serviceInstanceId).append("\""); + sb.append(", \"vnf-id\":").append("\"").append(vnfId).append("\""); + sb.append(", \"vnf-name\":").append("\"").append(vnfName).append("\""); + sb.append(", \"service-model-uuid\":").append("\"").append(serviceModelUuid).append("\""); + sb.append(", \"vnf-customization-uuid\":").append("\"").append(vnfCustomizationUuid).append("\""); + sb.append('}'); + String Expexted = sb.toString(); + assertEquals(Expexted, configDeployPropertiesForVnf.toString()); + + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnfTest.java new file mode 100644 index 0000000000..df41bf23b8 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestPnfTest.java @@ -0,0 +1,41 @@ +package org.onap.so.client.cds.beans; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class ConfigDeployRequestPnfTest { + ConfigDeployRequestPnf configDeployRequestPnf = new ConfigDeployRequestPnf(); + private String resolutionKey; + ConfigDeployPropertiesForPnf configDeployPropertiesForPnf = new ConfigDeployPropertiesForPnf(); + + @Test + public final void testConfigDeployRequestVnf() { + configDeployRequestPnf.setResolutionKey("resolution-key"); + configDeployRequestPnf.setConfigDeployPropertiesForPnf(configDeployPropertiesForPnf); + assertNotNull(configDeployRequestPnf.getResolutionKey()); + assertNotNull(configDeployRequestPnf.getConfigDeployPropertiesForPnf()); + assertEquals("resolution-key", configDeployRequestPnf.getResolutionKey()); + assertEquals(configDeployPropertiesForPnf, configDeployRequestPnf.getConfigDeployPropertiesForPnf()); + } + + @Test + public void testtoString() { + configDeployPropertiesForPnf.setServiceInstanceId("service-instance-id"); + configDeployPropertiesForPnf.setServiceModelUuid("service-model-uuid"); + configDeployPropertiesForPnf.setPnfCustomizationUuid("pnf-customization-uuid"); + configDeployPropertiesForPnf.setPnfId("pnf-id"); + configDeployPropertiesForPnf.setPnfName("pnf-name"); + configDeployRequestPnf.setConfigDeployPropertiesForPnf(configDeployPropertiesForPnf); + final StringBuilder sb = new StringBuilder("{\"config-deploy-request\":{"); + sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\""); + sb.append(", \"config-deploy-properties\":").append(configDeployPropertiesForPnf.toString()); + sb.append('}'); + sb.append('}'); + String Expexted = sb.toString(); + + assertEquals(Expexted, configDeployRequestPnf.toString()); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnfTest.java new file mode 100644 index 0000000000..f771710f8b --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/client/cds/beans/ConfigDeployRequestVnfTest.java @@ -0,0 +1,42 @@ +package org.onap.so.client.cds.beans; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class ConfigDeployRequestVnfTest { + + ConfigDeployRequestVnf configDeployRequestVnf = new ConfigDeployRequestVnf(); + private String resolutionKey; + ConfigDeployPropertiesForVnf configDeployPropertiesForVnf = new ConfigDeployPropertiesForVnf(); + + @Test + public final void testConfigDeployRequestVnf() { + configDeployRequestVnf.setResolutionKey("resolution-key"); + configDeployRequestVnf.setConfigDeployPropertiesForVnf(configDeployPropertiesForVnf); + assertNotNull(configDeployRequestVnf.getResolutionKey()); + assertNotNull(configDeployRequestVnf.getConfigDeployPropertiesForVnf()); + assertEquals("resolution-key", configDeployRequestVnf.getResolutionKey()); + assertEquals(configDeployPropertiesForVnf, configDeployRequestVnf.getConfigDeployPropertiesForVnf()); + } + + @Test + public void testtoString() { + configDeployPropertiesForVnf.setServiceInstanceId("service-instance-id"); + configDeployPropertiesForVnf.setServiceModelUuid("service-model-uuid"); + configDeployPropertiesForVnf.setVnfCustomizationUuid("vnf-customization-uuid"); + configDeployPropertiesForVnf.setVnfId("vnf-id"); + configDeployPropertiesForVnf.setVnfName("vnf-name"); + configDeployRequestVnf.setConfigDeployPropertiesForVnf(configDeployPropertiesForVnf); + final StringBuilder sb = new StringBuilder("{\"config-deploy-request\":{"); + sb.append("\"resolution-key\":").append("\"").append(resolutionKey).append("\""); + sb.append(", \"config-deploy-properties\":").append(configDeployPropertiesForVnf.toString()); + sb.append('}'); + sb.append('}'); + String Expexted = sb.toString(); + + assertEquals(Expexted, configDeployRequestVnf.toString()); + } + +} diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AbstractCDSProcessingBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AbstractCDSProcessingBB.bpmn new file mode 100644 index 0000000000..4fcf13d98d --- /dev/null +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/AbstractCDSProcessingBB.bpmn @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_1l7m222" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.0.1"> + <bpmn:process id="AbstractCDSProcessingBB" name="Abstract CDS Processing BB" isExecutable="true"> + <bpmn:startEvent id="StartEvent_1"> + <bpmn:outgoing>SequenceFlow_02v5z4h</bpmn:outgoing> + </bpmn:startEvent> + <bpmn:sequenceFlow id="SequenceFlow_02v5z4h" sourceRef="StartEvent_1" targetRef="Task_06n9c9v" /> + <bpmn:sequenceFlow id="SequenceFlow_0gksy4i" sourceRef="Task_06n9c9v" targetRef="Task_0kjfr5o" /> + <bpmn:sequenceFlow id="SequenceFlow_161g9uz" sourceRef="Task_0kjfr5o" targetRef="EndEvent_1h3epjc" /> + <bpmn:endEvent id="EndEvent_1h3epjc"> + <bpmn:incoming>SequenceFlow_161g9uz</bpmn:incoming> + </bpmn:endEvent> + <bpmn:serviceTask id="Task_06n9c9v" name="Get Required data to call CDS Client" camunda:expression="${AbstractCDSProcessingBBUtils.constructExecutionServiceInputObject(execution)}"> + <bpmn:incoming>SequenceFlow_02v5z4h</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0gksy4i</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:serviceTask id="Task_0kjfr5o" name="CDS (Call SelfServiceAPI) " camunda:expression="${AbstractCDSProcessingBBUtils.sendRequestToCDSClient(execution)}"> + <bpmn:incoming>SequenceFlow_0gksy4i</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_161g9uz</bpmn:outgoing> + </bpmn:serviceTask> + </bpmn:process> + <bpmndi:BPMNDiagram id="BPMNDiagram_1"> + <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="AbstractCDSProcessingBB"> + <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1"> + <dc:Bounds x="124" y="264" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_02v5z4h_di" bpmnElement="SequenceFlow_02v5z4h"> + <di:waypoint x="160" y="282" /> + <di:waypoint x="223" y="282" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_0gksy4i_di" bpmnElement="SequenceFlow_0gksy4i"> + <di:waypoint x="323" y="282" /> + <di:waypoint x="385" y="282" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_161g9uz_di" bpmnElement="SequenceFlow_161g9uz"> + <di:waypoint x="485" y="282" /> + <di:waypoint x="578" y="282" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="EndEvent_1h3epjc_di" bpmnElement="EndEvent_1h3epjc"> + <dc:Bounds x="578" y="264" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_16es7z5_di" bpmnElement="Task_06n9c9v"> + <dc:Bounds x="223" y="242" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_18soa9e_di" bpmnElement="Task_0kjfr5o"> + <dc:Bounds x="385" y="242" width="100" height="80" /> + </bpmndi:BPMNShape> + </bpmndi:BPMNPlane> + </bpmndi:BPMNDiagram> +</bpmn:definitions> diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ConfigAssignVnfBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ConfigAssignVnfBB.bpmn new file mode 100644 index 0000000000..9892fbdd91 --- /dev/null +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ConfigAssignVnfBB.bpmn @@ -0,0 +1,98 @@ +<?xml version="1.0" encoding="UTF-8"?> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_1ahlzqg" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.0.1"> + <bpmn:process id="ConfigAssignVnfBB" name="ConfigAssignVnfBB" isExecutable="true"> + <bpmn:startEvent id="StartEvent_1"> + <bpmn:outgoing>SequenceFlow_0gmfit3</bpmn:outgoing> + </bpmn:startEvent> + <bpmn:sequenceFlow id="SequenceFlow_0gmfit3" sourceRef="StartEvent_1" targetRef="Task_0bhf6tp" /> + <bpmn:endEvent id="EndEvent_0lgvk82"> + <bpmn:incoming>SequenceFlow_1mkhog2</bpmn:incoming> + </bpmn:endEvent> + <bpmn:sequenceFlow id="SequenceFlow_1mkhog2" sourceRef="Task_1hs1mn0" targetRef="EndEvent_0lgvk82" /> + <bpmn:callActivity id="CallActivity_1gfzi2g" name="Abstract CDS (CDS Call) " calledElement="AbstractCDSProcessingBB"> + <bpmn:extensionElements> + <camunda:out source="WorkflowException" target="WorkflowException" /> + <camunda:out source="CDSStatus" target="CDSStatus" /> + <camunda:in source="executionObject" target="executionObject" /> + </bpmn:extensionElements> + <bpmn:incoming>SequenceFlow_05qembo</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0cvsnuu</bpmn:outgoing> + </bpmn:callActivity> + <bpmn:serviceTask id="Task_1hs1mn0" name="Update AAI (VNF) " camunda:expression="${AAIUpdateTasks.updateOrchestrationStatusConfigAssignedVnf(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:incoming>SequenceFlow_07tqu82</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_1mkhog2</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:sequenceFlow id="SequenceFlow_05qembo" sourceRef="Task_0bhf6tp" targetRef="CallActivity_1gfzi2g" /> + <bpmn:serviceTask id="Task_0bhf6tp" name="PreProcess Abstract CDS Processing" camunda:expression="${ConfigAssignVnf.PreProcessAbstractCDSProcessing(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:incoming>SequenceFlow_0gmfit3</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_05qembo</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:exclusiveGateway id="ExclusiveGateway_13q340y" default="SequenceFlow_15gxql1"> + <bpmn:incoming>SequenceFlow_0cvsnuu</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_07tqu82</bpmn:outgoing> + <bpmn:outgoing>SequenceFlow_15gxql1</bpmn:outgoing> + </bpmn:exclusiveGateway> + <bpmn:sequenceFlow id="SequenceFlow_0cvsnuu" sourceRef="CallActivity_1gfzi2g" targetRef="ExclusiveGateway_13q340y" /> + <bpmn:sequenceFlow id="SequenceFlow_07tqu82" name="success" sourceRef="ExclusiveGateway_13q340y" targetRef="Task_1hs1mn0"> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">#{execution.getVariable("CDSStatus").equals("Success")}</bpmn:conditionExpression> + </bpmn:sequenceFlow> + <bpmn:endEvent id="EndEvent_0mnaj50"> + <bpmn:incoming>SequenceFlow_15gxql1</bpmn:incoming> + <bpmn:errorEventDefinition id="ErrorEventDefinition_1s1hqgm" errorRef="Error_0aovtfv" /> + </bpmn:endEvent> + <bpmn:sequenceFlow id="SequenceFlow_15gxql1" sourceRef="ExclusiveGateway_13q340y" targetRef="EndEvent_0mnaj50" /> + </bpmn:process> + <bpmn:error id="Error_0aovtfv" name="MSOWorkflowException" errorCode="MSOWorkflowException" /> + <bpmndi:BPMNDiagram id="BPMNDiagram_1"> + <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="ConfigAssignVnfBB"> + <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1"> + <dc:Bounds x="507" y="187" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0gmfit3_di" bpmnElement="SequenceFlow_0gmfit3"> + <di:waypoint x="543" y="205" /> + <di:waypoint x="614" y="205" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="EndEvent_0lgvk82_di" bpmnElement="EndEvent_0lgvk82"> + <dc:Bounds x="1307" y="187" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_1mkhog2_di" bpmnElement="SequenceFlow_1mkhog2"> + <di:waypoint x="1218" y="205" /> + <di:waypoint x="1307" y="205" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="CallActivity_1gfzi2g_di" bpmnElement="CallActivity_1gfzi2g"> + <dc:Bounds x="788" y="165" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ServiceTask_0404s6a_di" bpmnElement="Task_1hs1mn0"> + <dc:Bounds x="1118" y="165" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_05qembo_di" bpmnElement="SequenceFlow_05qembo"> + <di:waypoint x="714" y="205" /> + <di:waypoint x="788" y="205" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ServiceTask_01mv1si_di" bpmnElement="Task_0bhf6tp"> + <dc:Bounds x="614" y="165" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="ExclusiveGateway_13q340y_di" bpmnElement="ExclusiveGateway_13q340y" isMarkerVisible="true"> + <dc:Bounds x="978" y="180" width="50" height="50" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0cvsnuu_di" bpmnElement="SequenceFlow_0cvsnuu"> + <di:waypoint x="888" y="205" /> + <di:waypoint x="978" y="205" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNEdge id="SequenceFlow_07tqu82_di" bpmnElement="SequenceFlow_07tqu82"> + <di:waypoint x="1028" y="205" /> + <di:waypoint x="1118" y="205" /> + <bpmndi:BPMNLabel> + <dc:Bounds x="1053" y="187" width="41" height="14" /> + </bpmndi:BPMNLabel> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="EndEvent_0mnaj50_di" bpmnElement="EndEvent_0mnaj50"> + <dc:Bounds x="985" y="327" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_15gxql1_di" bpmnElement="SequenceFlow_15gxql1"> + <di:waypoint x="1003" y="230" /> + <di:waypoint x="1003" y="327" /> + </bpmndi:BPMNEdge> + </bpmndi:BPMNPlane> + </bpmndi:BPMNDiagram> +</bpmn:definitions> diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/EtsiVnfInstantiateBB.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/EtsiVnfInstantiateBB.bpmn new file mode 100644 index 0000000000..9b98620f78 --- /dev/null +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/EtsiVnfInstantiateBB.bpmn @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_0x13ohc" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="2.0.3"> + <bpmn:process id="EtsiVnfInstantiateBB" name=" EtsiVnfInstantiateBB" isExecutable="true"> + <bpmn:serviceTask id="ServiceTask_02e82t2" name="Create CreateVnfRequest " camunda:expression="${VnfmAdapterCreateVnfTask.buildCreateVnfRequest(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:incoming>SequenceFlow_016sgof</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0f0vsnv</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:startEvent id="StartEvent_0ru3x55"> + <bpmn:outgoing>SequenceFlow_016sgof</bpmn:outgoing> + </bpmn:startEvent> + <bpmn:sequenceFlow id="SequenceFlow_016sgof" sourceRef="StartEvent_0ru3x55" targetRef="ServiceTask_02e82t2" /> + <bpmn:endEvent id="EndEvent_001k15i"> + <bpmn:incoming>SequenceFlow_0cik89t</bpmn:incoming> + </bpmn:endEvent> + <bpmn:sequenceFlow id="SequenceFlow_0f0vsnv" sourceRef="ServiceTask_02e82t2" targetRef="ServiceTask_06ao4xu" /> + <bpmn:serviceTask id="ServiceTask_06ao4xu" name=" Invoke VNFM Adaptor " camunda:asyncAfter="true" camunda:expression="${VnfmAdapterCreateVnfTask.invokeVnfmAdapter(InjectExecution.execute(execution, execution.getVariable("gBuildingBlockExecution")))}"> + <bpmn:incoming>SequenceFlow_0f0vsnv</bpmn:incoming> + <bpmn:outgoing>SequenceFlow_0cik89t</bpmn:outgoing> + </bpmn:serviceTask> + <bpmn:sequenceFlow id="SequenceFlow_0cik89t" sourceRef="ServiceTask_06ao4xu" targetRef="EndEvent_001k15i" /> + </bpmn:process> + <bpmndi:BPMNDiagram id="BPMNDiagram_1"> + <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="EtsiVnfInstantiateBB"> + <bpmndi:BPMNShape id="ServiceTask_02e82t1_di" bpmnElement="ServiceTask_02e82t2"> + <dc:Bounds x="353" y="227" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNShape id="StartEvent_0ru3x55_di" bpmnElement="StartEvent_0ru3x55"> + <dc:Bounds x="232" y="249" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_016sgof_di" bpmnElement="SequenceFlow_016sgof"> + <di:waypoint x="268" y="267" /> + <di:waypoint x="353" y="267" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="EndEvent_001k15i_di" bpmnElement="EndEvent_001k15i"> + <dc:Bounds x="703" y="249" width="36" height="36" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0f0vsnv_di" bpmnElement="SequenceFlow_0f0vsnv"> + <di:waypoint x="453" y="267" /> + <di:waypoint x="522" y="267" /> + </bpmndi:BPMNEdge> + <bpmndi:BPMNShape id="ServiceTask_06ao4xu_di" bpmnElement="ServiceTask_06ao4xu"> + <dc:Bounds x="522" y="227" width="100" height="80" /> + </bpmndi:BPMNShape> + <bpmndi:BPMNEdge id="SequenceFlow_0cik89t_di" bpmnElement="SequenceFlow_0cik89t"> + <di:waypoint x="622" y="267" /> + <di:waypoint x="703" y="267" /> + </bpmndi:BPMNEdge> + </bpmndi:BPMNPlane> + </bpmndi:BPMNDiagram> +</bpmn:definitions> diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ExecuteBuildingBlock.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ExecuteBuildingBlock.bpmn index 5189f8b48a..83363d48ba 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ExecuteBuildingBlock.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/ExecuteBuildingBlock.bpmn @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="1.8.2"> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="1.7.2"> <bpmn:process id="ExecuteBuildingBlock" name="ExecuteBuildingBlock" isExecutable="true"> <bpmn:startEvent id="Start_ExecuteBuildingBlock" name="start"> <bpmn:outgoing>SequenceFlow_0rq4c5r</bpmn:outgoing> @@ -9,6 +9,7 @@ <camunda:in source="gBuildingBlockExecution" target="gBuildingBlockExecution" /> <camunda:out source="WorkflowException" target="WorkflowException" /> <camunda:in source="mso-request-id" target="mso-request-id" /> + <camunda:out source="WorkflowExceptionErrorMessage" target="WorkflowExceptionErrorMessage" /> </bpmn:extensionElements> <bpmn:incoming>SequenceFlow_19wuics</bpmn:incoming> <bpmn:outgoing>SequenceFlow_01h9qmz</bpmn:outgoing> 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 2437476b59..76ca2a89cc 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 @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="1.10.0"> +<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="1.7.2"> <bpmn:process id="WorkflowActionBB" name="WorkflowActionBB" isExecutable="true"> <bpmn:startEvent id="Start_WorkflowActionBB" name="start"> <bpmn:outgoing>SequenceFlow_15s0okp</bpmn:outgoing> @@ -88,7 +88,7 @@ </bpmn:serviceTask> </bpmn:subProcess> <bpmn:sequenceFlow id="SequenceFlow_0v588sm" name="Rollback = true" sourceRef="ExclusiveGateway_Finished" targetRef="Task_RollbackExecutionPath"> - <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("handlingCode")=="Rollback"||execution.getVariable("handlingCode")=="RollbackToAssigned"}]]></bpmn:conditionExpression> + <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("handlingCode")=="Rollback"||execution.getVariable("handlingCode")=="RollbackToAssigned"||execution.getVariable("handlingCode")=="RollbackToCreated"}]]></bpmn:conditionExpression> </bpmn:sequenceFlow> <bpmn:sequenceFlow id="SequenceFlow_1atzsgn" sourceRef="Task_RollbackExecutionPath" targetRef="Task_SelectBB"> <bpmn:conditionExpression xsi:type="bpmn:tFormalExpression"><![CDATA[${execution.getVariable("isRollbackNeeded")==true}]]></bpmn:conditionExpression> diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java index cd2b46bf70..6aa5cf3412 100644 --- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java +++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/BuildingBlockTestDataSetup.java @@ -349,7 +349,7 @@ public class BuildingBlockTestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -367,7 +367,7 @@ public class BuildingBlockTestDataSetup{ Collection collection = null; try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); collection = serviceInstance.getCollection(); if (collection == null) { @@ -442,7 +442,7 @@ public class BuildingBlockTestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -487,7 +487,7 @@ public class BuildingBlockTestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -522,7 +522,7 @@ public class BuildingBlockTestDataSetup{ GenericVnf genericVnf = null; try { - genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); } catch(BBObjectNotFoundException e) { genericVnf = setGenericVnf(); } @@ -550,7 +550,7 @@ public class BuildingBlockTestDataSetup{ GenericVnf genericVnf = null; try { - genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); } catch(BBObjectNotFoundException e) { genericVnf = setGenericVnf(); } @@ -614,7 +614,7 @@ public class BuildingBlockTestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } diff --git a/bpmn/so-bpmn-tasks/pom.xml b/bpmn/so-bpmn-tasks/pom.xml index 0243ce8ae6..ce1cdd5068 100644 --- a/bpmn/so-bpmn-tasks/pom.xml +++ b/bpmn/so-bpmn-tasks/pom.xml @@ -1,150 +1,160 @@ <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <parent> - <groupId>org.onap.so</groupId> - <artifactId>bpmn</artifactId> - <version>1.4.0-SNAPSHOT</version> - </parent> - <modelVersion>4.0.0</modelVersion> - <artifactId>so-bpmn-tasks</artifactId> - <packaging>jar</packaging> - <properties> - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> - <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> - <maven.compiler.target>1.8</maven.compiler.target> - <maven.compiler.source>1.8</maven.compiler.source> - </properties> - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-surefire-plugin</artifactId> - <executions> - <execution> - <id>default-test</id> - <goals> - <goal>test</goal> - </goals> - <configuration> - <includes> - <include>**/UnitTestSuite.java</include> - </includes> - </configuration> - </execution> - <execution> - <id>integration-test</id> - <goals> - <goal>test</goal> - </goals> - <configuration> - <includes> - <include>**/IntegrationTestSuite.java</include> - </includes> - </configuration> - </execution> - </executions> - </plugin> - <plugin> - <groupId>io.swagger</groupId> - <artifactId>swagger-codegen-maven-plugin</artifactId> - <version>2.3.1</version> - <executions> - <execution> - <goals> - <goal>generate</goal> - </goals> - <configuration> - <inputSpec>${project.basedir}/src/main/resources/naming-service/swagger.json</inputSpec> - <apiPackage>org.onap.namingservice.api</apiPackage> - <modelPackage>org.onap.namingservice.model</modelPackage> - <invokerPackage>org.onap.namingservice.invoker</invokerPackage> - </configuration> - </execution> - </executions> - <configuration> - <inputSpec>${project.basedir}/src/main/resources/swagger.json</inputSpec> - <language>java</language> - <configOptions> - <sourceFolder>src/gen/java/main</sourceFolder> - <serializableModel>true</serializableModel> - </configOptions> - <output>${project.build.directory}/generated-sources</output> - <generateApis>false</generateApis> - <library>jersey2</library> - <generateSupportingFiles>false</generateSupportingFiles> - </configuration> - </plugin> - </plugins> - </build> - <dependencyManagement> - <dependencies> - <dependency> - <!-- Import dependency management from Spring Boot --> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-dependencies</artifactId> - <version>${springboot.version}</version> - <type>pom</type> - <scope>import</scope> - </dependency> - </dependencies> - </dependencyManagement> - <dependencies> - <dependency> - <groupId>org.camunda.bpm.springboot</groupId> - <artifactId>camunda-bpm-spring-boot-starter</artifactId> - <version>${camunda.springboot.version}</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.springframework.cloud</groupId> - <artifactId>spring-cloud-contract-wiremock</artifactId> - <version>1.2.4.RELEASE</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.springframework.boot</groupId> - <artifactId>spring-boot-starter-test</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.camunda.bpm.extension.mockito</groupId> - <artifactId>camunda-bpm-mockito</artifactId> - </dependency> - <dependency> - <groupId>org.onap.so</groupId> - <artifactId>MSOCommonBPMN</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> - <groupId>org.onap.so</groupId> - <artifactId>so-bpmn-infrastructure-common</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> - <groupId>org.onap.so.adapters</groupId> - <artifactId>mso-adapter-utils</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> - <groupId>org.onap.sdnc.northbound</groupId> - <artifactId>generic-resource-api-client</artifactId> - <version>1.5.0-SNAPSHOT</version> - <exclusions> - <exclusion> - <groupId>javax.ws.rs</groupId> - <artifactId>jsr311-api</artifactId> - </exclusion> - </exclusions> - </dependency> - <dependency> - <groupId>ch.vorburger.mariaDB4j</groupId> - <artifactId>mariaDB4j</artifactId> - <version>2.2.3</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.commons</groupId> - <artifactId>commons-lang3</artifactId> - </dependency> - </dependencies> + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <parent> + <groupId>org.onap.so</groupId> + <artifactId>bpmn</artifactId> + <version>1.4.0-SNAPSHOT</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>so-bpmn-tasks</artifactId> + <packaging>jar</packaging> + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> + <maven.compiler.target>1.8</maven.compiler.target> + <maven.compiler.source>1.8</maven.compiler.source> + </properties> + <build> + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-surefire-plugin</artifactId> + <executions> + <execution> + <id>default-test</id> + <goals> + <goal>test</goal> + </goals> + <configuration> + <includes> + <include>**/UnitTestSuite.java</include> + </includes> + </configuration> + </execution> + <execution> + <id>integration-test</id> + <goals> + <goal>test</goal> + </goals> + <configuration> + <includes> + <include>**/IntegrationTestSuite.java</include> + </includes> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>io.swagger</groupId> + <artifactId>swagger-codegen-maven-plugin</artifactId> + <version>2.3.1</version> + <executions> + <execution> + <goals> + <goal>generate</goal> + </goals> + <configuration> + <inputSpec>${project.basedir}/src/main/resources/naming-service/swagger.json</inputSpec> + <apiPackage>org.onap.namingservice.api</apiPackage> + <modelPackage>org.onap.namingservice.model</modelPackage> + <invokerPackage>org.onap.namingservice.invoker</invokerPackage> + </configuration> + </execution> + </executions> + <configuration> + <inputSpec>${project.basedir}/src/main/resources/swagger.json</inputSpec> + <language>java</language> + <configOptions> + <sourceFolder>src/gen/java/main</sourceFolder> + <serializableModel>true</serializableModel> + </configOptions> + <output>${project.build.directory}/generated-sources</output> + <generateApis>false</generateApis> + <library>jersey2</library> + <generateSupportingFiles>false</generateSupportingFiles> + </configuration> + </plugin> + </plugins> + </build> + <dependencyManagement> + <dependencies> + <dependency> + <!-- Import dependency management from Spring Boot --> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-dependencies</artifactId> + <version>${springboot.version}</version> + <type>pom</type> + <scope>import</scope> + </dependency> + </dependencies> + </dependencyManagement> + <dependencies> + <dependency> + <groupId>org.camunda.bpm.springboot</groupId> + <artifactId>camunda-bpm-spring-boot-starter</artifactId> + <version>${camunda.springboot.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework.cloud</groupId> + <artifactId>spring-cloud-contract-wiremock</artifactId> + <version>1.2.4.RELEASE</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-test</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.camunda.bpm.extension.mockito</groupId> + <artifactId>camunda-bpm-mockito</artifactId> + </dependency> + <dependency> + <groupId>org.onap.so</groupId> + <artifactId>MSOCommonBPMN</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.so</groupId> + <artifactId>so-bpmn-infrastructure-common</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.so.adapters</groupId> + <artifactId>mso-adapter-utils</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.sdnc.northbound</groupId> + <artifactId>generic-resource-api-client</artifactId> + <version>1.5.0-SNAPSHOT</version> + <exclusions> + <exclusion> + <groupId>javax.ws.rs</groupId> + <artifactId>jsr311-api</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>ch.vorburger.mariaDB4j</groupId> + <artifactId>mariaDB4j</artifactId> + <version>2.2.3</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + </dependency> + <dependency> + <groupId>org.onap.so.adapters</groupId> + <artifactId>mso-vnfm-adapter-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-configuration-processor</artifactId> + <optional>true</optional> + </dependency> + </dependencies> </project> diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICommonTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICommonTasks.java index 6571971347..bdb46e8d2b 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICommonTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICommonTasks.java @@ -41,7 +41,7 @@ public class AAICommonTasks { public Optional<String> getServiceType(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); ModelInfoServiceInstance model = serviceInstance.getModelInfoServiceInstance(); if (model != null) { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java index 760f623812..dad84e53a9 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasks.java @@ -104,7 +104,7 @@ public class AAICreateTasks { public void createServiceInstance(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Customer customer = execution.getGeneralBuildingBlock().getCustomer(); aaiSIResources.createServiceInstance(serviceInstance, customer); } catch (Exception ex) { @@ -115,7 +115,7 @@ public class AAICreateTasks { public void createServiceSubscription(BuildingBlockExecution execution){ try{ ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, - ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ResourceKey.SERVICE_INSTANCE_ID); Customer customer = execution.getGeneralBuildingBlock().getCustomer(); if (null == customer) { String errorMessage = "Exception in creating ServiceSubscription. Customer not present for ServiceInstanceID: " @@ -135,7 +135,7 @@ public class AAICreateTasks { public void createProject(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Project project = serviceInstance.getProject(); if(project != null) { if (project.getProjectName() == null || "".equals(project.getProjectName())) { @@ -151,7 +151,7 @@ public class AAICreateTasks { public void createOwningEntity(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); OwningEntity owningEntity = serviceInstance.getOwningEntity(); String owningEntityId = owningEntity.getOwningEntityId(); String owningEntityName = owningEntity.getOwningEntityName(); @@ -187,8 +187,8 @@ public class AAICreateTasks { public void createVnf(BuildingBlockExecution execution) { try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); execution.setVariable("callHoming", Boolean.TRUE.equals(vnf.isCallHoming())); aaiVnfResources.createVnfandConnectServiceInstance(vnf, serviceInstance); } catch (Exception ex) { @@ -198,7 +198,7 @@ public class AAICreateTasks { public void createPlatform(BuildingBlockExecution execution) { try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); Platform platform = vnf.getPlatform(); if(platform != null) { if (platform.getPlatformName() == null || "".equals(platform.getPlatformName())) { @@ -215,7 +215,7 @@ public class AAICreateTasks { public void createLineOfBusiness(BuildingBlockExecution execution) { try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); LineOfBusiness lineOfBusiness = vnf.getLineOfBusiness(); if(lineOfBusiness != null) { if (lineOfBusiness.getLineOfBusinessName() == null || "".equals(lineOfBusiness.getLineOfBusinessName())) { @@ -233,8 +233,8 @@ public class AAICreateTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); - VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); CloudRegion cloudRegion = gBBInput.getCloudRegion(); aaiVolumeGroupResources.createVolumeGroup(volumeGroup, cloudRegion); aaiVolumeGroupResources.connectVolumeGroupToVnf(genericVnf, volumeGroup, cloudRegion); @@ -246,8 +246,8 @@ public class AAICreateTasks { public void createVfModule(BuildingBlockExecution execution) { try { - GenericVnf vnf = 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)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); int moduleIndex = 0; if (vfModule.getModelInfoVfModule() != null && !Boolean.TRUE.equals(vfModule.getModelInfoVfModule().getIsBaseBoolean())) { moduleIndex = this.getLowestUnusedVfModuleIndexFromAAIVnfResponse(vnf, vfModule); @@ -266,11 +266,11 @@ public class AAICreateTasks { */ public void connectVfModuleToVolumeGroup(BuildingBlockExecution execution) { try { - GenericVnf vnf = 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)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); VolumeGroup volumeGroup = null; try{ - volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); } catch (BBObjectNotFoundException e){ logger.info("VolumeGroup not found. Skipping Connect between VfModule and VolumeGroup"); } @@ -289,8 +289,8 @@ public class AAICreateTasks { */ public void createNetwork(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); //set default to false. ToBe updated by SDNC l3network.setIsBoundToVpn(false); //define is bound to vpn flag as true if NEUTRON_NETWORK_TYPE is PROVIDER @@ -319,7 +319,7 @@ public class AAICreateTasks { */ public void createNetworkCollection(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Collection networkCollection = serviceInstance.getCollection(); //pass name generated for NetworkCollection/NetworkCollectionInstanceGroup in previous step of the BB flow //put shell in AAI @@ -337,7 +337,7 @@ public class AAICreateTasks { */ public void createNetworkCollectionInstanceGroup(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); InstanceGroup instanceGroup = serviceInstance.getCollection().getInstanceGroup(); //set name generated for NetworkCollection/NetworkCollectionInstanceGroup in previous step of the BB flow instanceGroup.setInstanceGroupName(execution.getVariable(NETWORK_COLLECTION_NAME)); @@ -356,7 +356,7 @@ public class AAICreateTasks { */ public void connectNetworkToTenant(BuildingBlockExecution execution) { try { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); aaiNetworkResources.connectNetworkToTenant(l3network, execution.getGeneralBuildingBlock().getCloudRegion()); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -370,7 +370,7 @@ public class AAICreateTasks { */ public void connectNetworkToCloudRegion(BuildingBlockExecution execution) { try { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); aaiNetworkResources.connectNetworkToCloudRegion(l3network, execution.getGeneralBuildingBlock().getCloudRegion()); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -390,7 +390,7 @@ public class AAICreateTasks { cloudRegionsToSkip = Arrays.stream(cloudRegions).anyMatch(execution.getGeneralBuildingBlock().getCloudRegion().getLcpCloudRegionId()::equals); } if(!cloudRegionsToSkip) { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); aaiVnfResources.connectVnfToCloudRegion(vnf, execution.getGeneralBuildingBlock().getCloudRegion()); } } catch (Exception ex) { @@ -405,7 +405,7 @@ public class AAICreateTasks { */ public void connectVnfToTenant(BuildingBlockExecution execution) { try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); aaiVnfResources.connectVnfToTenant(vnf, execution.getGeneralBuildingBlock().getCloudRegion()); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -419,8 +419,8 @@ public class AAICreateTasks { */ public void connectNetworkToNetworkCollectionServiceInstance(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); aaiNetworkResources.connectNetworkToNetworkCollectionServiceInstance(l3network, serviceInstance); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -434,8 +434,8 @@ public class AAICreateTasks { */ public void connectNetworkToNetworkCollectionInstanceGroup(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); //connect network only if Instance Group / Collection objects exist if (serviceInstance.getCollection() != null && serviceInstance.getCollection().getInstanceGroup() != null) aaiNetworkResources.connectNetworkToNetworkCollectionInstanceGroup(l3network, serviceInstance.getCollection().getInstanceGroup()); @@ -446,7 +446,7 @@ public class AAICreateTasks { public void createConfiguration(BuildingBlockExecution execution){ try{ - Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID, execution.getLookupMap().get(ResourceKey.CONFIGURATION_ID)); + Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID); aaiConfigurationResources.createConfiguration(configuration); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -455,8 +455,8 @@ public class AAICreateTasks { public void createInstanceGroupVnf(BuildingBlockExecution execution){ try{ - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID, execution.getLookupMap().get(ResourceKey.INSTANCE_GROUP_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID); aaiInstanceGroupResources.createInstanceGroupandConnectServiceInstance(instanceGroup, serviceInstance); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasks.java index 6e4a5f3d15..095fd7f86d 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasks.java @@ -82,8 +82,8 @@ public class AAIDeleteTasks { private AAIInstanceGroupResources aaiInstanceGroupResources; public void deleteVfModule(BuildingBlockExecution execution) throws Exception { - 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)); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); execution.setVariable("aaiVfModuleRollback", false); try { @@ -95,7 +95,7 @@ public class AAIDeleteTasks { } public void deleteVnf(BuildingBlockExecution execution) throws Exception { - GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); execution.setVariable("aaiVnfRollback", false); try { @@ -108,7 +108,7 @@ public class AAIDeleteTasks { public void deleteServiceInstance(BuildingBlockExecution execution) throws Exception { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); aaiSIResources.deleteServiceInstance(serviceInstance); } catch(Exception ex) { @@ -119,7 +119,7 @@ public class AAIDeleteTasks { public void deleteNetwork(BuildingBlockExecution execution) throws Exception { try { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); aaiNetworkResources.deleteNetwork(l3network); execution.setVariable("isRollbackNeeded", true); } @@ -130,7 +130,7 @@ public class AAIDeleteTasks { public void deleteCollection(BuildingBlockExecution execution) throws Exception { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); aaiNetworkResources.deleteCollection(serviceInstance.getCollection()); } catch(Exception ex) { @@ -140,7 +140,7 @@ public class AAIDeleteTasks { public void deleteInstanceGroup(BuildingBlockExecution execution) throws Exception { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); aaiNetworkResources.deleteNetworkInstanceGroup(serviceInstance.getCollection().getInstanceGroup()); } catch(Exception ex) { @@ -150,7 +150,7 @@ public class AAIDeleteTasks { public void deleteVolumeGroup(BuildingBlockExecution execution) { try { - VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); CloudRegion cloudRegion = execution.getGeneralBuildingBlock().getCloudRegion(); aaiVolumeGroupResources.deleteVolumeGroup(volumeGroup, cloudRegion); } catch (Exception ex) { @@ -159,7 +159,7 @@ public class AAIDeleteTasks { } public void deleteConfiguration(BuildingBlockExecution execution) { try { - Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID, execution.getLookupMap().get(ResourceKey.CONFIGURATION_ID)); + Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID); aaiConfigurationResources.deleteConfiguration(configuration); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -168,7 +168,7 @@ public class AAIDeleteTasks { public void deleteInstanceGroupVnf(BuildingBlockExecution execution) { try { - InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID, execution.getLookupMap().get(ResourceKey.INSTANCE_GROUP_ID)); + InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID); aaiInstanceGroupResources.deleteInstanceGroup(instanceGroup); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIFlagTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIFlagTasks.java index ccc9fb0e43..177e09d5a1 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIFlagTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIFlagTasks.java @@ -47,7 +47,7 @@ public class AAIFlagTasks { public void checkVnfInMaintFlag(BuildingBlockExecution execution) { boolean inMaint = false; try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); String vnfId = vnf.getVnfId(); inMaint = aaiVnfResources.checkInMaintFlag(vnfId); } catch (Exception ex) { @@ -60,7 +60,7 @@ public class AAIFlagTasks { public void modifyVnfInMaintFlag(BuildingBlockExecution execution, boolean inMaint) { try { - GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); GenericVnf copiedGenericVnf = genericVnf.shallowCopyId(); @@ -76,7 +76,7 @@ public class AAIFlagTasks { public void checkVnfClosedLoopDisabledFlag(BuildingBlockExecution execution) { boolean isClosedLoopDisabled = false; try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); String vnfId = vnf.getVnfId(); isClosedLoopDisabled = aaiVnfResources.checkVnfClosedLoopDisabledFlag(vnfId); } catch (Exception ex) { @@ -89,7 +89,7 @@ public class AAIFlagTasks { public void modifyVnfClosedLoopDisabledFlag(BuildingBlockExecution execution, boolean closedLoopDisabled) { try { - GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); GenericVnf copiedGenericVnf = genericVnf.shallowCopyId(); copiedGenericVnf.setClosedLoopDisabled(closedLoopDisabled); @@ -104,7 +104,7 @@ public class AAIFlagTasks { public void checkVnfPserversLockedFlag(BuildingBlockExecution execution) { boolean inPserversLocked = false; try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); String vnfId = vnf.getVnfId(); inPserversLocked = aaiVnfResources.checkVnfPserversLockedFlag(vnfId); } catch (Exception ex) { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIQueryTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIQueryTasks.java index e89dffc6d9..e0e139e290 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIQueryTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIQueryTasks.java @@ -71,8 +71,7 @@ public class AAIQueryTasks { public void queryNetworkVpnBinding(BuildingBlockExecution execution) { try { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, - execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network); Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships(); if (!networkRelationships.isPresent()) { @@ -106,8 +105,7 @@ public class AAIQueryTasks { public void getNetworkVpnBinding(BuildingBlockExecution execution) { try { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, - execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network); CreateNetworkRequest createNetworkRequest = execution.getVariable("createNetworkRequest"); @@ -162,8 +160,7 @@ public class AAIQueryTasks { */ public void queryNetworkPolicy(BuildingBlockExecution execution) { try { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, - execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network); Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships(); if (!networkRelationships.isPresent()) { @@ -193,8 +190,7 @@ public class AAIQueryTasks { */ public void queryNetworkTableRef(BuildingBlockExecution execution) { try { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, - execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network); Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships(); if (!networkRelationships.isPresent()) { @@ -229,8 +225,7 @@ public class AAIQueryTasks { public void querySubnet(BuildingBlockExecution execution) { try { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, - execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network); Optional<Relationships> networkRelationships = aaiResultWrapper.getRelationships(); if (!networkRelationships.isPresent()) { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java index 34598ef00a..bc6770cc81 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIUpdateTasks.java @@ -82,7 +82,7 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusAssignedService(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); aaiServiceInstanceResources.updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ASSIGNED); execution.setVariable("aaiServiceInstanceRollback", true); } catch (Exception ex) { @@ -92,7 +92,7 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusActiveService(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); aaiServiceInstanceResources.updateOrchestrationStatusServiceInstance(serviceInstance, OrchestrationStatus.ACTIVE); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -101,7 +101,7 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusAssignedVnf(BuildingBlockExecution execution) { try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); aaiVnfResources.updateOrchestrationStatusVnf(vnf,OrchestrationStatus.ASSIGNED); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -110,7 +110,7 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusActiveVnf(BuildingBlockExecution execution) { try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); aaiVnfResources.updateOrchestrationStatusVnf(vnf,OrchestrationStatus.ACTIVE); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -121,7 +121,7 @@ public class AAIUpdateTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); CloudRegion cloudRegion = gBBInput.getCloudRegion(); volumeGroup.setHeatStackId(""); aaiVolumeGroupResources.updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.ASSIGNED); @@ -134,7 +134,7 @@ public class AAIUpdateTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); CloudRegion cloudRegion = gBBInput.getCloudRegion(); aaiVolumeGroupResources.updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.ACTIVE); @@ -147,7 +147,7 @@ public class AAIUpdateTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); CloudRegion cloudRegion = gBBInput.getCloudRegion(); aaiVolumeGroupResources.updateOrchestrationStatusVolumeGroup(volumeGroup, cloudRegion, OrchestrationStatus.CREATED); @@ -163,7 +163,7 @@ public class AAIUpdateTasks { if (heatStackId == null) { heatStackId = ""; } - VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); CloudRegion cloudRegion = gBBInput.getCloudRegion(); volumeGroup.setHeatStackId(heatStackId); @@ -175,9 +175,9 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusAssignedVfModule(BuildingBlockExecution execution) { try { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); vfModule.setHeatStackId(""); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule,vnf,OrchestrationStatus.ASSIGNED); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -186,8 +186,8 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusPendingActivationVfModule(BuildingBlockExecution execution) { try { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule,vnf,OrchestrationStatus.PENDING_ACTIVATION); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -196,9 +196,9 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusAssignedOrPendingActivationVfModule(BuildingBlockExecution execution) { try { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); vfModule.setHeatStackId(""); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); String multiStageDesign = MULTI_STAGE_DESIGN_OFF; if (vnf.getModelInfoGenericVnf() != null) { multiStageDesign = vnf.getModelInfoGenericVnf().getMultiStageDesign(); @@ -217,8 +217,8 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusCreatedVfModule(BuildingBlockExecution execution) { try { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule,vnf,OrchestrationStatus.CREATED); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -228,8 +228,8 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusDeactivateVfModule(BuildingBlockExecution execution) { execution.setVariable("aaiDeactivateVfModuleRollback", false); try { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule,vnf,OrchestrationStatus.CREATED); execution.setVariable("aaiDeactivateVfModuleRollback", true); } catch (Exception ex) { @@ -266,7 +266,7 @@ public class AAIUpdateTasks { protected void updateNetwork(BuildingBlockExecution execution, OrchestrationStatus status) { try { - L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); updateNetworkAAI(l3Network, status); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -298,7 +298,7 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusActiveNetworkCollection(BuildingBlockExecution execution) { execution.setVariable("aaiNetworkCollectionActivateRollback", false); try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Collection networkCollection = serviceInstance.getCollection(); Collection copiedNetworkCollection = networkCollection.shallowCopyId(); @@ -314,8 +314,8 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusActivateVfModule(BuildingBlockExecution execution) { execution.setVariable("aaiActivateVfModuleRollback", false); try { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); aaiVfModuleResources.updateOrchestrationStatusVfModule(vfModule, vnf, OrchestrationStatus.ACTIVE); execution.setVariable("aaiActivateVfModuleRollback", true); } catch (Exception ex) { @@ -329,8 +329,8 @@ public class AAIUpdateTasks { if (heatStackId == null) { heatStackId = ""; } - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); vfModule.setHeatStackId(heatStackId); aaiVfModuleResources.updateHeatStackIdVfModule(vfModule, vnf); } catch (Exception ex) { @@ -345,7 +345,7 @@ public class AAIUpdateTasks { */ public void updateNetworkCreated(BuildingBlockExecution execution) throws Exception { execution.setVariable("aaiNetworkActivateRollback", false); - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); L3Network copiedl3network = l3network.shallowCopyId(); CreateNetworkResponse response = execution.getVariable("createNetworkResponse"); try { @@ -386,7 +386,7 @@ public class AAIUpdateTasks { * @throws Exception */ public void updateNetworkUpdated(BuildingBlockExecution execution) throws Exception { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); L3Network copiedl3network = l3network.shallowCopyId(); UpdateNetworkResponse response = execution.getVariable("updateNetworkResponse"); try { @@ -410,7 +410,7 @@ public class AAIUpdateTasks { public void updateObjectNetwork(BuildingBlockExecution execution) { try { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); aaiNetworkResources.updateNetwork(l3network); } catch(Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -423,7 +423,7 @@ public class AAIUpdateTasks { */ public void updateServiceInstance(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); aaiServiceInstanceResources.updateServiceInstance(serviceInstance); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -432,7 +432,7 @@ public class AAIUpdateTasks { public void updateObjectVnf(BuildingBlockExecution execution) { try { - GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); aaiVnfResources.updateObjectVnf(genericVnf); } catch(Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -442,9 +442,9 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusDeleteVfModule(BuildingBlockExecution execution) { execution.setVariable("aaiDeleteVfModuleRollback", false); try { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); vfModule.setHeatStackId(""); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); VfModule copiedVfModule = vfModule.shallowCopyId(); copiedVfModule.setHeatStackId(""); @@ -457,8 +457,8 @@ public class AAIUpdateTasks { public void updateModelVfModule(BuildingBlockExecution execution) { try { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); aaiVfModuleResources.changeAssignVfModule(vfModule, vnf); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -466,7 +466,7 @@ public class AAIUpdateTasks { } public void updateOrchestrationStatusActivateFabricConfiguration(BuildingBlockExecution execution) { try { - Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID, execution.getLookupMap().get(ResourceKey.CONFIGURATION_ID)); + Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID); aaiConfigurationResources.updateOrchestrationStatusConfiguration(configuration, OrchestrationStatus.ACTIVE); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -475,7 +475,7 @@ public class AAIUpdateTasks { public void updateOrchestrationStatusDeactivateFabricConfiguration(BuildingBlockExecution execution) { try { - Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID, execution.getLookupMap().get(ResourceKey.CONFIGURATION_ID)); + Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID); aaiConfigurationResources.updateOrchestrationStatusConfiguration(configuration, OrchestrationStatus.ASSIGNED); } catch (Exception ex) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); @@ -486,7 +486,7 @@ public class AAIUpdateTasks { try { String ipv4OamAddress = execution.getVariable("oamManagementV4Address"); if (ipv4OamAddress != null) { - GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); GenericVnf copiedGenericVnf = genericVnf.shallowCopyId(); genericVnf.setIpv4OamAddress(ipv4OamAddress); @@ -503,7 +503,7 @@ public class AAIUpdateTasks { try { String managementV6Address = execution.getVariable("oamManagementV6Address"); if (managementV6Address != null) { - GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); GenericVnf copiedGenericVnf = genericVnf.shallowCopyId(); genericVnf.setManagementV6Address(managementV6Address); @@ -520,8 +520,8 @@ public class AAIUpdateTasks { try { String contrailServiceInstanceFqdn = execution.getVariable("contrailServiceInstanceFqdn"); if (contrailServiceInstanceFqdn != null) { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); vfModule.setContrailServiceInstanceFqdn(contrailServiceInstanceFqdn); aaiVfModuleResources.updateContrailServiceInstanceFqdnVfModule(vfModule, vnf); } @@ -530,4 +530,12 @@ public class AAIUpdateTasks { } } + public void updateOrchestrationStatusConfigAssignedVnf(BuildingBlockExecution execution) { + try { + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + aaiVnfResources.updateOrchestrationStatusVnf(vnf, OrchestrationStatus.CONFIGASSIGNED); + } catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasks.java index 4c531d46f9..67d2864204 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasks.java @@ -53,8 +53,8 @@ public class NetworkAdapterCreateTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); Map<String, String> userInput = gBBInput.getUserInput(); String cloudRegionPo = execution.getVariable("cloudRegionPo"); @@ -69,7 +69,7 @@ public class NetworkAdapterCreateTasks { public void processResponseFromOpenstack(BuildingBlockExecution execution) { try { - L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); CreateNetworkResponse createNetworkResponse = execution.getVariable("createNetworkResponse"); if(createNetworkResponse != null) { @@ -90,8 +90,8 @@ public class NetworkAdapterCreateTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); CreateNetworkResponse createNetworkResponse = execution.getVariable("createNetworkResponse"); Map<String, String> userInput = gBBInput.getUserInput(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasks.java index 5eab6110f9..7e0c5f6da4 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasks.java @@ -46,8 +46,8 @@ public class NetworkAdapterDeleteTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); DeleteNetworkRequest deleteNetworkRequest = networkAdapterObjectMapper.deleteNetworkRequestMapper(gBBInput.getRequestContext(), gBBInput.getCloudRegion(), serviceInstance, l3Network); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java index 61687081d9..9eeba0445b 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasks.java @@ -52,8 +52,8 @@ public class NetworkAdapterUpdateTasks { public void updateNetwork(BuildingBlockExecution execution) { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); UpdateNetworkRequest updateNetworkRequest = networkAdapterObjectMapper.createNetworkUpdateRequestMapper(gBBInput.getRequestContext(), gBBInput.getCloudRegion(), gBBInput.getOrchContext(), serviceInstance, l3Network, gBBInput.getUserInput(), gBBInput.getCustomer()); execution.setVariable("networkAdapterRequest", updateNetworkRequest); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java index 1815fcd827..ae9e6e7488 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasks.java @@ -65,12 +65,12 @@ public class VnfAdapterCreateTasks { ServiceInstance serviceInstance = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0); - GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); - VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); VfModule vfModule; String sdncVfModuleQueryResponse = null; try { - vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); + vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); if(vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) { sdncVfModuleQueryResponse = execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()); } @@ -94,11 +94,11 @@ public class VnfAdapterCreateTasks { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); ServiceInstance serviceInstance = gBBInput.getCustomer().getServiceSubscription().getServiceInstances().get(0); - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_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); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); VolumeGroup volumeGroup = null; try { - volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); } catch(BBObjectNotFoundException bbException) { } CloudRegion cloudRegion = gBBInput.getCloudRegion(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java index 759ec61878..a96e2702cd 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasks.java @@ -58,8 +58,8 @@ public class VnfAdapterDeleteTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); DeleteVolumeGroupRequest deleteVolumeGroupRequest = vnfAdapterVolumeGroupResources.deleteVolumeGroupRequest(gBBInput.getRequestContext(), gBBInput.getCloudRegion(), serviceInstance, volumeGroup); execution.setVariable(VNFREST_REQUEST, deleteVolumeGroupRequest.toXmlString()); @@ -73,9 +73,9 @@ public class VnfAdapterDeleteTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); - GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); DeleteVfModuleRequest deleteVfModuleRequest = vnfAdapterVfModuleResources.deleteVfModuleRequest( gBBInput.getRequestContext(), gBBInput.getCloudRegion(), serviceInstance, genericVnf, vfModule); execution.setVariable(VNFREST_REQUEST, deleteVfModuleRequest.toXmlString()); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java index 05ddb2e417..e854efd414 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java @@ -74,7 +74,7 @@ public class VnfAdapterImpl { public void preProcessVnfAdapter(BuildingBlockExecution execution) { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); execution.setVariable("mso-request-id", gBBInput.getRequestContext().getMsoRequestId()); execution.setVariable("mso-service-instance-id", serviceInstance.getServiceInstanceId()); execution.setVariable("heatStackId", null); @@ -93,7 +93,7 @@ public class VnfAdapterImpl { if (!StringUtils.isEmpty( vnfAdapterResponse)) { Object vnfRestResponse = unMarshal(vnfAdapterResponse); if(vnfRestResponse instanceof CreateVfModuleResponse) { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); String heatStackId = ((CreateVfModuleResponse) vnfRestResponse).getVfModuleStackId(); if(!StringUtils.isEmpty(heatStackId)) { vfModule.setHeatStackId(heatStackId); @@ -104,8 +104,8 @@ public class VnfAdapterImpl { processVfModuleOutputs(execution, vfModuleOutputs); } } else if(vnfRestResponse instanceof DeleteVfModuleResponse) { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_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); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); Boolean vfModuleDelete = ((DeleteVfModuleResponse) vnfRestResponse).getVfModuleDeleted(); if(null!= vfModuleDelete && vfModuleDelete) { vfModule.setHeatStackId(null); @@ -128,7 +128,7 @@ public class VnfAdapterImpl { } } } else if(vnfRestResponse instanceof CreateVolumeGroupResponse) { - VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); String heatStackId = ((CreateVolumeGroupResponse) vnfRestResponse).getVolumeGroupStackId(); if(!StringUtils.isEmpty(heatStackId)) { volumeGroup.setHeatStackId(heatStackId); @@ -137,7 +137,7 @@ public class VnfAdapterImpl { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "HeatStackId is missing from create VolumeGroup Vnf Adapter response."); } } else if(vnfRestResponse instanceof DeleteVolumeGroupResponse) { - VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); Boolean volumeGroupDelete = ((DeleteVolumeGroupResponse) vnfRestResponse).getVolumeGroupDeleted(); if(null!= volumeGroupDelete && volumeGroupDelete) { volumeGroup.setHeatStackId(null); @@ -178,8 +178,8 @@ public class VnfAdapterImpl { return; } try { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_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); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); List<String> contrailNetworkPolicyFqdnList = new ArrayList<String>(); Iterator<String> keys = vfModuleOutputs.keySet().iterator(); while (keys.hasNext()) { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java new file mode 100644 index 0000000000..d03173d0ac --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/Constants.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +/** + * @author waqas.ikram@est.tech + */ +public class Constants { + + public static final String CREATE_VNF_REQUEST_PARAM_NAME = "createVnfRequest"; + public static final String CREATE_VNF_RESPONSE_PARAM_NAME = "createVnfResponse"; + + public static final String DOT = "."; + public static final String UNDERSCORE = "_"; + public static final String SPACE = "\\s+"; + + public static final String VNFM_ADAPTER_DEFAULT_URL = "http://so-vnfm-adapter.onap:9092/so/vnfm-adapter/v1/"; + public static final String VNFM_ADAPTER_DEFAULT_AUTH = "Basic dm5mbTpwYXNzd29yZDEk"; + + + private Constants() {} +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTask.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTask.java new file mode 100644 index 0000000000..23ddb6f3f7 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTask.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.CREATE_VNF_REQUEST_PARAM_NAME; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.CREATE_VNF_RESPONSE_PARAM_NAME; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.DOT; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.SPACE; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.UNDERSCORE; +import static org.onap.so.bpmn.servicedecomposition.entities.ResourceKey.GENERIC_VNF_ID; + +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; +import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; +import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; +import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf; +import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.vnfmadapter.v1.model.CreateVnfRequest; +import org.onap.vnfmadapter.v1.model.CreateVnfResponse; +import org.onap.vnfmadapter.v1.model.Tenant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.google.common.base.Optional; + +/** + * This class is executed from EtsiVnfInstantiateBB building block and it sends the create request + * to the VNFM adapter + * + * @author waqas.ikram@est.tech + */ +@Component +public class VnfmAdapterCreateVnfTask { + + private static final Logger LOGGER = LoggerFactory.getLogger(VnfmAdapterCreateVnfTask.class); + + private final ExtractPojosForBB extractPojosForBB; + private final ExceptionBuilder exceptionUtil; + private final VnfmAdapterServiceProvider vnfmAdapterServiceProvider; + + @Autowired + public VnfmAdapterCreateVnfTask(final ExceptionBuilder exceptionUtil, final ExtractPojosForBB extractPojosForBB, + final VnfmAdapterServiceProvider vnfmAdapterServiceProvider) { + this.exceptionUtil = exceptionUtil; + this.extractPojosForBB = extractPojosForBB; + this.vnfmAdapterServiceProvider = vnfmAdapterServiceProvider; + } + + /** + * Create {@link CreateVnfRequest} object with required fields and store it in + * {@link org.camunda.bpm.engine.delegate.DelegateExecution} + * + * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl} + */ + public void buildCreateVnfRequest(final BuildingBlockExecution execution) { + try { + LOGGER.debug("Executing buildCreateVnfRequest ..."); + + final GeneralBuildingBlock buildingBlock = execution.getGeneralBuildingBlock(); + final CloudRegion cloudRegion = buildingBlock.getCloudRegion(); + + final GenericVnf vnf = extractPojosForBB.extractByKey(execution, GENERIC_VNF_ID); + final ModelInfoGenericVnf modelInfoGenericVnf = vnf.getModelInfoGenericVnf(); + + final CreateVnfRequest createVnfRequest = new CreateVnfRequest(); + + createVnfRequest.setName(getName(vnf.getVnfName(), modelInfoGenericVnf.getModelInstanceName())); + createVnfRequest.setTenant(getTenant(cloudRegion)); + + LOGGER.info("CreateVnfRequest : {}", createVnfRequest); + + execution.setVariable(CREATE_VNF_REQUEST_PARAM_NAME, createVnfRequest); + + LOGGER.debug("Finished executing buildCreateVnfRequest ..."); + } catch (final Exception exception) { + LOGGER.error("Unable to execute buildCreateVnfRequest", exception); + exceptionUtil.buildAndThrowWorkflowException(execution, 1200, exception); + } + } + + /** + * Invoke VNFM adapter to create and instantiate VNF + * + * @param execution {@link org.onap.so.bpmn.common.DelegateExecutionImpl} + */ + public void invokeVnfmAdapter(final BuildingBlockExecution execution) { + try { + LOGGER.debug("Executing invokeVnfmAdapter ..."); + final CreateVnfRequest request = execution.getVariable(CREATE_VNF_REQUEST_PARAM_NAME); + + final GenericVnf vnf = extractPojosForBB.extractByKey(execution, GENERIC_VNF_ID); + + final Optional<CreateVnfResponse> response = + vnfmAdapterServiceProvider.invokeCreateInstantiationRequest(vnf.getVnfId(), request); + + if (!response.isPresent()) { + final String errorMessage = "Unexpected error while processing create and instantiation request"; + LOGGER.error(errorMessage); + exceptionUtil.buildAndThrowWorkflowException(execution, 1201, errorMessage); + } + + final CreateVnfResponse vnfResponse = response.get(); + + LOGGER.debug("Vnf instantiation response: {}", vnfResponse); + execution.setVariable(CREATE_VNF_RESPONSE_PARAM_NAME, vnfResponse); + + LOGGER.debug("Finished executing invokeVnfmAdapter ..."); + } catch (final Exception exception) { + LOGGER.error("Unable to invoke create and instantiation request", exception); + exceptionUtil.buildAndThrowWorkflowException(execution, 1202, exception); + } + } + + private Tenant getTenant(final CloudRegion cloudRegion) { + final Tenant tenant = new Tenant(); + tenant.setCloudOwner(cloudRegion.getCloudOwner()); + tenant.setRegionName(cloudRegion.getLcpCloudRegionId()); + tenant.setTenantId(cloudRegion.getTenantId()); + return tenant; + } + + private String getName(final String vnfName, final String modelInstanceName) { + if (modelInstanceName != null) { + return (vnfName + DOT + modelInstanceName).replaceAll(SPACE, UNDERSCORE); + } + return vnfName != null ? vnfName.replaceAll(SPACE, UNDERSCORE) : vnfName; + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfiguration.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfiguration.java new file mode 100644 index 0000000000..1046b6bf26 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfiguration.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; + +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.configuration.rest.HttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProviderImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +/** + * Provides {@link org.onap.so.rest.service.VnfmAdapterServiceProvider} configuration for + * {@link VnfmAdapterCreateVnfTask} + * + * @author waqas.ikram@est.tech + */ +@Configuration +public class VnfmAdapterCreateVnfTaskConfiguration { + + @Bean + public HttpRestServiceProvider databaseHttpRestServiceProvider( + @Qualifier(CONFIGURABLE_REST_TEMPLATE) @Autowired final RestTemplate restTemplate, + @Autowired final VnfmBasicHttpConfigProvider etsiVnfmAdapter) { + return getHttpRestServiceProvider(restTemplate, new BasicHttpHeadersProvider(etsiVnfmAdapter.getAuth())); + } + + private HttpRestServiceProvider getHttpRestServiceProvider(final RestTemplate restTemplate, + final HttpHeadersProvider httpHeadersProvider) { + return new HttpRestServiceProviderImpl(restTemplate, httpHeadersProvider); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/MockResourceApplication.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProvider.java index 6c62920781..02303ef09d 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/mock/MockResourceApplication.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProvider.java @@ -1,55 +1,38 @@ /*- * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ -package org.onap.so.bpmn.mock; +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; -import java.util.HashSet; -import java.util.Set; +import org.onap.vnfmadapter.v1.model.CreateVnfRequest; +import org.onap.vnfmadapter.v1.model.CreateVnfResponse; -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; +import com.google.common.base.Optional; -import org.junit.Ignore; /** + * Provide a service which interacts with VNFM adapter for instantiating, monitoring VNF * - * JAX RS Application wiring for Mock Resource + * @author waqas.ikram@est.tech */ -@ApplicationPath("/console") -@Ignore -public class MockResourceApplication extends Application { - - private Set<Object> singletons = new HashSet<>(); - private Set<Class<?>> classes = new HashSet<>(); - - public MockResourceApplication() { - singletons.add(new MockResource()); - } +public interface VnfmAdapterServiceProvider { - @Override - public Set<Class<?>> getClasses() { - return classes; - } + Optional<CreateVnfResponse> invokeCreateInstantiationRequest(final String vnfId, final CreateVnfRequest request); - @Override - public Set<Object> getSingletons() { - return singletons; - } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java new file mode 100644 index 0000000000..afdcccfd36 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImpl.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import org.onap.so.rest.exceptions.InvalidRestRequestException; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.vnfmadapter.v1.model.CreateVnfRequest; +import org.onap.vnfmadapter.v1.model.CreateVnfResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +import com.google.common.base.Optional; + +/** + * @author waqas.ikram@est.tech + */ +@Service +public class VnfmAdapterServiceProviderImpl implements VnfmAdapterServiceProvider { + + private static final Logger LOGGER = LoggerFactory.getLogger(VnfmAdapterServiceProviderImpl.class); + + private final VnfmAdapterUrlProvider urlProvider; + private final HttpRestServiceProvider httpServiceProvider; + + @Autowired + public VnfmAdapterServiceProviderImpl(final VnfmAdapterUrlProvider urlProvider, + final HttpRestServiceProvider httpServiceProvider) { + this.urlProvider = urlProvider; + this.httpServiceProvider = httpServiceProvider; + } + + @Override + public Optional<CreateVnfResponse> invokeCreateInstantiationRequest(final String vnfId, + final CreateVnfRequest request) { + try { + final String url = urlProvider.getCreateInstantiateUrl(vnfId); + + final ResponseEntity<CreateVnfResponse> response = + httpServiceProvider.postHttpRequest(request, url, CreateVnfResponse.class); + + final HttpStatus httpStatus = response.getStatusCode(); + if (!(httpStatus.equals(HttpStatus.ACCEPTED)) && !(httpStatus.equals(HttpStatus.OK))) { + LOGGER.error("Unable to invoke HTTP POST using URL: {}, Response Code: {}", url, httpStatus.value()); + return Optional.absent(); + } + + if (!response.hasBody()) { + LOGGER.error("Received response without body: {}", response); + return Optional.absent(); + } + + final CreateVnfResponse createVnfResponse = response.getBody(); + + if (createVnfResponse.getJobId() == null || createVnfResponse.getJobId().isEmpty()) { + LOGGER.error("Received invalid instantiation response: {}", response); + return Optional.absent(); + } + + return Optional.of(createVnfResponse); + } catch (final RestProcessingException | InvalidRestRequestException httpInvocationException) { + LOGGER.error("Unexpected error while processing create and instantiation request", httpInvocationException); + return Optional.absent(); + } + + } +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProvider.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProvider.java new file mode 100644 index 0000000000..03ee0712e7 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProvider.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import java.net.URI; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.util.UriComponentsBuilder; + +/** + * + * Provides VNFM adapter {@link java.net.URL} + * + * @author waqas.ikram@est.tech + * + */ +@Service +public class VnfmAdapterUrlProvider { + + private final URI baseUri; + + @Autowired + public VnfmAdapterUrlProvider(final VnfmBasicHttpConfigProvider etsiVnfmAdapter) { + this.baseUri = UriComponentsBuilder.fromHttpUrl(etsiVnfmAdapter.getUrl()).build().toUri(); + } + + /** + * Get VNFM create and instantiate URL + * + * @param vnfId The identifier of the VNF. This must be the vnf-id of an existing generic-vnf in + * AAI. + * @return VNFM create and instantiate URL + */ + public String getCreateInstantiateUrl(final String vnfId) { + return UriComponentsBuilder.fromUri(baseUri).pathSegment("vnfs").pathSegment(vnfId).build().toString(); + } + + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmBasicHttpConfigProvider.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmBasicHttpConfigProvider.java new file mode 100644 index 0000000000..c9b1ad1ce1 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmBasicHttpConfigProvider.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNFM_ADAPTER_DEFAULT_AUTH; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.VNFM_ADAPTER_DEFAULT_URL; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * Provides VNFM adapter {@link java.net.URI} and basic authorization values + * + * @author waqas.ikram@est.tech + */ +@Configuration +@ConfigurationProperties(prefix = "so.vnfm.adapter") +public class VnfmBasicHttpConfigProvider { + + private String url = VNFM_ADAPTER_DEFAULT_URL; + + private String auth = VNFM_ADAPTER_DEFAULT_AUTH; + + /** + * @return the url + */ + public String getUrl() { + return url; + } + + /** + * @param url the url to set + */ + public void setUrl(final String url) { + this.url = url; + } + + /** + * @return the auth + */ + public String getAuth() { + return auth; + } + + /** + * @param auth the auth to set + */ + public void setAuth(final String auth) { + this.auth = auth; + } + + @Override + public String toString() { + return "EtsiVnfmAdapter [url=" + url + ", auth=" + auth + "]"; + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java index 876a555b10..f9e4177315 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasks.java @@ -82,7 +82,7 @@ public class AppcRunTasks { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); GenericVnf vnf = null; try { - vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); } catch (BBObjectNotFoundException e) { exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "No valid VNF exists"); } @@ -110,7 +110,7 @@ public class AppcRunTasks { String vfModuleId = null; VfModule vfModule = null; try { - vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); + vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); } catch (BBObjectNotFoundException e) { } if (vfModule != null) { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java index 8cb7cbbe91..f6e07c8303 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/audit/AuditTasks.java @@ -71,7 +71,7 @@ public class AuditTasks { AuditInventory auditInventory = new AuditInventory(); GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); CloudRegion cloudRegion = gBBInput.getCloudRegion(); auditInventory.setCloudOwner(cloudRegion.getCloudOwner()); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetwork.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetwork.java index 753a29f208..c3106d6e49 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetwork.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetwork.java @@ -47,8 +47,7 @@ public class AssignNetwork { public boolean networkFoundByName(BuildingBlockExecution execution) { boolean networkFound = false; try { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, - execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); if (!OrchestrationStatus.PRECREATED.equals(l3network.getOrchestrationStatus())){ networkFound = true; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnf.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnf.java index ee80ba4c55..0aa3142996 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnf.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnf.java @@ -50,7 +50,7 @@ public class AssignVnf { public void createInstanceGroups(BuildingBlockExecution execution) { try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); List<InstanceGroup> instanceGroups = vnf.getInstanceGroups(); for(InstanceGroup instanceGroup : instanceGroups) { if(ModelInfoInstanceGroup.TYPE_VNFC.equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java new file mode 100644 index 0000000000..242135adb8 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnf.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.bpmn.infrastructure.flowspecific.tasks; + +import java.util.Map; +import java.util.UUID; + +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.entities.GeneralBuildingBlock; +import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB; +import org.onap.so.client.cds.beans.AbstractCDSPropertiesBean; +import org.onap.so.client.cds.beans.ConfigAssignPropertiesForVnf; +import org.onap.so.client.cds.beans.ConfigAssignRequestVnf; +import org.onap.so.client.exception.ExceptionBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * + * Get vnf related data and config assign + * + */ +@Component +public class ConfigAssignVnf { + + private static final Logger logger = LoggerFactory.getLogger(ConfigAssignVnf.class); + private static final String ORIGINATOR_ID = "SO"; + private static final String ACTION_NAME = "config-assign"; + private static final String MODE = "sync"; + + @Autowired + private ExceptionBuilder exceptionUtil; + @Autowired + private ExtractPojosForBB extractPojosForBB; + + /** + * Getting the vnf data, blueprint name, blueprint version etc and setting them + * in execution object and calling the subprocess. + * + * @param execution + */ + public void preProcessAbstractCDSProcessing(BuildingBlockExecution execution) { + logger.info("Start preProcessAbstractCDSProcessing "); + try { + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + + Map<String, Object> userParams = execution.getGeneralBuildingBlock().getRequestContext().getUserParams(); + + ConfigAssignPropertiesForVnf configAssignPropertiesForVnf = new ConfigAssignPropertiesForVnf(); + configAssignPropertiesForVnf.setServiceInstanceId(serviceInstance.getServiceInstanceId()); + configAssignPropertiesForVnf + .setServiceModelUuid(serviceInstance.getModelInfoServiceInstance().getModelUuid()); + configAssignPropertiesForVnf + .setVnfCustomizationUuid(vnf.getModelInfoGenericVnf().getModelCustomizationUuid()); + configAssignPropertiesForVnf.setVnfId(vnf.getVnfId()); + configAssignPropertiesForVnf.setVnfName(vnf.getVnfName()); + + for (Map.Entry<String, Object> entry : userParams.entrySet()) { + configAssignPropertiesForVnf.setUserParam(entry.getKey(), entry.getValue()); + } + + ConfigAssignRequestVnf configAssignRequestVnf = new ConfigAssignRequestVnf(); + configAssignRequestVnf.setResolutionKey(vnf.getVnfName()); + configAssignRequestVnf.setConfigAssignPropertiesForVnf(configAssignPropertiesForVnf); + + String blueprintName = vnf.getBlueprintName(); + String blueprintVersion = vnf.getBlueprintVersion(); + + AbstractCDSPropertiesBean abstractCDSPropertiesBean = new AbstractCDSPropertiesBean(); + + abstractCDSPropertiesBean.setBlueprintName(blueprintName); + abstractCDSPropertiesBean.setBlueprintVersion(blueprintVersion); + abstractCDSPropertiesBean.setRequestObject(configAssignRequestVnf.toString()); + + GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); + + abstractCDSPropertiesBean.setOriginatorId(ORIGINATOR_ID); + abstractCDSPropertiesBean.setRequestId(gBBInput.getRequestContext().getMsoRequestId()); + abstractCDSPropertiesBean.setSubRequestId(UUID.randomUUID().toString()); + abstractCDSPropertiesBean.setActionName(ACTION_NAME); + abstractCDSPropertiesBean.setMode(MODE); + execution.setVariable("executionObject", abstractCDSPropertiesBean); + + } catch (Exception ex) { + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex); + } + } + +} diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java index 717d0deff6..4cd0321578 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOut.java @@ -81,7 +81,7 @@ public class ConfigurationScaleOut { String configScaleOutPayloadString = null; ControllerSelectionReference controllerSelectionReference; ConfigScaleOutPayload configPayload = new ConfigScaleOutPayload(); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); String vnfId = vnf.getVnfId(); String vnfName = vnf.getVnfName(); String vnfType = vnf.getVnfType(); @@ -89,7 +89,7 @@ public class ConfigurationScaleOut { controllerSelectionReference = catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory(vnfType, actionCategory); String controllerName = controllerSelectionReference.getControllerName(); - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); String sdncVfModuleQueryResponse = execution.getVariable("SDNCQueryResponse_" + vfModule.getVfModuleId()); Map<String, String> paramsMap = new HashMap<>(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java index 962d4fa8c4..8cad8f93ec 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetwork.java @@ -55,8 +55,8 @@ public class CreateNetwork { public void buildCreateNetworkRequest(BuildingBlockExecution execution) throws Exception { try{ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); Map<String, String> userInput = gBBInput.getUserInput(); String cloudRegionPo = execution.getVariable("cloudRegionPo"); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java index 060775e1d7..5665302b2a 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollection.java @@ -54,7 +54,7 @@ public class CreateNetworkCollection { */ public void buildNetworkCollectionName(BuildingBlockExecution execution) throws Exception { try{ - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); InstanceGroup instanceGroup = serviceInstance.getCollection().getInstanceGroup(); if(instanceGroup.getModelInfoInstanceGroup() != null) { //Build collection name assembling SI name and IG function @@ -84,7 +84,7 @@ public class CreateNetworkCollection { public void connectCollectionToInstanceGroup(BuildingBlockExecution execution) throws Exception { execution.setVariable("connectCollectionToInstanceGroupRollback", false); try{ - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Collection networkCollection = serviceInstance.getCollection(); aaiNetworkResources.connectNetworkCollectionInstanceGroupToNetworkCollection(networkCollection.getInstanceGroup(), networkCollection); execution.setVariable("connectCollectionToInstanceGroupRollback", true); @@ -101,7 +101,7 @@ public class CreateNetworkCollection { public void connectInstanceGroupToCloudRegion(BuildingBlockExecution execution) throws Exception { execution.setVariable("connectInstanceGroupToCloudRegionRollback", false); try{ - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Collection networkCollection = serviceInstance.getCollection(); aaiNetworkResources.connectInstanceGroupToCloudRegion(networkCollection.getInstanceGroup(), execution.getGeneralBuildingBlock().getCloudRegion()); execution.setVariable("connectInstanceGroupToCloudRegionRollback", true); @@ -118,7 +118,7 @@ public class CreateNetworkCollection { public void connectCollectionToServiceInstance(BuildingBlockExecution execution) throws Exception { execution.setVariable("connectCollectionToServiceInstanceRollback", false); try{ - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Collection networkCollection = serviceInstance.getCollection(); aaiNetworkResources.connectNetworkCollectionToServiceInstance(networkCollection, serviceInstance); execution.setVariable("connectCollectionToServiceInstanceRollback", true); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java index ce14bde0b3..f0db5eda2e 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheck.java @@ -60,7 +60,7 @@ public class GenericVnfHealthCheck { try { ControllerSelectionReference controllerSelectionReference; - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); String vnfId = vnf.getVnfId(); String vnfName = vnf.getVnfName(); String vnfType = vnf.getVnfType(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java index c7fd41c77a..9a7d695c01 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBB.java @@ -67,8 +67,7 @@ public class UnassignNetworkBB { public void checkRelationshipRelatedTo(BuildingBlockExecution execution, String relatedToValue) throws Exception { try { - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, - execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); AAIResultWrapper aaiResultWrapper = aaiNetworkResources.queryNetworkWrapperById(l3network); Optional<org.onap.aai.domain.yang.L3Network> network = aaiResultWrapper.asBean(org.onap.aai.domain.yang.L3Network.class); if (networkBBUtils.isRelationshipRelatedToExists(network, relatedToValue)) { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnf.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnf.java index b9360b3d81..afa9b439db 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnf.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnf.java @@ -48,7 +48,7 @@ public class UnassignVnf { public void deleteInstanceGroups(BuildingBlockExecution execution) { try { - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); List<InstanceGroup> instanceGroups = vnf.getInstanceGroups(); for(InstanceGroup instanceGroup : instanceGroups) { if(ModelInfoInstanceGroup.TYPE_VNFC.equalsIgnoreCase(instanceGroup.getModelInfoInstanceGroup().getType())) { diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java index cb4ac5c9d9..119716a58d 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasks.java @@ -42,7 +42,7 @@ public class NamingServiceCreateTasks { private NamingServiceResources namingServiceResources; public void createInstanceGroupName(BuildingBlockExecution execution) throws Exception { - InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID, execution.getLookupMap().get(ResourceKey.INSTANCE_GROUP_ID)); + InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID); String policyInstanceName = execution.getVariable("policyInstanceName"); String nfNamingCode = execution.getVariable("nfNamingCode"); String generatedInstanceGroupName = ""; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java index ddea2724bc..c998e4aa75 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasks.java @@ -42,7 +42,7 @@ public class NamingServiceDeleteTasks { private NamingServiceResources namingServiceResources; public void deleteInstanceGroupName(BuildingBlockExecution execution) throws Exception { - InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID, execution.getLookupMap().get(ResourceKey.INSTANCE_GROUP_ID)); + InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID); try { namingServiceResources.deleteInstanceGroupName(instanceGroup); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java index 3793adc5d0..31f4b33e0c 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTasks.java @@ -67,8 +67,8 @@ public class SDNCActivateTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); RequestContext requestContext = gBBInput.getRequestContext(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); CloudRegion cloudRegion = gBBInput.getCloudRegion(); Customer customer = gBBInput.getCustomer(); GenericResourceApiVnfOperationInformation req = sdncVnfResources.activateVnf(vnf, serviceInstance, customer, cloudRegion, requestContext); @@ -89,8 +89,8 @@ public class SDNCActivateTasks { public void activateNetwork(BuildingBlockExecution execution) throws BBObjectNotFoundException { try{ GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Customer customer = gBBInput.getCustomer(); RequestContext requestContext = gBBInput.getRequestContext(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); @@ -111,12 +111,9 @@ public class SDNCActivateTasks { GenericVnf vnf = null; VfModule vfModule = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, - execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, - execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); - vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, - execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); Customer customer = gBBInput.getCustomer(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.activateVfModule(vfModule, vnf, serviceInstance, customer, diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java index 715322bef3..cbb1f34ae5 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasks.java @@ -71,7 +71,7 @@ public class SDNCAssignTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); RequestContext requestContext = gBBInput.getRequestContext(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Customer customer = gBBInput.getCustomer(); GenericResourceApiServiceOperationInformation req = sdncSIResources.assignServiceInstance(serviceInstance, customer, requestContext); SDNCRequest sdncRequest = new SDNCRequest(); @@ -87,8 +87,8 @@ public class SDNCAssignTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); RequestContext requestContext = gBBInput.getRequestContext(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); Customer customer = gBBInput.getCustomer(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); GenericResourceApiVnfOperationInformation req = sdncVnfResources.assignVnf(vnf, serviceInstance, customer, cloudRegion, requestContext, Boolean.TRUE.equals(vnf.isCallHoming())); @@ -105,12 +105,12 @@ public class SDNCAssignTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); RequestContext requestContext = gBBInput.getRequestContext(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - GenericVnf vnf = 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)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); VolumeGroup volumeGroup = null; try{ - volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); } catch (BBObjectNotFoundException e){ logger.info("No volume group was found."); } @@ -134,8 +134,8 @@ public class SDNCAssignTasks { public void assignNetwork(BuildingBlockExecution execution) { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + L3Network l3network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Customer customer = gBBInput.getCustomer(); RequestContext requestContext = gBBInput.getRequestContext(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java index 592b831d62..59e46e1667 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasks.java @@ -63,7 +63,7 @@ public class SDNCChangeAssignTasks { public void changeModelServiceInstance(BuildingBlockExecution execution) { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); GenericResourceApiServiceOperationInformation req = sdncServiceInstanceResources.changeModelServiceInstance(serviceInstance, gBBInput.getCustomer(), gBBInput.getRequestContext()); SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); @@ -77,8 +77,8 @@ public class SDNCChangeAssignTasks { public void changeModelVnf(BuildingBlockExecution execution) { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); - 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); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); GenericResourceApiVnfOperationInformation req = sdncVnfResources.changeModelVnf(genericVnf, serviceInstance, gBBInput.getCustomer(), gBBInput.getCloudRegion(), gBBInput.getRequestContext()); SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); @@ -92,8 +92,8 @@ public class SDNCChangeAssignTasks { public void changeAssignNetwork(BuildingBlockExecution execution) { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); GenericResourceApiNetworkOperationInformation req = sdncNetworkResources.changeAssignNetwork(network, serviceInstance, gBBInput.getCustomer(), gBBInput.getRequestContext(), gBBInput.getCloudRegion()); SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); @@ -109,9 +109,9 @@ public class SDNCChangeAssignTasks { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); RequestContext requestContext = gBBInput.getRequestContext(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - GenericVnf vnf = 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)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); Customer customer = gBBInput.getCustomer(); GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.changeAssignVfModule(vfModule, vnf, serviceInstance, customer, cloudRegion, requestContext); SDNCRequest sdncRequest = new SDNCRequest(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java index d7313ad9a4..8202a14fa3 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTasks.java @@ -69,9 +69,9 @@ public class SDNCDeactivateTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); RequestContext requestContext = gBBInput.getRequestContext(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - GenericVnf vnf = 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)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); Customer customer = gBBInput.getCustomer(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.deactivateVfModule(vfModule, vnf, serviceInstance, customer, @@ -95,8 +95,8 @@ public class SDNCDeactivateTasks { RequestContext requestContext = gBBInput.getRequestContext(); ServiceInstance serviceInstance = null; GenericVnf vnf = null; - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); CloudRegion cloudRegion = gBBInput.getCloudRegion(); Customer customer = gBBInput.getCustomer(); GenericResourceApiVnfOperationInformation req = sdncVnfResources.deactivateVnf(vnf, serviceInstance, customer, cloudRegion, requestContext); @@ -118,8 +118,7 @@ public class SDNCDeactivateTasks { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); RequestContext requestContext = gBBInput.getRequestContext(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, - execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Customer customer = gBBInput.getCustomer(); GenericResourceApiServiceOperationInformation req = sdncSIResources.deactivateServiceInstance(serviceInstance, customer, requestContext); SDNCRequest sdncRequest = new SDNCRequest(); @@ -139,8 +138,8 @@ public class SDNCDeactivateTasks { public void deactivateNetwork(BuildingBlockExecution execution) { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + L3Network l3Network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Customer customer = gBBInput.getCustomer(); RequestContext requestContext = gBBInput.getRequestContext(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); 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 b636fe1292..941eb7a004 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 @@ -50,8 +50,8 @@ public class SDNCQueryTasks { private ExtractPojosForBB extractPojosForBB; 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)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); String selfLink = "restconf/config/GENERIC-RESOURCE-API:services/service/" + serviceInstance.getServiceInstanceId() + "/service-data/vnfs/vnf/" @@ -69,9 +69,9 @@ 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)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + VfModule vfModule = extractPojosForBB.extractByKey(execution, 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/" @@ -94,7 +94,7 @@ public class SDNCQueryTasks { public void queryVfModuleForVolumeGroup(BuildingBlockExecution execution) { try { - VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); if(vfModule.getSelflink() != null && !vfModule.getSelflink().isEmpty()) { String response = sdncVfModuleResources.queryVfModule(vfModule); execution.setVariable("SDNCQueryResponse_" + vfModule.getVfModuleId(), response); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java index 292f29c349..340872593f 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasks.java @@ -68,7 +68,7 @@ public class SDNCUnassignTasks { public void unassignServiceInstance(BuildingBlockExecution execution) { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); RequestContext requestContext = gBBInput.getRequestContext(); Customer customer = gBBInput.getCustomer(); GenericResourceApiServiceOperationInformation req = sdncSIResources.unassignServiceInstance(serviceInstance, customer, requestContext); @@ -83,9 +83,9 @@ public class SDNCUnassignTasks { public void unassignVfModule(BuildingBlockExecution execution) { try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - GenericVnf vnf = 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)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); + VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); GenericResourceApiVfModuleOperationInformation req = sdncVfModuleResources.unassignVfModule(vfModule, vnf, serviceInstance); SDNCRequest sdncRequest = new SDNCRequest(); sdncRequest.setSDNCPayload(req); @@ -98,8 +98,8 @@ public class SDNCUnassignTasks { public void unassignVnf(BuildingBlockExecution execution) { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); - GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); + GenericVnf vnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); RequestContext requestContext = gBBInput.getRequestContext(); Customer customer = gBBInput.getCustomer(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); @@ -116,8 +116,8 @@ public class SDNCUnassignTasks { public void unassignNetwork(BuildingBlockExecution execution) throws Exception { try { GeneralBuildingBlock gBBInput = execution.getGeneralBuildingBlock(); - L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); Customer customer = gBBInput.getCustomer(); RequestContext requestContext = gBBInput.getRequestContext(); CloudRegion cloudRegion = gBBInput.getCloudRegion(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java index a622520a71..bbfc01921c 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/workflow/tasks/OrchestrationStatusValidator.java @@ -80,36 +80,36 @@ public class OrchestrationStatusValidator { switch(buildingBlockDetail.getResourceType()) { case SERVICE: - org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); orchestrationStatus = serviceInstance.getOrchestrationStatus(); break; case VNF: - org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); orchestrationStatus = genericVnf.getOrchestrationStatus(); break; case VF_MODULE: - org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID, execution.getLookupMap().get(ResourceKey.VF_MODULE_ID)); + org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule vfModule = extractPojosForBB.extractByKey(execution, ResourceKey.VF_MODULE_ID); orchestrationStatus = vfModule.getOrchestrationStatus(); break; case VOLUME_GROUP: - org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID, execution.getLookupMap().get(ResourceKey.VOLUME_GROUP_ID)); + org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup = extractPojosForBB.extractByKey(execution, ResourceKey.VOLUME_GROUP_ID); orchestrationStatus = volumeGroup.getOrchestrationStatus(); break; case NETWORK: - org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID, execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); orchestrationStatus = network.getOrchestrationStatus(); break; case NETWORK_COLLECTION: - org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInst = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInst = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); org.onap.so.bpmn.servicedecomposition.bbobjects.Collection networkCollection = serviceInst.getCollection(); orchestrationStatus = networkCollection.getOrchestrationStatus(); break; case CONFIGURATION: - org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID, execution.getLookupMap().get(ResourceKey.CONFIGURATION_ID)); + org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration configuration = extractPojosForBB.extractByKey(execution, ResourceKey.CONFIGURATION_ID); orchestrationStatus = configuration.getOrchestrationStatus(); break; case INSTANCE_GROUP: - org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID, execution.getLookupMap().get(ResourceKey.INSTANCE_GROUP_ID)); + org.onap.so.bpmn.servicedecomposition.bbobjects.InstanceGroup instanceGroup = extractPojosForBB.extractByKey(execution, ResourceKey.INSTANCE_GROUP_ID); orchestrationStatus = instanceGroup.getOrchestrationStatus(); break; case NO_VALIDATE: @@ -128,7 +128,7 @@ public class OrchestrationStatusValidator { if(aLaCarte && ResourceType.VF_MODULE.equals(buildingBlockDetail.getResourceType()) && OrchestrationAction.CREATE.equals(buildingBlockDetail.getTargetAction()) && OrchestrationStatus.PENDING_ACTIVATION.equals(orchestrationStatus)) { - org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); orchestrationStatusStateTransitionDirective = processPossibleSecondStageofVfModuleCreate(execution, previousOrchestrationStatusValidationResult, genericVnf, orchestrationStatusStateTransitionDirective); } 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 482957e006..242f125bde 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 @@ -375,38 +375,23 @@ public class WorkflowActionBBTasks { List<Vnfc> vnfcs = workflowAction.getRelatedResourcesInVfModule(vnfId, vfModuleId, Vnfc.class, AAIObjectType.VNFC); for(Vnfc vnfc : vnfcs) { String modelCustomizationId = vnfc.getModelCustomizationId(); - List<CvnfcCustomization> cvnfcCustomizations = catalogDbClient.getCvnfcCustomizationByVnfCustomizationUUIDAndVfModuleCustomizationUUID(vnfCustomizationUUID, vfModuleCustomizationUUID); - CvnfcCustomization cvnfcCustomization = null; - for(CvnfcCustomization cvnfc : cvnfcCustomizations) { - if(cvnfc.getModelCustomizationUUID().equalsIgnoreCase(modelCustomizationId)) { - cvnfcCustomization = cvnfc; - } - } - if(cvnfcCustomization != null) { - VnfVfmoduleCvnfcConfigurationCustomization fabricConfig = null; - for(VnfVfmoduleCvnfcConfigurationCustomization customization : cvnfcCustomization.getVnfVfmoduleCvnfcConfigurationCustomization()){ - if(customization.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)){ - if(fabricConfig == null) { - fabricConfig = customization; - } else { - throw new Exception("Multiple Fabric configs found for this vnfc"); - } - } - } - if(fabricConfig != null) { - String configurationId = UUID.randomUUID().toString(); - ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys(); - configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId); - configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID); - configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID); - configurationResourceKeys.setVnfcName(vnfc.getVnfcName()); - ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys); - ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys); - flowsToExecute.add(assignConfigBB); - flowsToExecute.add(activateConfigBB); - execution.setVariable("flowsToExecute", flowsToExecute); - execution.setVariable("completed", false); - } + VnfVfmoduleCvnfcConfigurationCustomization fabricConfig = + catalogDbClient.getVnfVfmoduleCvnfcConfigurationCustomizationByVnfCustomizationUuidAndVfModuleCustomizationUuidAndCvnfcCustomizationUuid(vnfCustomizationUUID, vfModuleCustomizationUUID, modelCustomizationId); + if(fabricConfig != null && fabricConfig.getConfigurationResource() != null + && fabricConfig.getConfigurationResource().getToscaNodeType() != null + && fabricConfig.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)) { + String configurationId = UUID.randomUUID().toString(); + ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys(); + configurationResourceKeys.setCvnfcCustomizationUUID(modelCustomizationId); + configurationResourceKeys.setVfModuleCustomizationUUID(vfModuleCustomizationUUID); + configurationResourceKeys.setVnfResourceCustomizationUUID(vnfCustomizationUUID); + configurationResourceKeys.setVnfcName(vnfc.getVnfcName()); + ExecuteBuildingBlock assignConfigBB = getExecuteBBForConfig(ASSIGN_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys); + ExecuteBuildingBlock activateConfigBB = getExecuteBBForConfig(ACTIVATE_FABRIC_CONFIGURATION_BB, ebb, configurationId, configurationResourceKeys); + flowsToExecute.add(assignConfigBB); + flowsToExecute.add(activateConfigBB); + execution.setVariable("flowsToExecute", flowsToExecute); + execution.setVariable("completed", false); } else { logger.debug("No cvnfcCustomization found for customizationId: " + modelCustomizationId); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasks.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasks.java index 36162af740..c0f7b21a9e 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasks.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasks.java @@ -57,7 +57,7 @@ public class SDNOHealthCheckTasks { Map<ResourceKey, String> lookupMap = execution.getLookupMap(); for (Map.Entry<ResourceKey, String> entry : lookupMap.entrySet()) { if (entry.getKey().equals(ResourceKey.GENERIC_VNF_ID)) { - vnf = extractPojosForBB.extractByKey(execution, entry.getKey(), entry.getValue()); + vnf = extractPojosForBB.extractByKey(execution, entry.getKey()); } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java index 138a20b609..f412720af7 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/orchestration/AAIConfigurationResources.java @@ -50,7 +50,7 @@ public class AAIConfigurationResources { */ public void createConfiguration(Configuration configuration) { AAIResourceUri configurationURI = AAIUriFactory.createResourceUri(AAIObjectType.CONFIGURATION, configuration.getConfigurationId()); - configuration.setOrchestrationStatus(OrchestrationStatus.INVENTORIED); + configuration.setOrchestrationStatus(OrchestrationStatus.ASSIGNED); org.onap.aai.domain.yang.Configuration aaiConfiguration = aaiObjectMapper.mapConfiguration(configuration); injectionHelper.getAaiClient().create(configurationURI, aaiConfiguration); } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java index 99d5fca31f..cae4a19f20 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/SDNCClient.java @@ -42,7 +42,6 @@ import org.springframework.stereotype.Component; public class SDNCClient { private static final Logger logger = LoggerFactory.getLogger(SDNCClient.class); - private BaseClient<String, LinkedHashMap<String, Object>> STOClient = new BaseClient<>(); @Autowired private SDNCProperties properties; @@ -61,6 +60,8 @@ public class SDNCClient { public String post(Object request, SDNCTopology topology) throws MapperException, BadResponseException { String jsonRequest = sdnCommonTasks.buildJsonRequest(request); String targetUrl = properties.getHost() + properties.getPath() + ":" + topology.toString() + "/"; + BaseClient<String, LinkedHashMap<String, Object>> STOClient = new BaseClient<>(); + STOClient.setTargetUrl(targetUrl); HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth()); STOClient.setHttpHeader(httpHeader); @@ -70,7 +71,8 @@ public class SDNCClient { public String post(Object request, String url) throws MapperException, BadResponseException { - String jsonRequest = sdnCommonTasks.buildJsonRequest(request); + String jsonRequest = sdnCommonTasks.buildJsonRequest(request); + BaseClient<String, LinkedHashMap<String, Object>> STOClient = new BaseClient<>(); STOClient.setTargetUrl(url); HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth()); STOClient.setHttpHeader(httpHeader); @@ -91,7 +93,8 @@ public class SDNCClient { public String get(String queryLink) throws MapperException, BadResponseException { String request = ""; String jsonRequest = sdnCommonTasks.buildJsonRequest(request); - String targetUrl = UriBuilder.fromUri(properties.getHost()).path(queryLink).build().toString(); + String targetUrl = UriBuilder.fromUri(properties.getHost()).path(queryLink).build().toString(); + BaseClient<String, LinkedHashMap<String, Object>> STOClient = new BaseClient<>(); STOClient.setTargetUrl(targetUrl); HttpHeaders httpHeader = sdnCommonTasks.getHttpHeaders(properties.getAuth()); STOClient.setHttpHeader(httpHeader); 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 e46c456f88..b11e2caafa 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 @@ -85,6 +85,7 @@ public class GCTopologyOperationRequestMapper { GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation = new GenericResourceApiConfigurationinformationConfigurationInformation(); configurationInformation.setConfigurationId(vnrConfiguration.getConfigurationId()); + configurationInformation.setConfigurationType(vnrConfiguration.getConfigurationType()); req.setRequestInformation(requestInformation); req.setSdncRequestHeader(sdncRequestHeader); req.setServiceInformation(serviceInformation); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/aai/tasks/AAIFlagTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/aai/tasks/AAIFlagTasksTest.java index cad97cad6e..a91ef66a29 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/aai/tasks/AAIFlagTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/common/aai/tasks/AAIFlagTasksTest.java @@ -65,7 +65,7 @@ public class AAIFlagTasksTest extends BaseTaskTest { public void before() throws BBObjectNotFoundException { genericVnf = setGenericVnf(); doReturn(MOCK_aaiResourcesClient).when(MOCK_injectionHelper).getAaiClient(); - when(extractPojosForBB.extractByKey(any(),any(), any())).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),any())).thenReturn(genericVnf); } @Test 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 166319d32b..d0901eb689 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 @@ -353,7 +353,7 @@ public class TestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -371,7 +371,7 @@ public class TestDataSetup{ Collection collection = null; try { - ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + ServiceInstance serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); collection = serviceInstance.getCollection(); if (collection == null) { @@ -393,7 +393,7 @@ public class TestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -464,7 +464,7 @@ public class TestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -517,7 +517,7 @@ public class TestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -556,7 +556,7 @@ public class TestDataSetup{ GenericVnf genericVnf = null; try { - genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); } catch(BBObjectNotFoundException e) { genericVnf = setGenericVnf(); } @@ -586,7 +586,7 @@ public class TestDataSetup{ GenericVnf genericVnf = null; try { - genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID, execution.getLookupMap().get(ResourceKey.GENERIC_VNF_ID)); + genericVnf = extractPojosForBB.extractByKey(execution, ResourceKey.GENERIC_VNF_ID); } catch(BBObjectNotFoundException e) { genericVnf = setGenericVnf(); } @@ -650,7 +650,7 @@ public class TestDataSetup{ ServiceInstance serviceInstance = null; try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } @@ -710,7 +710,7 @@ public class TestDataSetup{ configurations.add(config); ServiceInstance serviceInstance = new ServiceInstance(); try { - serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID, execution.getLookupMap().get(ResourceKey.SERVICE_INSTANCE_ID)); + serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID); } catch(BBObjectNotFoundException e) { serviceInstance = setServiceInstance(); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java index 4e147a022c..fcb95ca07e 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAICreateTasksTest.java @@ -96,13 +96,13 @@ public class AAICreateTasksTest extends BaseTaskTest{ configuration = setConfiguration(); instanceGroup = setInstanceGroupVnf(); - 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); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID), any())).thenReturn(volumeGroup); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID), any())).thenReturn(configuration); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID), any())).thenReturn(instanceGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID))).thenReturn(configuration); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID))).thenReturn(instanceGroup); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); @@ -277,7 +277,7 @@ public class AAICreateTasksTest extends BaseTaskTest{ public void createVnfExceptionTest() throws Exception { expectedException.expect(BpmnError.class); lookupKeyMap.put(ResourceKey.GENERIC_VNF_ID, "notfound"); - doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID),eq("notfound")); + doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)); doNothing().when(aaiVnfResources).createVnfandConnectServiceInstance(genericVnf, serviceInstance); aaiCreateTasks.createVnf(execution); verify(aaiVnfResources, times(1)).createVnfandConnectServiceInstance(genericVnf, serviceInstance); @@ -291,7 +291,7 @@ public class AAICreateTasksTest extends BaseTaskTest{ newVfModule.setModuleIndex(null); newVfModule.getModelInfoVfModule().setModelInvariantUUID("testModelInvariantUUID1"); doNothing().when(aaiVfModuleResources).createVfModule(newVfModule, genericVnf); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID), any())).thenReturn(newVfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(newVfModule); assertEquals(null, newVfModule.getModuleIndex()); aaiCreateTasks.createVfModule(execution); @@ -412,8 +412,8 @@ public class AAICreateTasksTest extends BaseTaskTest{ gBBInput.setServiceInstance(serviceInstance); lookupKeyMap.put(ResourceKey.SERVICE_INSTANCE_ID, serviceInstance.getServiceInstanceId()); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), eq("testServiceInstanceId"))).thenReturn(serviceInstance); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID),eq("testNetworkId"))).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(serviceInstance); //verify connection call was not executednetwork exception.expect(BpmnError.class); aaiCreateTasks.connectNetworkToNetworkCollectionInstanceGroup(execution); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasksTest.java index 94d886cdb5..826f888818 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/aai/tasks/AAIDeleteTasksTest.java @@ -88,13 +88,13 @@ public class AAIDeleteTasksTest extends BaseTaskTest { configuration = setConfiguration(); instanceGroup = setInstanceGroupVnf(); - 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); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID), any())).thenReturn(volumeGroup); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID), any())).thenReturn(configuration); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID), any())).thenReturn(instanceGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID))).thenReturn(configuration); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID))).thenReturn(instanceGroup); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); 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 a8a249f386..78d08aa1f1 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 @@ -84,12 +84,12 @@ public class AAIUpdateTasksTest extends BaseTaskTest{ configuration = setConfiguration(); subnet = buildSubnet(); - 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); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID), any())).thenReturn(volumeGroup); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID), any())).thenReturn(configuration); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.CONFIGURATION_ID))).thenReturn(configuration); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasksTest.java index 3034f0bd67..72f6a08ee7 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterCreateTasksTest.java @@ -72,8 +72,8 @@ public class NetworkAdapterCreateTasksTest extends BaseTaskTest{ orchestrationContext.setIsRollbackEnabled(true); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(l3Network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(l3Network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasksTest.java index 5b534e00e7..ceb4796443 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterDeleteTasksTest.java @@ -66,8 +66,8 @@ public class NetworkAdapterDeleteTasksTest extends BaseTaskTest{ requestContext = setRequestContext(); cloudRegion = setCloudRegion(); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(l3Network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(l3Network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasksTest.java index 478c512b0a..0406ce09a3 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/network/tasks/NetworkAdapterUpdateTasksTest.java @@ -79,8 +79,8 @@ public class NetworkAdapterUpdateTasksTest extends BaseTaskTest{ userInput = setUserInput(); userInput.put("userInputKey1", "userInputValue1"); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasksTest.java index eaab75d4b9..32b3201d11 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterCreateTasksTest.java @@ -76,9 +76,9 @@ public class VnfAdapterCreateTasksTest extends BaseTaskTest{ CreateVolumeGroupRequest request = new CreateVolumeGroupRequest(); request.setVolumeGroupId("volumeGroupStackId"); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any())).thenReturn(genericVnf); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID), any())).thenReturn(volumeGroup); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID), any())).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); doReturn(request).when(vnfAdapterVolumeGroupResources).createVolumeGroupRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, sdncVnfQueryResponse); vnfAdapterCreateTasks.createVolumeGroupRequest(execution); @@ -107,9 +107,9 @@ public class VnfAdapterCreateTasksTest extends BaseTaskTest{ CreateVolumeGroupRequest request = new CreateVolumeGroupRequest(); request.setVolumeGroupId("volumeGroupStackId"); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any())).thenReturn(genericVnf); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID), any())).thenReturn(volumeGroup); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID), any())).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); doReturn(request).when(vnfAdapterVolumeGroupResources).createVolumeGroupRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, volumeGroup, null); vnfAdapterCreateTasks.createVolumeGroupRequest(execution); @@ -122,7 +122,7 @@ public class VnfAdapterCreateTasksTest extends BaseTaskTest{ @Test public void test_createVolumeGroupRequest_exception() throws Exception { - doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any()); + doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); expectedException.expect(BpmnError.class); @@ -156,8 +156,8 @@ public class VnfAdapterCreateTasksTest extends BaseTaskTest{ String sdncVnfQueryResponse = "{someJson}"; execution.setVariable("SDNCQueryResponse_" + genericVnf.getVnfId(), sdncVnfQueryResponse); - 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); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); doReturn(createVfModuleRequest).when(vnfAdapterVfModuleResources).createVfModuleRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, vfModule, null, sdncVnfQueryResponse, sdncVfModuleQueryResponse); @@ -199,9 +199,9 @@ public class VnfAdapterCreateTasksTest extends BaseTaskTest{ String sdncVnfQueryResponse = "{someJson}"; execution.setVariable("SDNCQueryResponse_" + genericVnf.getVnfId(), sdncVnfQueryResponse); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any())).thenReturn(genericVnf); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID), any())).thenReturn(volumeGroup); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID), any())).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); doReturn(createVfModuleRequest).when(vnfAdapterVfModuleResources).createVfModuleRequest(requestContext, cloudRegion, orchestrationContext, serviceInstance, genericVnf, vfModule, volumeGroup, sdncVnfQueryResponse, sdncVfModuleQueryResponse); @@ -216,7 +216,7 @@ public class VnfAdapterCreateTasksTest extends BaseTaskTest{ @Test public void createVfModuleExceptionTest() throws Exception { // run with no data setup, and it will throw a BBObjectNotFoundException - doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any()); + doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID)); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); expectedException.expect(BpmnError.class); vnfAdapterCreateTasks.createVolumeGroupRequest(execution); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasksTest.java index b8be26b12a..efd2e7d849 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterDeleteTasksTest.java @@ -76,10 +76,10 @@ public class VnfAdapterDeleteTasksTest extends BaseTaskTest{ orchestrationContext = setOrchestrationContext(); orchestrationContext.setIsRollbackEnabled(true); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any())).thenReturn(genericVnf); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID), any())).thenReturn(volumeGroup); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID), any())).thenReturn(vfModule); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class)); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java index 33d0dbe130..b515835f19 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java @@ -78,10 +78,10 @@ public class VnfAdapterImplTest extends BaseTaskTest { volumeGroup.setHeatStackId(null); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class)); 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.VOLUME_GROUP_ID), any())).thenReturn(volumeGroup); - 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); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); } @Test @@ -209,7 +209,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void preProcessVnfAdapterExceptionTest() throws BBObjectNotFoundException { expectedException.expect(BpmnError.class); - doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any()); + doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID)); vnfAdapterImpl.preProcessVnfAdapter(execution); } @@ -263,7 +263,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapterExceptionTest() throws BBObjectNotFoundException { - doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID), any()); + doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID)); execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_REST_CREATE_RESPONSE); expectedException.expect(BpmnError.class); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java new file mode 100644 index 0000000000..5451d4442f --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/TestConstants.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.VnfmBasicHttpConfigProvider; + +/** + * @author waqas.ikram@est.tech + * + */ +public class TestConstants { + + public static final String DUMMY_GENERIC_VND_ID = "5956a99d-9736-11e8-8caf-022ac9304eeb"; + public static final String DUMMY_BASIC_AUTH = "Basic 123abc"; + public static final String DUMMY_URL = "http://localhost:30406/so/vnfm-adapter/v1/"; + public static final String EXPECTED_URL = DUMMY_URL + "vnfs/" + DUMMY_GENERIC_VND_ID; + + public static VnfmBasicHttpConfigProvider getVnfmBasicHttpConfigProvider() { + return getVnfmBasicHttpConfigProvider(DUMMY_URL, DUMMY_BASIC_AUTH); + } + + public static VnfmBasicHttpConfigProvider getVnfmBasicHttpConfigProvider(final String url, final String auth) { + final VnfmBasicHttpConfigProvider vnfmBasicHttpConfigProvider = new VnfmBasicHttpConfigProvider(); + vnfmBasicHttpConfigProvider.setUrl(url); + vnfmBasicHttpConfigProvider.setAuth(auth); + return vnfmBasicHttpConfigProvider; + } + + private TestConstants() {} + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfigurationTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfigurationTest.java new file mode 100644 index 0000000000..5aaebea76e --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskConfigurationTest.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import static org.junit.Assert.assertNotNull; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.getVnfmBasicHttpConfigProvider; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.VnfmAdapterCreateVnfTaskConfiguration; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.springframework.web.client.RestTemplate; + +/** + * @author waqas.ikram@est.tech + */ +@RunWith(MockitoJUnitRunner.class) +public class VnfmAdapterCreateVnfTaskConfigurationTest { + + @Mock + private RestTemplate restTemplate; + + @Test + public void test_databaseHttpRestServiceProvider_httpRestServiceProviderNotNull() { + final VnfmAdapterCreateVnfTaskConfiguration objUnderTest = new VnfmAdapterCreateVnfTaskConfiguration(); + + final HttpRestServiceProvider actual = + objUnderTest.databaseHttpRestServiceProvider(restTemplate, getVnfmBasicHttpConfigProvider()); + assertNotNull(actual); + + + } + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskTest.java new file mode 100644 index 0000000000..ddfc08e08f --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterCreateVnfTaskTest.java @@ -0,0 +1,248 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.CREATE_VNF_REQUEST_PARAM_NAME; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.Constants.CREATE_VNF_RESPONSE_PARAM_NAME; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.junit.Test; +import org.mockito.Mock; +import org.onap.so.bpmn.BaseTaskTest; +import org.onap.so.bpmn.common.BuildingBlockExecution; +import org.onap.so.bpmn.common.exceptions.RequiredExecutionVariableExeception; +import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.VnfmAdapterCreateVnfTask; +import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.VnfmAdapterServiceProvider; +import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion; +import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf; +import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; +import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoGenericVnf; +import org.onap.vnfmadapter.v1.model.CreateVnfRequest; +import org.onap.vnfmadapter.v1.model.CreateVnfResponse; +import org.onap.vnfmadapter.v1.model.Tenant; + +import com.google.common.base.Optional; + + +/** + * @author waqas.ikram@est.tech + */ +public class VnfmAdapterCreateVnfTaskTest extends BaseTaskTest { + + private static final String MODEL_INSTANCE_NAME = "MODEL_INSTANCE_NAME"; + + private static final String CLOUD_OWNER = "CLOUD_OWNER"; + + private static final String LCP_CLOUD_REGIONID = "RegionOnce"; + + private static final String TENANT_ID = UUID.randomUUID().toString(); + + private static final String VNF_ID = UUID.randomUUID().toString(); + + private static final String VNF_NAME = "VNF_NAME"; + + private static final String JOB_ID = UUID.randomUUID().toString(); + + @Mock + private VnfmAdapterServiceProvider mockedVnfmAdapterServiceProvider; + + private final BuildingBlockExecution stubbedxecution = new StubbedBuildingBlockExecution(); + + @Test + public void testBuildCreateVnfRequest_withValidValues_storesRequestInExecution() throws Exception { + + final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask(); + + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf()); + objUnderTest.buildCreateVnfRequest(stubbedxecution); + + final CreateVnfRequest actual = stubbedxecution.getVariable(CREATE_VNF_REQUEST_PARAM_NAME); + assertNotNull(actual); + assertEquals(VNF_NAME + "." + MODEL_INSTANCE_NAME, actual.getName()); + + final Tenant actualTenant = actual.getTenant(); + assertEquals(CLOUD_OWNER, actualTenant.getCloudOwner()); + assertEquals(LCP_CLOUD_REGIONID, actualTenant.getRegionName()); + assertEquals(TENANT_ID, actualTenant.getTenantId()); + + } + + @Test + public void testBuildCreateVnfRequest_extractPojosForBBThrowsException_exceptionBuilderCalled() throws Exception { + + final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask(); + + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenThrow(RuntimeException.class); + + objUnderTest.buildCreateVnfRequest(stubbedxecution); + + final CreateVnfRequest actual = stubbedxecution.getVariable(CREATE_VNF_REQUEST_PARAM_NAME); + + assertNull(actual); + verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1200), + any(Exception.class)); + + } + + @Test + public void testInvokeVnfmAdapter_validValues_storesResponseInExecution() throws Exception { + + final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask(); + + stubbedxecution.setVariable(CREATE_VNF_REQUEST_PARAM_NAME, new CreateVnfRequest()); + + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf()); + when(mockedVnfmAdapterServiceProvider.invokeCreateInstantiationRequest(eq(VNF_ID), any(CreateVnfRequest.class))) + .thenReturn(getCreateVnfResponse()); + + objUnderTest.invokeVnfmAdapter(stubbedxecution); + + assertNotNull(stubbedxecution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME)); + } + + @Test + public void testInvokeVnfmAdapter_invalidValues_storesResponseInExecution() throws Exception { + + final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask(); + + stubbedxecution.setVariable(CREATE_VNF_REQUEST_PARAM_NAME, new CreateVnfRequest()); + + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(getGenericVnf()); + when(mockedVnfmAdapterServiceProvider.invokeCreateInstantiationRequest(eq(VNF_ID), any(CreateVnfRequest.class))) + .thenReturn(Optional.absent()); + + objUnderTest.invokeVnfmAdapter(stubbedxecution); + + assertNull(stubbedxecution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME)); + verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1202), + any(Exception.class)); + } + + + @Test + public void testInvokeVnfmAdapter_extractPojosForBBThrowsException_exceptionBuilderCalled() throws Exception { + + final VnfmAdapterCreateVnfTask objUnderTest = getEtsiVnfInstantiateTask(); + + when(extractPojosForBB.extractByKey(any(), eq(ResourceKey.GENERIC_VNF_ID))).thenThrow(RuntimeException.class); + + objUnderTest.invokeVnfmAdapter(stubbedxecution); + + assertNull(stubbedxecution.getVariable(CREATE_VNF_RESPONSE_PARAM_NAME)); + verify(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(1202), + any(Exception.class)); + + } + + private Optional<CreateVnfResponse> getCreateVnfResponse() { + final CreateVnfResponse response = new CreateVnfResponse(); + response.setJobId(JOB_ID); + return Optional.of(response); + } + + private GenericVnf getGenericVnf() { + final GenericVnf genericVnf = new GenericVnf(); + genericVnf.setVnfId(VNF_ID); + genericVnf.setModelInfoGenericVnf(getModelInfoGenericVnf()); + genericVnf.setVnfName(VNF_NAME); + return genericVnf; + } + + private ModelInfoGenericVnf getModelInfoGenericVnf() { + final ModelInfoGenericVnf modelInfoGenericVnf = new ModelInfoGenericVnf(); + modelInfoGenericVnf.setModelInstanceName(MODEL_INSTANCE_NAME); + return modelInfoGenericVnf; + } + + private VnfmAdapterCreateVnfTask getEtsiVnfInstantiateTask() { + return new VnfmAdapterCreateVnfTask(exceptionUtil, extractPojosForBB, mockedVnfmAdapterServiceProvider); + } + + private class StubbedBuildingBlockExecution implements BuildingBlockExecution { + + private final Map<String, Serializable> execution = new HashMap<>(); + private final GeneralBuildingBlock generalBuildingBlock; + + StubbedBuildingBlockExecution() { + generalBuildingBlock = getGeneralBuildingBlockValue(); + } + + @Override + public GeneralBuildingBlock getGeneralBuildingBlock() { + return generalBuildingBlock; + } + + @SuppressWarnings("unchecked") + @Override + public <T> T getVariable(final String key) { + return (T) execution.get(key); + } + + @Override + public <T> T getRequiredVariable(final String key) throws RequiredExecutionVariableExeception { + return null; + } + + @Override + public void setVariable(final String key, final Serializable value) { + execution.put(key, value); + } + + @Override + public Map<ResourceKey, String> getLookupMap() { + return Collections.emptyMap(); + } + + @Override + public String getFlowToBeCalled() { + return null; + } + + private GeneralBuildingBlock getGeneralBuildingBlockValue() { + final GeneralBuildingBlock buildingBlock = new GeneralBuildingBlock(); + buildingBlock.setCloudRegion(getCloudRegion()); + return buildingBlock; + } + + private CloudRegion getCloudRegion() { + final CloudRegion cloudRegion = new CloudRegion(); + cloudRegion.setCloudOwner(CLOUD_OWNER); + cloudRegion.setLcpCloudRegionId(LCP_CLOUD_REGIONID); + cloudRegion.setTenantId(TENANT_ID); + return cloudRegion; + } + + } + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java new file mode 100644 index 0000000000..0f443916c4 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterServiceProviderImplTest.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.DUMMY_GENERIC_VND_ID; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.getVnfmBasicHttpConfigProvider; + +import java.util.UUID; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.VnfmAdapterServiceProvider; +import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.VnfmAdapterServiceProviderImpl; +import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.VnfmAdapterUrlProvider; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.vnfmadapter.v1.model.CreateVnfRequest; +import org.onap.vnfmadapter.v1.model.CreateVnfResponse; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import com.google.common.base.Optional; + + +/** + * @author waqas.ikram@est.tech + */ +@RunWith(MockitoJUnitRunner.class) +public class VnfmAdapterServiceProviderImplTest { + + private static final String EMPTY_JOB_ID = ""; + + private static final CreateVnfRequest CREATE_VNF_REQUEST = new CreateVnfRequest(); + + private static final String DUMMY_JOB_ID = UUID.randomUUID().toString(); + + @Mock + private HttpRestServiceProvider mockedHttpServiceProvider; + + @Mock + private ResponseEntity<CreateVnfResponse> mockedResponseEntity; + + @Test + public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusAcceptedWithBody_validResponse() { + + when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(), + eq(CreateVnfResponse.class))).thenReturn(mockedResponseEntity); + when(mockedResponseEntity.getStatusCode()).thenReturn(HttpStatus.ACCEPTED); + when(mockedResponseEntity.hasBody()).thenReturn(true); + final CreateVnfResponse response = getCreateVnfResponse(DUMMY_JOB_ID); + when(mockedResponseEntity.getBody()).thenReturn(response); + + + final VnfmAdapterServiceProvider objUnderTest = + new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider); + + final Optional<CreateVnfResponse> actual = + objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST); + assertTrue(actual.isPresent()); + assertEquals(actual.get(), response); + + } + + @Test + public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusAcceptedWithNoBody_noResponse() { + assertWithStatuCode(HttpStatus.ACCEPTED); + } + + @Test + public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusNotOkWithNoBody_noResponse() { + assertWithStatuCode(HttpStatus.UNAUTHORIZED); + } + + + @Test + public void testInvokeCreateInstantiationRequest_httpServiceProviderReturnsStatusAcceptedWithBodyWithInvalidJobId_noResponse() { + assertWithJobId(null); + assertWithJobId(EMPTY_JOB_ID); + } + + @Test + public void testInvokeCreateInstantiationRequest_httpServiceProviderThrowException_httpRestServiceProviderNotNull() { + + when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(), + eq(CreateVnfResponse.class))).thenThrow(RestProcessingException.class); + + + final VnfmAdapterServiceProvider objUnderTest = + new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider); + + final Optional<CreateVnfResponse> actual = + objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST); + assertFalse(actual.isPresent()); + + } + + + private void assertWithJobId(final String jobId) { + when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(), + eq(CreateVnfResponse.class))).thenReturn(mockedResponseEntity); + when(mockedResponseEntity.getStatusCode()).thenReturn(HttpStatus.ACCEPTED); + when(mockedResponseEntity.hasBody()).thenReturn(true); + final CreateVnfResponse response = getCreateVnfResponse(jobId); + when(mockedResponseEntity.getBody()).thenReturn(response); + + + final VnfmAdapterServiceProvider objUnderTest = + new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider); + + final Optional<CreateVnfResponse> actual = + objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST); + assertFalse(actual.isPresent()); + } + + private void assertWithStatuCode(final HttpStatus status) { + when(mockedHttpServiceProvider.postHttpRequest(eq(CREATE_VNF_REQUEST), anyString(), + eq(CreateVnfResponse.class))).thenReturn(mockedResponseEntity); + when(mockedResponseEntity.getStatusCode()).thenReturn(status); + when(mockedResponseEntity.hasBody()).thenReturn(false); + + final VnfmAdapterServiceProvider objUnderTest = + new VnfmAdapterServiceProviderImpl(getVnfmAdapterUrlProvider(), mockedHttpServiceProvider); + + final Optional<CreateVnfResponse> actual = + objUnderTest.invokeCreateInstantiationRequest(DUMMY_GENERIC_VND_ID, CREATE_VNF_REQUEST); + assertFalse(actual.isPresent()); + } + + + + private CreateVnfResponse getCreateVnfResponse(final String jobId) { + final CreateVnfResponse response = new CreateVnfResponse(); + response.setJobId(jobId); + return response; + } + + + private VnfmAdapterUrlProvider getVnfmAdapterUrlProvider() { + return new VnfmAdapterUrlProvider(getVnfmBasicHttpConfigProvider()); + } +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProviderTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProviderTest.java new file mode 100644 index 0000000000..cb93adca69 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnfm/tasks/VnfmAdapterUrlProviderTest.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks; + +import static org.junit.Assert.assertEquals; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.DUMMY_GENERIC_VND_ID; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.EXPECTED_URL; +import static org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.TestConstants.getVnfmBasicHttpConfigProvider; + +import org.junit.Test; +import org.onap.so.bpmn.infrastructure.adapter.vnfm.tasks.VnfmAdapterUrlProvider; + + +/** + * @author waqas.ikram@est.tech + * + */ +public class VnfmAdapterUrlProviderTest { + + + @Test + public void test_getCreateInstantiateUrl_returnValidCreationInstantiationRequest() { + final VnfmAdapterUrlProvider objUnderTest = new VnfmAdapterUrlProvider(getVnfmBasicHttpConfigProvider()); + + final String actual = objUnderTest.getCreateInstantiateUrl(DUMMY_GENERIC_VND_ID); + + assertEquals(EXPECTED_URL, actual); + } + + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java index 7495cc1e8d..a8518d9016 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/appc/tasks/AppcRunTasksTest.java @@ -73,7 +73,7 @@ public class AppcRunTasksTest extends BaseTaskTest { public void runAppcCommandVnfNull() throws BBObjectNotFoundException { execution.getLookupMap().put(ResourceKey.GENERIC_VNF_ID, "NULL-TEST"); fillRequiredAppcExecutionFields(); - when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID), eq("NULL-TEST"))) + when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID))) .thenReturn(null); when(catalogDbClient.getControllerSelectionReferenceByVnfTypeAndActionCategory( isNull(), eq(Action.Lock.toString()))). @@ -92,7 +92,7 @@ public class AppcRunTasksTest extends BaseTaskTest { public void runAppcCommandBBObjectNotFoundException() throws BBObjectNotFoundException { execution.getLookupMap().put(ResourceKey.GENERIC_VNF_ID, "EXCEPTION-TEST"); fillRequiredAppcExecutionFields(); - when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID), eq("EXCEPTION-TEST"))) + when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID))) .thenThrow(new BBObjectNotFoundException()); appcRunTasks.runAppcCommand(execution, Action.Lock); @@ -107,11 +107,11 @@ public class AppcRunTasksTest extends BaseTaskTest { execution.getLookupMap().put(ResourceKey.GENERIC_VNF_ID, "SUCCESS-TEST"); fillRequiredAppcExecutionFields(); GenericVnf genericVnf = getTestGenericVnf(); - when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID), eq("SUCCESS-TEST"))) + when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID))) .thenReturn(genericVnf); mockReferenceResponse(); execution.getLookupMap().put(ResourceKey.VF_MODULE_ID, "VF-MODULE-ID-TEST"); - when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.VF_MODULE_ID), eq("VF-MODULE-ID-TEST"))) + when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.VF_MODULE_ID))) .thenReturn(null); when(appCClient.getErrorCode()).thenReturn("0"); @@ -125,13 +125,13 @@ public class AppcRunTasksTest extends BaseTaskTest { execution.getLookupMap().put(ResourceKey.GENERIC_VNF_ID, "SUCCESS-TEST"); fillRequiredAppcExecutionFields(); GenericVnf genericVnf = getTestGenericVnf(); - when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID), eq("SUCCESS-TEST"))) + when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.GENERIC_VNF_ID))) .thenReturn(genericVnf); mockReferenceResponse(); execution.getLookupMap().put(ResourceKey.VF_MODULE_ID, "VF-MODULE-ID-TEST"); VfModule vfModule = new VfModule(); vfModule.setVfModuleId("VF-MODULE-ID"); - when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.VF_MODULE_ID), eq("VF-MODULE-ID-TEST"))) + when(extractPojosForBB.extractByKey(eq(execution), eq(ResourceKey.VF_MODULE_ID))) .thenReturn(vfModule); when(appCClient.getErrorCode()).thenReturn("0"); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/audit/AuditTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/audit/AuditTasksTest.java index 7a9e2bb6cf..3542d7fdb3 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/audit/AuditTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/audit/AuditTasksTest.java @@ -56,9 +56,9 @@ public class AuditTasksTest extends BaseTaskTest{ genericVnf = setGenericVnf(); vfModule = setVfModule(); setCloudRegion(); - 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); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); } @Test diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkTest.java index befeea411d..19981bc45a 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignNetworkTest.java @@ -48,14 +48,14 @@ public class AssignNetworkTest extends BaseTaskTest { public void before() throws BBObjectNotFoundException { network = setL3Network(); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); } @Test public void networkNotFoundTest() throws Exception { //network status to PRECREATED - when it was NOT found by name try { - network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID,execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); } catch(BBObjectNotFoundException e) { } @@ -67,7 +67,7 @@ public class AssignNetworkTest extends BaseTaskTest { @Test public void networkFoundTest() throws Exception { try { - network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID,execution.getLookupMap().get(ResourceKey.NETWORK_ID)); + network = extractPojosForBB.extractByKey(execution, ResourceKey.NETWORK_ID); } catch(BBObjectNotFoundException e) { } boolean networkFound = assignNetwork.networkFoundByName(execution); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnfTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnfTest.java index 4ad6fba910..834990db5a 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnfTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/AssignVnfTest.java @@ -92,7 +92,7 @@ public class AssignVnfTest extends BaseTaskTest { doNothing().when(aaiInstanceGroupResources).createInstanceGroup(isA(InstanceGroup.class)); doNothing().when(aaiInstanceGroupResources).connectInstanceGroupToVnf(isA(InstanceGroup.class), isA(GenericVnf.class)); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any())).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class)); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnfTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnfTest.java new file mode 100644 index 0000000000..07983ccd50 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigAssignVnfTest.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.bpmn.infrastructure.flowspecific.tasks; + +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentMatchers; +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.entities.ResourceKey; +import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext; +import org.onap.so.client.exception.BBObjectNotFoundException; + +public class ConfigAssignVnfTest extends BaseTaskTest { + @InjectMocks + private ConfigAssignVnf configAssignVnf = new ConfigAssignVnf(); + + private GenericVnf genericVnf; + private ServiceInstance serviceInstance; + private RequestContext requestContext; + private String msoRequestId; + + @Before + public void before() throws BBObjectNotFoundException { + genericVnf = setGenericVnf(); + serviceInstance = setServiceInstance(); + msoRequestId = UUID.randomUUID().toString(); + requestContext = setRequestContext(); + requestContext.setMsoRequestId(msoRequestId); + gBBInput.setRequestContext(requestContext); + + doThrow(new BpmnError("BPMN Error")).when(exceptionUtil) + .buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); + when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))) + .thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(), ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))) + .thenReturn(serviceInstance); + } + + @Test + public void preProcessAbstractCDSProcessingTest() throws Exception { + + configAssignVnf.preProcessAbstractCDSProcessing(execution); + + assertTrue(true); + } + +} diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOutTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOutTest.java index ad848a4d49..6390268a0c 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOutTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/ConfigurationScaleOutTest.java @@ -81,8 +81,8 @@ public class ConfigurationScaleOutTest extends BaseTaskTest { gBBInput.setRequestContext(requestContext); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); - 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); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollectionTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollectionTest.java index 7202bd5298..423029c59b 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollectionTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkCollectionTest.java @@ -70,8 +70,8 @@ public class CreateNetworkCollectionTest extends BaseTaskTest{ orchestrationContext.setIsRollbackEnabled(true); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); } @Test diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkTest.java index ddfd636a64..de1aa63f55 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/CreateNetworkTest.java @@ -70,8 +70,8 @@ public class CreateNetworkTest extends BaseTaskTest{ userInput = setUserInput(); customer.getServiceSubscription().getServiceInstances().add(serviceInstance); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); } @Test diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheckTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheckTest.java index 7fdf2535bf..2386da743b 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheckTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericVnfHealthCheckTest.java @@ -66,7 +66,7 @@ public class GenericVnfHealthCheckTest extends BaseTaskTest { gBBInput.setRequestContext(requestContext); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any())).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); } @Test diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBBTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBBTest.java index ccfcabaf09..ecdf11bd05 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBBTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignNetworkBBTest.java @@ -72,7 +72,7 @@ public class UnassignNetworkBBTest extends BaseTaskTest { AAIResultWrapper aaiResultWrapper = new AAIResultWrapper(aaiResponse); Optional<org.onap.aai.domain.yang.L3Network> l3network = aaiResultWrapper.asBean(org.onap.aai.domain.yang.L3Network.class); - doReturn(network).when(extractPojosForBB).extractByKey(execution, ResourceKey.NETWORK_ID, "testNetworkId1"); + doReturn(network).when(extractPojosForBB).extractByKey(execution, ResourceKey.NETWORK_ID); doReturn(aaiResultWrapper).when(aaiNetworkResources).queryNetworkWrapperById(network); doReturn(true).when(networkBBUtils).isRelationshipRelatedToExists(any(Optional.class), eq("vf-module")); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnfTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnfTest.java index 688f95c3c0..394ffcf0ac 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnfTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/UnassignVnfTest.java @@ -68,7 +68,7 @@ public class UnassignVnfTest extends BaseTaskTest{ instanceGroup2.setId("test-002"); instanceGroup2.setModelInfoInstanceGroup(modelVnfc); genericVnf.getInstanceGroups().add(instanceGroup2); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any())).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); unassignVnf.deleteInstanceGroups(execution); verify(aaiInstanceGroupResources, times(1)).deleteInstanceGroup(eq(instanceGroup1)); verify(aaiInstanceGroupResources, times(1)).deleteInstanceGroup(eq(instanceGroup2)); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java index 41739f37e6..67c48d1e91 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceCreateTasksTest.java @@ -22,7 +22,6 @@ package org.onap.so.bpmn.infrastructure.namingservice.tasks; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; @@ -47,7 +46,7 @@ public class NamingServiceCreateTasksTest extends BaseTaskTest { @Before public void before() throws BBObjectNotFoundException { instanceGroup = setInstanceGroup(); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID), any())).thenReturn(instanceGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID))).thenReturn(instanceGroup); } @Test @@ -68,7 +67,7 @@ public class NamingServiceCreateTasksTest extends BaseTaskTest { public void createInstanceGroupExceptionTest() throws Exception { expectedException.expect(BBObjectNotFoundException.class); lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, "notfound"); - doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID),eq("notfound")); + doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID)); String policyInstanceName = "policyInstanceName"; String nfNamingCode = "nfNamingCode"; execution.setVariable(policyInstanceName, policyInstanceName); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java index 97dcc617ac..56226dfa96 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/namingservice/tasks/NamingServiceDeleteTasksTest.java @@ -21,7 +21,6 @@ package org.onap.so.bpmn.infrastructure.namingservice.tasks; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; @@ -46,7 +45,7 @@ public class NamingServiceDeleteTasksTest extends BaseTaskTest { @Before public void before() throws BBObjectNotFoundException { instanceGroup = setInstanceGroup(); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID), any())).thenReturn(instanceGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID))).thenReturn(instanceGroup); } @Test @@ -62,7 +61,7 @@ public class NamingServiceDeleteTasksTest extends BaseTaskTest { public void deleteInstanceGroupExceptionTest() throws Exception { expectedException.expect(BBObjectNotFoundException.class); lookupKeyMap.put(ResourceKey.INSTANCE_GROUP_ID, "notfound"); - doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID),eq("notfound")); + doThrow(BBObjectNotFoundException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.INSTANCE_GROUP_ID)); doReturn("").when(namingServiceResources).deleteInstanceGroupName(instanceGroup); namingServiceDeleteTasks.deleteInstanceGroupName(execution); verify(namingServiceResources, times(1)).deleteInstanceGroupName(instanceGroup); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java index 65e7d249c5..cbd7605aa4 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCActivateTaskTest.java @@ -78,10 +78,10 @@ public class SDNCActivateTaskTest extends BaseTaskTest{ customer.getServiceSubscription().getServiceInstances().add(serviceInstance); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class)); - 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); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java index d021df56e0..b5509b1e12 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCAssignTasksTest.java @@ -80,11 +80,11 @@ public class SDNCAssignTasksTest extends BaseTaskTest{ doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(String.class)); - 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); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID), any())).thenReturn(volumeGroup); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VOLUME_GROUP_ID))).thenReturn(volumeGroup); } @Test diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java index f01596c86f..be792115c9 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCChangeAssignTasksTest.java @@ -69,9 +69,9 @@ public class SDNCChangeAssignTasksTest extends BaseTaskTest{ requestContext = setRequestContext(); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); - 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); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); } @Test diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java index 3d25addb9c..18048da50d 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCDeactivateTaskTest.java @@ -75,10 +75,10 @@ public class SDNCDeactivateTaskTest extends BaseTaskTest { network = setL3Network(); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any())).thenReturn(genericVnf); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID), any())).thenReturn(vfModule); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); } @@ -142,7 +142,7 @@ public class SDNCDeactivateTaskTest extends BaseTaskTest { @Test public void test_deactivateNetwork_exception() throws Exception { expectedException.expect(BpmnError.class); - doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any()); + doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID)); sdncDeactivateTasks.deactivateNetwork(execution); verify(sdncNetworkResources, times(0)).deactivateNetwork(network, serviceInstance, customer, requestContext, cloudRegion); } 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 4c5c50ebbf..28551baa7a 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 @@ -63,11 +63,11 @@ public class SDNCQueryTasksTest extends BaseTaskTest{ 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.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any())).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID), any())).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); } @@ -124,7 +124,7 @@ public class SDNCQueryTasksTest extends BaseTaskTest{ @Test public void queryVfModuleForVolumeGroupVfObjectExceptionTest() throws Exception { expectedException.expect(BpmnError.class); - doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID), any()); + doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID)); sdncQueryTasks.queryVfModuleForVolumeGroup(execution); verify(sdncVfModuleResources, times(0)).queryVfModule(any(VfModule.class)); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java index 1301787dff..527fe0d916 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/sdnc/tasks/SDNCUnassignTasksTest.java @@ -76,10 +76,10 @@ public class SDNCUnassignTasksTest extends BaseTaskTest{ cloudRegion = setCloudRegion(); network = setL3Network(); doThrow(new BpmnError("BPMN Error")).when(exceptionUtil).buildAndThrowWorkflowException(any(BuildingBlockExecution.class), eq(7000), any(Exception.class)); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID), any())).thenReturn(genericVnf); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID), any())).thenReturn(network); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID), any())).thenReturn(vfModule); - when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID), any())).thenReturn(serviceInstance); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.GENERIC_VNF_ID))).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.NETWORK_ID))).thenReturn(network); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID))).thenReturn(vfModule); + when(extractPojosForBB.extractByKey(any(),ArgumentMatchers.eq(ResourceKey.SERVICE_INSTANCE_ID))).thenReturn(serviceInstance); } @Test diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasksTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasksTest.java index 6eb22a6dcc..329f2cf8c1 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasksTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/sdno/tasks/SDNOHealthCheckTasksTest.java @@ -69,7 +69,7 @@ public class SDNOHealthCheckTasksTest extends TestDataSetup { public void before() throws BBObjectNotFoundException { genericVnf = setGenericVnf(); requestContext = setRequestContext(); - when(extractPojosForBB.extractByKey(any(),any(), any())).thenReturn(genericVnf); + when(extractPojosForBB.extractByKey(any(),any())).thenReturn(genericVnf); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java index 4aeed71177..4bf445949a 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/orchestration/AAIConfigurationResourcesTest.java @@ -98,7 +98,7 @@ public class AAIConfigurationResourcesTest extends TestDataSetup{ aaiConfigurationResources.createConfiguration(configuration); - assertEquals(OrchestrationStatus.INVENTORIED, configuration.getOrchestrationStatus()); + assertEquals(OrchestrationStatus.ASSIGNED, configuration.getOrchestrationStatus()); verify(MOCK_aaiResourcesClient, times(1)).create(any(AAIResourceUri.class), isA(org.onap.aai.domain.yang.Configuration.class)); } 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 f4d442bbc3..0ca80c75f7 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 @@ -62,6 +62,7 @@ public class GCTopologyOperationRequestMapperTest extends TestDataSetup { serviceInstance.setServiceInstanceId("ServiceInstanceId"); Configuration Configuration = new Configuration(); Configuration.setConfigurationId("ConfigurationId"); + Configuration.setConfigurationType("VLAN-NETWORK-RECEPTOR"); GenericResourceApiGcTopologyOperationInformation genericInfo = genObjMapper.deactivateOrUnassignVnrReqMapper (SDNCSvcAction.UNASSIGN, serviceInstance, requestContext, Configuration,"uuid",new URI("http://localhost")); @@ -70,6 +71,8 @@ public class GCTopologyOperationRequestMapperTest extends TestDataSetup { Assert.assertNotNull(genericInfo.getSdncRequestHeader()); Assert.assertNotNull(genericInfo.getClass()); Assert.assertNotNull(genericInfo.getServiceInformation()); + Assert.assertEquals("ConfigurationId", genericInfo.getConfigurationInformation().getConfigurationId()); + Assert.assertEquals("VLAN-NETWORK-RECEPTOR", genericInfo.getConfigurationInformation().getConfigurationType()); Assert.assertEquals("uuid",genericInfo.getSdncRequestHeader().getSvcRequestId()); Assert.assertEquals("http://localhost",genericInfo.getSdncRequestHeader().getSvcNotificationUrl()); } diff --git a/common/src/main/java/org/onap/so/client/RestTemplateConfig.java b/common/src/main/java/org/onap/so/client/RestTemplateConfig.java index 14556f1211..34ad6ef758 100644 --- a/common/src/main/java/org/onap/so/client/RestTemplateConfig.java +++ b/common/src/main/java/org/onap/so/client/RestTemplateConfig.java @@ -20,7 +20,10 @@ package org.onap.so.client; +import org.onap.so.configuration.rest.HttpComponentsClientConfiguration; import org.onap.so.logging.jaxrs.filter.SpringClientFilter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.BufferingClientHttpRequestFactory; @@ -30,11 +33,28 @@ import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateConfig { - @Bean - public RestTemplate restTemplate() { - RestTemplate restTemplate = new RestTemplate(); - restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory())); - restTemplate.getInterceptors().add(new SpringClientFilter()); - return restTemplate; - } + public static final String CONFIGURABLE_REST_TEMPLATE = "configurableRestTemplate"; + + @Autowired + private HttpComponentsClientConfiguration httpComponentsClientConfiguration; + + @Bean + public RestTemplate restTemplate() { + final RestTemplate restTemplate = new RestTemplate(); + restTemplate + .setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory())); + restTemplate.getInterceptors().add(new SpringClientFilter()); + return restTemplate; + } + + @Bean + @Qualifier(CONFIGURABLE_REST_TEMPLATE) + public RestTemplate configurableRestTemplate() { + final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = + httpComponentsClientConfiguration.httpComponentsClientHttpRequestFactory(); + final RestTemplate restTemplate = + new RestTemplate(new BufferingClientHttpRequestFactory(clientHttpRequestFactory)); + restTemplate.getInterceptors().add(new SpringClientFilter()); + return restTemplate; + } } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java index 21e36cde6c..34d560210c 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java @@ -21,7 +21,6 @@ package org.onap.so.client.aai; import java.io.Serializable; -import java.lang.reflect.Field; import java.net.URL; import java.util.HashMap; import java.util.Map; @@ -39,7 +38,9 @@ import org.onap.aai.domain.yang.Connector; import org.onap.aai.domain.yang.Customer; import org.onap.aai.domain.yang.Device; import org.onap.aai.domain.yang.ExtAaiNetwork; +import org.onap.aai.domain.yang.Flavor; import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.Image; import org.onap.aai.domain.yang.InstanceGroup; import org.onap.aai.domain.yang.L3Network; import org.onap.aai.domain.yang.LInterface; @@ -134,6 +135,8 @@ public class AAIObjectType implements GraphInventoryObjectType, Serializable { public static final AAIObjectType EXT_AAI_NETWORK = new AAIObjectType(AAINamespaceConstants.NETWORK, ExtAaiNetwork.class); public static final AAIObjectType AGGREGATE_ROUTE = new AAIObjectType(AAINamespaceConstants.NETWORK, AggregateRoute.class); public static final AAIObjectType L_INTERFACE = new AAIObjectType(AAIObjectType.VSERVER.uriTemplate(), LInterface.class); + public static final AAIObjectType IMAGE = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), Image.class); + public static final AAIObjectType FLAVOR = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), Flavor.class); public static final AAIObjectType UNKNOWN = new AAIObjectType("", "", "unknown"); public static final AAIObjectType DSL = new AAIObjectType("/dsl", "", "dsl"); diff --git a/common/src/main/java/org/onap/so/client/cds/CDSProperties.java b/common/src/main/java/org/onap/so/client/cds/CDSProperties.java index 42a4b47aa2..59c64e0459 100644 --- a/common/src/main/java/org/onap/so/client/cds/CDSProperties.java +++ b/common/src/main/java/org/onap/so/client/cds/CDSProperties.java @@ -1,23 +1,18 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2019 Bell Canada. - * ================================================================================ +/* + * Copyright (C) 2019 Bell Canada. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.cds; import org.onap.so.client.RestProperties; @@ -30,4 +25,6 @@ public interface CDSProperties extends RestProperties { int getPort(); String getBasicAuth(); + + int getTimeout(); } diff --git a/common/src/main/java/org/onap/so/configuration/rest/BasicHttpHeadersProvider.java b/common/src/main/java/org/onap/so/configuration/rest/BasicHttpHeadersProvider.java new file mode 100644 index 0000000000..7606f3a8d3 --- /dev/null +++ b/common/src/main/java/org/onap/so/configuration/rest/BasicHttpHeadersProvider.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.configuration.rest; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; + +/** + * @author waqas.ikram@est.tech + */ +public class BasicHttpHeadersProvider implements HttpHeadersProvider { + + public static final String AUTHORIZATION_HEADER = "Authorization"; + + private final HttpHeaders headers = new HttpHeaders(); + + public BasicHttpHeadersProvider(final String authorization) { + headers.add(AUTHORIZATION_HEADER, authorization); + headers.setContentType(MediaType.APPLICATION_JSON); + } + + public BasicHttpHeadersProvider() { + headers.setContentType(MediaType.APPLICATION_JSON); + } + + @Override + public HttpHeaders getHttpHeaders() { + return headers; + } + + @Override + public String toString() { + return "BasicHttpHeadersProvider [headers=" + headers + "]"; + } + +} diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/HttpClientConnectionConfiguration.java b/common/src/main/java/org/onap/so/configuration/rest/HttpClientConnectionConfiguration.java index 1260e535a1..a5a4cb7d53 100644 --- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/HttpClientConnectionConfiguration.java +++ b/common/src/main/java/org/onap/so/configuration/rest/HttpClientConnectionConfiguration.java @@ -1,29 +1,36 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. + * Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ -package org.onap.so.monitoring.configuration.rest; + +package org.onap.so.configuration.rest; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +/** + * This class is used configure the parameters needed for + * {@link org.apache.http.impl.client.CloseableHttpClient} + * + * @author waqas.ikram@est.tech + */ @Service public class HttpClientConnectionConfiguration { @@ -43,45 +50,38 @@ public class HttpClientConnectionConfiguration { private int maxConnectionsPerRoute; /** - * @return the socketTimeOut + * @return the socket connection time out in milliseconds */ public int getSocketTimeOutInMiliSeconds() { return (int) TimeUnit.SECONDS.toMillis(socketTimeOutInSeconds); } /** - * @return the maxConnections + * @return the maximum total connection value. */ public int getMaxConnections() { return maxConnections; } /** - * @return the maxConnectionsPerRoute + * @return the maximum connection per route value. */ public int getMaxConnectionsPerRoute() { return maxConnectionsPerRoute; } /** - * @return the connectionTimeOut + * @return the connect time out value in milliseconds. */ public int getConnectionTimeOutInMilliSeconds() { return (int) TimeUnit.SECONDS.toMillis(connectionTimeOutInSeconds); } /** - * @return the timeToLive + * @return the connection time to live value in mintues. */ public int getTimeToLiveInMins() { return (int) TimeUnit.SECONDS.toMinutes(timeToLiveInSeconds); } - @Override - public String toString() { - return "HttpClientConnectionConfiguration [connectionTimeOutInSeconds=" + connectionTimeOutInSeconds - + ", socketTimeOutInSeconds=" + socketTimeOutInSeconds + ", timeToLiveInSeconds=" + timeToLiveInSeconds - + ", maxConnections=" + maxConnections + ", maxConnectionsPerRoute=" + maxConnectionsPerRoute + "]"; - } - } diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/RestTemplateConfiguration.java b/common/src/main/java/org/onap/so/configuration/rest/HttpComponentsClientConfiguration.java index f8f0f687cf..e943aef159 100644 --- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/RestTemplateConfiguration.java +++ b/common/src/main/java/org/onap/so/configuration/rest/HttpComponentsClientConfiguration.java @@ -17,8 +17,8 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - -package org.onap.so.monitoring.configuration.rest; + +package org.onap.so.configuration.rest; import java.util.concurrent.TimeUnit; @@ -27,35 +27,23 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; -import org.springframework.web.client.RestTemplate; /** - * @author waqas.ikram@ericsson.com + * Allow user to configure {@link org.apache.http.client.HttpClient} + * + * @author waqas.ikram@est.tech */ @Configuration -public class RestTemplateConfiguration { +public class HttpComponentsClientConfiguration { - public static final String DATABASE_REST_TEMPLATE = "databaseRestTemplate"; - - public static final String CAMUNDA_REST_TEMPLATE = "camundaRestTemplate"; + private final HttpClientConnectionConfiguration clientConnectionConfiguration; @Autowired - private HttpClientConnectionConfiguration clientConnectionConfiguration; - - @Bean - @Qualifier(CAMUNDA_REST_TEMPLATE) - public RestTemplate camundaRestTemplate() { - return new RestTemplate(httpComponentsClientHttpRequestFactory()); - } - - @Bean - @Qualifier(DATABASE_REST_TEMPLATE) - public RestTemplate dataBasecamundaRestTemplate() { - return new RestTemplate(httpComponentsClientHttpRequestFactory()); + public HttpComponentsClientConfiguration(final HttpClientConnectionConfiguration clientConnectionConfiguration) { + this.clientConnectionConfiguration = clientConnectionConfiguration; } @Bean diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/HttpRestServiceProvider.java b/common/src/main/java/org/onap/so/configuration/rest/HttpHeadersProvider.java index 4606c04e05..0cff7b4ba0 100644 --- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/HttpRestServiceProvider.java +++ b/common/src/main/java/org/onap/so/configuration/rest/HttpHeadersProvider.java @@ -1,33 +1,35 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. + * Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ -package org.onap.so.monitoring.rest.service; -import com.google.common.base.Optional; +package org.onap.so.configuration.rest; + +import org.springframework.http.HttpHeaders; /** - * @author waqas.ikram@ericsson.com + * Providers {@link org.springframework.http.HttpHeaders} for HTTP requests + * + * @author waqas.ikram@est.tech + * */ -public interface HttpRestServiceProvider { - - public <T> Optional<T> getHttpResponse(final String url, final Class<T> clazz); +public interface HttpHeadersProvider { - public <T> Optional<T> postHttpRequest(final Object object, final String url, final Class<T> clazz); + HttpHeaders getHttpHeaders(); } diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java index cecef1945b..ed63a706a2 100644 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java @@ -57,6 +57,7 @@ public class SpringClientFilter implements ClientHttpRequestInterceptor { } private void processRequest(HttpRequest request, byte[] body) throws IOException { + setInvocationId(); setupHeaders(request); setupMDC(request); if (log.isDebugEnabled()) { @@ -89,7 +90,6 @@ public class SpringClientFilter implements ClientHttpRequestInterceptor { MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, clientRequest.getURI().toString()); MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - setInvocationId(); MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY,extractTargetEntity(clientRequest)); } diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/exception/InvalidRestRequestException.java b/common/src/main/java/org/onap/so/rest/exceptions/InvalidRestRequestException.java index 4d3c489fa9..2a9799315e 100644 --- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/exception/InvalidRestRequestException.java +++ b/common/src/main/java/org/onap/so/rest/exceptions/InvalidRestRequestException.java @@ -1,26 +1,27 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. + * Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ -package org.onap.so.monitoring.exception; + +package org.onap.so.rest.exceptions; /** - * @author waqas.ikram@ericsson.com + * @author waqas.ikram@est.tech * */ public class InvalidRestRequestException extends RuntimeException { diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/exception/RestProcessingException.java b/common/src/main/java/org/onap/so/rest/exceptions/RestProcessingException.java index ab25854542..e8ce00c7e5 100644 --- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/exception/RestProcessingException.java +++ b/common/src/main/java/org/onap/so/rest/exceptions/RestProcessingException.java @@ -1,26 +1,26 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. + * Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ -package org.onap.so.monitoring.exception; +package org.onap.so.rest.exceptions; /** - * @author waqas.ikram@ericsson.com + * @author waqas.ikram@est.tech * */ public class RestProcessingException extends RuntimeException { diff --git a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java new file mode 100644 index 0000000000..43b2fb4292 --- /dev/null +++ b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.rest.service; + +import org.springframework.http.ResponseEntity; + +import com.google.common.base.Optional; + +/** + * @author waqas.ikram@est.tech + */ +public interface HttpRestServiceProvider { + + /** + * Execute the HTTP GET to the given URI template + * + * @param url the URL + * @param clazz the type of the return value + * @return Returns the body of this entity. + */ + public <T> Optional<T> get(final String url, final Class<T> clazz); + + /** + * Execute the HTTP GET to the given URI template + * + * @param url the URL + * @param clazz the type of the return value + * @return Returns the {@link ResponseEntity}. + */ + public <T> ResponseEntity<T> getHttpResponse(final String url, final Class<T> clazz); + + + /** + * Execute the HTTP POST to the given URI template + * + * @param object the entity (i.e. body) to write to the request + * @param url the URL + * @param clazz the type of the return value + * @return Returns the body of this entity. + */ + public <T> Optional<T> post(final Object object, final String url, final Class<T> clazz); + + /** + * Execute the HTTP POST to the given URI template + * + * @param object the entity (i.e. body) to write to the request + * @param url the URL + * @param clazz the type of the return value + * @return Returns the {@link ResponseEntity}. + */ + public <T> ResponseEntity<T> postHttpRequest(final Object object, final String url, final Class<T> clazz); + + +} diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/HttpRestServiceProviderImpl.java b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java index 82a54c10a2..032df84a98 100644 --- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/HttpRestServiceProviderImpl.java +++ b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java @@ -1,27 +1,33 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. + * Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * + * * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ -package org.onap.so.monitoring.rest.service; -import org.onap.so.monitoring.exception.InvalidRestRequestException; -import org.onap.so.monitoring.exception.RestProcessingException; +package org.onap.so.rest.service; + +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.configuration.rest.HttpHeadersProvider; +import org.onap.so.rest.exceptions.InvalidRestRequestException; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -31,39 +37,54 @@ import org.springframework.web.client.RestTemplate; import com.google.common.base.Optional; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** - * @author waqas.ikram@ericsson.com + * A Service to perform HTTP requests + * + * @author waqas.ikram@est.tech */ public class HttpRestServiceProviderImpl implements HttpRestServiceProvider { private static final Logger LOGGER = LoggerFactory.getLogger(HttpRestServiceProviderImpl.class); private final RestTemplate restTemplate; + private final HttpHeadersProvider httpHeadersProvider; public HttpRestServiceProviderImpl(final RestTemplate restTemplate) { this.restTemplate = restTemplate; + this.httpHeadersProvider = new BasicHttpHeadersProvider(); + } + + public HttpRestServiceProviderImpl(final RestTemplate restTemplate, final HttpHeadersProvider httpHeadersProvider) { + this.restTemplate = restTemplate; + this.httpHeadersProvider = httpHeadersProvider; + } + + @Override + public <T> Optional<T> get(final String url, final Class<T> clazz) { + final ResponseEntity<T> response = getHttpResponse(url, clazz); + if (!response.getStatusCode().equals(HttpStatus.OK)) { + final String message = + "Unable to invoke HTTP GET using URL: " + url + ", Response Code: " + response.getStatusCode(); + LOGGER.error(message); + return Optional.absent(); + } + + if (response.hasBody()) { + return Optional.of(response.getBody()); + } + return Optional.absent(); } + @Override - public <T> Optional<T> getHttpResponse(final String url, final Class<T> clazz) { - LOGGER.trace("Will invoke HTTP GET using URL: " + url); + public <T> ResponseEntity<T> getHttpResponse(final String url, final Class<T> clazz) { + LOGGER.trace("Will invoke HTTP GET using URL: {}", url); try { - final ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, null, clazz); - if (!response.getStatusCode().equals(HttpStatus.OK)) { - final String message = "Unable to invoke HTTP GET using URL: " + url + - ", Response Code: " + response.getStatusCode(); - LOGGER.error(message); - return Optional.absent(); - } + final HttpEntity<?> request = new HttpEntity<>(getHttpHeaders()); + return restTemplate.exchange(url, HttpMethod.GET, request, clazz); - if (response.hasBody()) { - return Optional.of(response.getBody()); - } } catch (final HttpClientErrorException httpClientErrorException) { - final String message = "Unable to invoke HTTP GET using url: " + url + ", Response: " + - httpClientErrorException.getRawStatusCode(); + final String message = "Unable to invoke HTTP GET using url: " + url + ", Response: " + + httpClientErrorException.getRawStatusCode(); LOGGER.error(message, httpClientErrorException); final int rawStatusCode = httpClientErrorException.getRawStatusCode(); if (rawStatusCode == HttpStatus.BAD_REQUEST.value() || rawStatusCode == HttpStatus.NOT_FOUND.value()) { @@ -72,48 +93,52 @@ public class HttpRestServiceProviderImpl implements HttpRestServiceProvider { throw new RestProcessingException("Unable to invoke HTTP GET using URL: " + url); } catch (final RestClientException restClientException) { - LOGGER.error("Unable to invoke HTTP GET using url: " + url, restClientException); - throw new RestProcessingException("Unable to invoke HTTP GET using URL: " + - url, restClientException); + LOGGER.error("Unable to invoke HTTP GET using url: {}", url, restClientException); + throw new RestProcessingException("Unable to invoke HTTP GET using URL: " + url, restClientException); + } + } + + @Override + public <T> Optional<T> post(final Object object, final String url, final Class<T> clazz) { + final ResponseEntity<T> response = postHttpRequest(object, url, clazz); + if (!response.getStatusCode().equals(HttpStatus.OK)) { + final String message = + "Unable to invoke HTTP GET using URL: " + url + ", Response Code: " + response.getStatusCode(); + LOGGER.error(message); + return Optional.absent(); + } + + if (response.hasBody()) { + return Optional.of(response.getBody()); } return Optional.absent(); } + @Override - public <T> Optional<T> postHttpRequest(final Object object, final String url, final Class<T> clazz) { + public <T> ResponseEntity<T> postHttpRequest(final Object object, final String url, final Class<T> clazz) { try { - final HttpEntity<?> request = new HttpEntity<>(object); - final ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, request, clazz); - if (!response.getStatusCode().equals(HttpStatus.OK)) { - final String message = "Unable to invoke HTTP GET using URL: " + url + - ", Response Code: " + response.getStatusCode(); - LOGGER.error(message); - return Optional.absent(); - } - - if (response.hasBody()) { - return Optional.of(response.getBody()); - } + final HttpEntity<?> request = new HttpEntity<>(object, getHttpHeaders()); + return restTemplate.exchange(url, HttpMethod.POST, request, clazz); } catch (final HttpClientErrorException httpClientErrorException) { - final String message = "Unable to invoke HTTP POST using url: " + url + - ", Response: " + httpClientErrorException.getRawStatusCode(); + final String message = "Unable to invoke HTTP POST using url: " + url + ", Response: " + + httpClientErrorException.getRawStatusCode(); LOGGER.error(message, httpClientErrorException); final int rawStatusCode = httpClientErrorException.getRawStatusCode(); if (rawStatusCode == HttpStatus.BAD_REQUEST.value() || rawStatusCode == HttpStatus.NOT_FOUND.value()) { throw new InvalidRestRequestException("No result found for given url: " + url); } - throw new RestProcessingException("Unable to invoke HTTP POST using URL: " + url); + throw new RestProcessingException("Unable to invoke HTTP GET using URL: " + url); } catch (final RestClientException restClientException) { - LOGGER.error("Unable to invoke HTTP POST using url: " + url, restClientException); - throw new RestProcessingException("Unable to invoke HTTP POST using URL: " - + url, restClientException); + LOGGER.error("Unable to invoke HTTP POST using url: {}", url, restClientException); + throw new RestProcessingException("Unable to invoke HTTP GET using URL: " + url, restClientException); } - - return Optional.absent(); } - + private HttpHeaders getHttpHeaders() { + return httpHeadersProvider.getHttpHeaders(); + } } diff --git a/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java b/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java index 514c595100..b0e67090ff 100644 --- a/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java +++ b/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java @@ -1,23 +1,18 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2019 Bell Canada. - * ================================================================================ +/* + * Copyright (C) 2019 Bell Canada. + * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.cds; import java.net.MalformedURLException; @@ -68,4 +63,9 @@ public class TestCDSPropertiesImpl implements CDSProperties { public boolean mapNotFoundToEmpty() { return false; } + + @Override + public int getTimeout() { + return 60; + } } diff --git a/common/src/test/java/org/onap/so/configuration/rest/BasicHttpHeadersProviderTest.java b/common/src/test/java/org/onap/so/configuration/rest/BasicHttpHeadersProviderTest.java new file mode 100644 index 0000000000..3e762cfbe7 --- /dev/null +++ b/common/src/test/java/org/onap/so/configuration/rest/BasicHttpHeadersProviderTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.configuration.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.onap.so.configuration.rest.BasicHttpHeadersProvider.AUTHORIZATION_HEADER; + +import java.util.Arrays; + +import org.junit.Test; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; + + +/** + * @author waqas.ikram@est.tech + * + */ +public class BasicHttpHeadersProviderTest { + + private static final String BASIC_AUTH_VALUE = "Basic AuthValue"; + + @Test + public void test_getHttpHeaders_ContentTypeIsJson() { + final HttpHeadersProvider objUnderTest = new BasicHttpHeadersProvider(); + final HttpHeaders actualHttpHeaders = objUnderTest.getHttpHeaders(); + assertNull(actualHttpHeaders.get(AUTHORIZATION_HEADER)); + assertEquals(MediaType.APPLICATION_JSON, actualHttpHeaders.getContentType()); + } + + @Test + public void test_getHttpHeaders_ContainAuthorizationHeader() { + final HttpHeadersProvider objUnderTest = new BasicHttpHeadersProvider(BASIC_AUTH_VALUE); + final HttpHeaders actualHttpHeaders = objUnderTest.getHttpHeaders(); + assertEquals(Arrays.asList(BASIC_AUTH_VALUE), actualHttpHeaders.get(AUTHORIZATION_HEADER)); + assertEquals(MediaType.APPLICATION_JSON, actualHttpHeaders.getContentType()); + } + +} diff --git a/common/src/test/java/org/onap/so/configuration/rest/HttpComponentsClientConfigurationTest.java b/common/src/test/java/org/onap/so/configuration/rest/HttpComponentsClientConfigurationTest.java new file mode 100644 index 0000000000..5084acc934 --- /dev/null +++ b/common/src/test/java/org/onap/so/configuration/rest/HttpComponentsClientConfigurationTest.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.configuration.rest; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; + +/** + * @author waqas.ikram@est.tech + */ +public class HttpComponentsClientConfigurationTest { + + @Test + public void test_httpComponentsClientHttpRequestFactory_HttpComponentsClientHttpRequestFactoryNotNull() { + final HttpClientConnectionConfiguration clientConnectionConfiguration = new HttpClientConnectionConfiguration(); + final HttpComponentsClientConfiguration objUnderTest = + new HttpComponentsClientConfiguration(clientConnectionConfiguration); + + final HttpComponentsClientHttpRequestFactory factory = objUnderTest.httpComponentsClientHttpRequestFactory(); + assertNotNull(factory); + assertNotNull(factory.getHttpClient()); + + } + +} diff --git a/common/src/test/java/org/onap/so/rest/service/HttpRestServiceProviderImplTest.java b/common/src/test/java/org/onap/so/rest/service/HttpRestServiceProviderImplTest.java new file mode 100644 index 0000000000..a738afe565 --- /dev/null +++ b/common/src/test/java/org/onap/so/rest/service/HttpRestServiceProviderImplTest.java @@ -0,0 +1,252 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.rest.service; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.rest.exceptions.InvalidRestRequestException; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.google.common.base.Optional; + + +/** + * @author waqas.ikram@est.tech + */ +@RunWith(MockitoJUnitRunner.class) +public class HttpRestServiceProviderImplTest { + + private static final String BODY = "{}"; + private static final String DUMMY_URL = "http://localhost:9000/dummy/url"; + + @Mock + private RestTemplate mockRestTemplate; + + @Mock + private ResponseEntity<String> mockEntity; + + @Test + public void test_get_returnOptionalPresentIfResponseIsOKAndHasBody() { + + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.OK); + when(mockEntity.hasBody()).thenReturn(true); + when(mockEntity.getBody()).thenReturn(BODY); + + final Optional<String> actual = objUnderTest.get(DUMMY_URL, String.class); + + assertTrue(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), + eq(String.class)); + } + + @Test + public void test_get_returnOptionalPresentIfResponseIsNotOK() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR); + + final Optional<String> actual = objUnderTest.get(DUMMY_URL, String.class); + + assertFalse(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), + eq(String.class)); + } + + @Test + public void test_get_returnOptionalPresentIfResponseIsOKAndNoBody() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.OK); + when(mockEntity.hasBody()).thenReturn(false); + + final Optional<String> actual = objUnderTest.get(DUMMY_URL, String.class); + + assertFalse(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), + eq(String.class)); + } + + @Test(expected = InvalidRestRequestException.class) + public void test_get_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionWithHttpStatusBadRequest() { + assertGetErrorScenario(HttpStatus.BAD_REQUEST); + + } + + @Test(expected = InvalidRestRequestException.class) + public void test_get_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionWithHttpStatusNotFoundHttpStatus() { + assertGetErrorScenario(HttpStatus.NOT_FOUND); + } + + @Test(expected = RestProcessingException.class) + public void test_get_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionOccured() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenThrow(HttpClientErrorException.class); + + objUnderTest.get(DUMMY_URL, String.class); + } + + @Test(expected = RestProcessingException.class) + public void test_get_ThrowsInvalidRestRequestExceptionifRestProcessingExceptionOccured() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenThrow(RestClientException.class); + + objUnderTest.get(DUMMY_URL, String.class); + } + + @Test + public void test_post_returnOptionalPresentIfResponseIsOKAndHasBody() { + + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.OK); + when(mockEntity.hasBody()).thenReturn(true); + when(mockEntity.getBody()).thenReturn(BODY); + + final Optional<String> actual = objUnderTest.post(BODY, DUMMY_URL, String.class); + + assertTrue(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), + eq(String.class)); + } + + @Test + public void test_post_returnOptionalPresentIfResponseIsOKAndHasNoBody() { + + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.OK); + when(mockEntity.hasBody()).thenReturn(false); + + final Optional<String> actual = objUnderTest.post(BODY, DUMMY_URL, String.class); + + assertFalse(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), + eq(String.class)); + } + + + @Test + public void test_post_returnOptionalPresentIfResponseIsNotOKAndHasBody() { + + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.PARTIAL_CONTENT); + + final Optional<String> actual = objUnderTest.post(BODY, DUMMY_URL, String.class); + + assertFalse(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), + eq(String.class)); + } + + @Test(expected = InvalidRestRequestException.class) + public void test_post_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionWithHttpStatusBadRequest() { + assertPostErrorScenario(HttpStatus.BAD_REQUEST); + + } + + @Test(expected = InvalidRestRequestException.class) + public void test_post_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionWithHttpStatusNotFoundHttpStatus() { + assertPostErrorScenario(HttpStatus.NOT_FOUND); + } + + @Test(expected = RestProcessingException.class) + public void test_post_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionOccured() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenThrow(HttpClientErrorException.class); + + objUnderTest.post(BODY, DUMMY_URL, String.class); + } + + @Test(expected = RestProcessingException.class) + public void test_post_ThrowsInvalidRestRequestExceptionifRestProcessingExceptionOccured() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenThrow(RestClientException.class); + + objUnderTest.post(BODY, DUMMY_URL, String.class); + } + + private void assertPostErrorScenario(final HttpStatus status) { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + final HttpClientErrorException errorException = new HttpClientErrorException(status); + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenThrow(errorException); + + objUnderTest.post(BODY, DUMMY_URL, String.class); + } + + private void assertGetErrorScenario(final HttpStatus status) { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + final HttpClientErrorException errorException = new HttpClientErrorException(status); + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenThrow(errorException); + + objUnderTest.get(DUMMY_URL, String.class); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java index e09dcd8d2d..cd05aa558e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java @@ -116,10 +116,11 @@ public class ActivateVnfStatusOperationalEnvironment { // Update AAI to ACTIVE if Overall success if (isOverallSuccess) { - OperationalEnvironment aaiOpEnv = getAAIOperationalEnvironment(this.queryServiceModelResponse.getVnfOperationalEnvId()); + String vnfOperationalEnvironmentId = this.queryServiceModelResponse.getVnfOperationalEnvId(); + OperationalEnvironment aaiOpEnv = getAAIOperationalEnvironment(vnfOperationalEnvironmentId); if (aaiOpEnv != null) { aaiOpEnv.setOperationalEnvironmentStatus("ACTIVE"); - aaiHelper.updateAaiOperationalEnvironment(operationalEnvironmentId, aaiOpEnv); + aaiHelper.updateAaiOperationalEnvironment(vnfOperationalEnvironmentId, aaiOpEnv); }else { requestDb.updateInfraFailureCompletion("Unable to update ACTIVATE status in AAI. ", this.origRequestId, this.queryServiceModelResponse.getVnfOperationalEnvId()); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java index 6722941f95..c0250f7315 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java @@ -240,9 +240,9 @@ public class ActivateVnfStatusOperationalEnvironmentTest extends BaseTest{ .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId")) .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + stubFor(put(urlPathEqualTo("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId")) .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); activateVnfStatus.execute(requestId, request); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/logback-test.xml b/mso-api-handlers/mso-api-handler-infra/src/test/resources/logback-test.xml index 4da57a15f9..5e6b88c039 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/logback-test.xml +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/logback-test.xml @@ -38,4 +38,4 @@ <logger name="wiremock.org" level="ERROR" /> -</configuration>
\ No newline at end of file +</configuration> diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql index fddd7adbf4..e46996181e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql @@ -776,61 +776,105 @@ AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = latin1; CREATE TABLE IF NOT EXISTS cvnfc_customization ( -`ID` INT(11) NOT NULL AUTO_INCREMENT, -`MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, -`MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, -`MODEL_UUID` VARCHAR(200) NOT NULL, -`MODEL_INVARIANT_UUID` VARCHAR(200) NOT NULL, -`MODEL_VERSION` VARCHAR(20) NOT NULL, -`MODEL_NAME` VARCHAR(200) NOT NULL, -`TOSCA_NODE_TYPE` VARCHAR(200) NOT NULL, -`DESCRIPTION` VARCHAR(1200) NULL DEFAULT NULL, -`NFC_FUNCTION` VARCHAR(200) NULL, -`NFC_NAMING_CODE` VARCHAR(200) NULL, -`CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, -`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, -`VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, -`VNFC_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, PRIMARY KEY (`ID`), INDEX `fk_cvnfc_customization__vf_module_customization1_idx` (`VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` ASC), INDEX `fk_cvnfc_customization__vnfc_customization1_idx` (`VNFC_CUST_MODEL_CUSTOMIZATION_UUID` ASC), INDEX `fk_cvnfc_customization__vnf_resource_customization1_idx` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC), UNIQUE INDEX `UK_cvnfc_customization` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC, `VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` ASC, `MODEL_CUSTOMIZATION_UUID` ASC), INDEX `fk_cvnfc_customization__vnf_vfmod_cvnfc_config_cust1_idx` (`MODEL_CUSTOMIZATION_UUID` ASC), CONSTRAINT `fk_cvnfc_customization__vf_module_customization1` FOREIGN KEY (`VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID`) REFERENCES `vf_module_customization` (`MODEL_CUSTOMIZATION_UUID`) ON -DELETE CASCADE ON -UPDATE CASCADE, CONSTRAINT `fk_cvnfc_customization__vnfc_customization1` FOREIGN KEY (`VNFC_CUST_MODEL_CUSTOMIZATION_UUID`) REFERENCES `vnfc_customization` (`MODEL_CUSTOMIZATION_UUID`) ON -DELETE CASCADE ON -UPDATE CASCADE, CONSTRAINT `fk_cvnfc_customization__vnf_resource_customization1` FOREIGN KEY (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID`) REFERENCES `vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) ON -DELETE CASCADE ON -UPDATE CASCADE) ENGINE = InnoDB AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = latin1; + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + `MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, + `MODEL_UUID` VARCHAR(200) NOT NULL, + `MODEL_INVARIANT_UUID` VARCHAR(200) NOT NULL, + `MODEL_VERSION` VARCHAR(20) NOT NULL, + `MODEL_NAME` VARCHAR(200) NOT NULL, + `TOSCA_NODE_TYPE` VARCHAR(200) NOT NULL, + `DESCRIPTION` VARCHAR(1200) NULL DEFAULT NULL, + `NFC_FUNCTION` VARCHAR(200) NULL, + `NFC_NAMING_CODE` VARCHAR(200) NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + `VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + `VNFC_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + PRIMARY KEY (`ID`), + INDEX `fk_cvnfc_customization__vf_module_customization1_idx` ( + `VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` ASC + ), + INDEX `fk_cvnfc_customization__vnfc_customization1_idx` ( + `VNFC_CUST_MODEL_CUSTOMIZATION_UUID` ASC + ), + INDEX `fk_cvnfc_customization__vnf_resource_customization1_idx` ( + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC + ), + UNIQUE INDEX `UK_cvnfc_customization` ( + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC, + `VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` ASC, + `MODEL_CUSTOMIZATION_UUID` ASC + ), + INDEX `fk_cvnfc_customization__vnf_vfmod_cvnfc_config_cust1_idx` (`MODEL_CUSTOMIZATION_UUID` ASC), + CONSTRAINT `fk_cvnfc_customization__vf_module_customization1` FOREIGN KEY ( + `VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` + ) REFERENCES `vf_module_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_cvnfc_customization__vnfc_customization1` FOREIGN KEY ( + `VNFC_CUST_MODEL_CUSTOMIZATION_UUID` + ) REFERENCES `vnfc_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_cvnfc_customization__vnf_resource_customization1` FOREIGN KEY ( + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` + ) REFERENCES `vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = latin1; CREATE TABLE IF NOT EXISTS vnf_vfmodule_cvnfc_configuration_customization ( - `ID` INT(11) NOT NULL AUTO_INCREMENT, - `MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `VF_MODULE_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `CVNFC_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, - `CONFIGURATION_TYPE` VARCHAR(200) NULL, - `CONFIGURATION_ROLE` VARCHAR(200) NULL, - `CONFIGURATION_FUNCTION` VARCHAR(200) NULL, - `POLICY_NAME` VARCHAR(200) NULL, - `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - `CONFIGURATION_MODEL_UUID` VARCHAR(200) NOT NULL, - PRIMARY KEY (`ID`), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__configuration_idx` (`CONFIGURATION_MODEL_UUID` ASC), - UNIQUE INDEX `UK_vnf_vfmodule_cvnfc_configuration_customization` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC , `VF_MODULE_MODEL_CUSTOMIZATION_UUID` ASC , `CVNFC_MODEL_CUSTOMIZATION_UUID` ASC , `MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__cvnfc_cust1_idx` (`CVNFC_MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__vf_module_cust_idx` (`VF_MODULE_MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__vnf_res_cust_idx` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC), - CONSTRAINT `fk_vnf_vfmod_cvnfc_config_cust__configuration_resource` FOREIGN KEY (`CONFIGURATION_MODEL_UUID`) - REFERENCES `configuration` (`MODEL_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_cvnfc_configuration_customization__cvnfc_customization1` FOREIGN KEY (`CVNFC_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `cvnfc_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_vnf_configuration_cvnfc_customization__vf_module_customiza1` FOREIGN KEY (`VF_MODULE_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `vf_module_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_vfmodule_cvnfc_configuration_customization__vnf_resource_c1` FOREIGN KEY (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=INNODB AUTO_INCREMENT=20654 DEFAULT CHARACTER SET=LATIN1; + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + `MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, + `CONFIGURATION_TYPE` VARCHAR(200) NULL, + `CONFIGURATION_ROLE` VARCHAR(200) NULL, + `CONFIGURATION_FUNCTION` VARCHAR(200) NULL, + `POLICY_NAME` VARCHAR(200) NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `CONFIGURATION_MODEL_UUID` VARCHAR(200) NOT NULL, + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) DEFAULT NULL, + `VF_MODULE_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) DEFAULT NULL, + `CVNFC_CUSTOMIZATION_ID` INT(11) DEFAULT NULL, + PRIMARY KEY (`ID`), + INDEX `fk_vnf_vfmodule_cvnfc_config_cust__configuration_idx` (`CONFIGURATION_MODEL_UUID` ASC), + + CONSTRAINT `fk_vnf_vfmod_cvnfc_config_cust__configuration_resource` FOREIGN KEY (`CONFIGURATION_MODEL_UUID`) + REFERENCES `configuration` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = INNODB AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = LATIN1; + +CREATE TABLE IF NOT EXISTS `pnf_resource` ( + `ORCHESTRATION_MODE` varchar(20) NOT NULL DEFAULT 'HEAT', + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) DEFAULT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `MODEL_NAME` varchar(200) DEFAULT NULL, + `TOSCA_NODE_TYPE` varchar(200) DEFAULT NULL, + `RESOURCE_CATEGORY` varchar(200) DEFAULT NULL, + `RESOURCE_SUB_CATEGORY` varchar(200) DEFAULT NULL, + PRIMARY KEY (`MODEL_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + +CREATE TABLE IF NOT EXISTS `pnf_resource_customization` ( + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `NF_TYPE` varchar(200) DEFAULT NULL, + `NF_ROLE` varchar(200) DEFAULT NULL, + `NF_FUNCTION` varchar(200) DEFAULT NULL, + `NF_NAMING_CODE` varchar(200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `PNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, + `MULTI_STAGE_DESIGN` varchar(20) DEFAULT NULL, + `RESOURCE_INPUT` varchar(2000) DEFAULT NULL, + `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, + PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), + KEY `fk_pnf_resource_customization__pnf_resource1_idx` (`PNF_RESOURCE_MODEL_UUID`), + CONSTRAINT `fk_pnf_resource_customization__pnf_resource1` FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) REFERENCES `pnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +CREATE TABLE IF NOT EXISTS `pnf_resource_customization_to_service` ( + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `RESOURCE_MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`SERVICE_MODEL_UUID`,`RESOURCE_MODEL_CUSTOMIZATION_UUID`) +)ENGINE=InnoDB DEFAULT CHARSET=latin1; --------START Request DB SCHEMA -------- CREATE DATABASE requestdb; USE requestdb; diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java index 34832b9917..0a74c1d7be 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/RequestProcessingData.java @@ -33,10 +33,12 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.openpojo.business.annotation.BusinessKey; /** @@ -50,6 +52,8 @@ import com.openpojo.business.annotation.BusinessKey; */ @Entity + +@JsonInclude(Include.NON_NULL) @Table(name = "request_processing_data") public class RequestProcessingData implements Serializable{ diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java index 5958397851..9c29d968c9 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java @@ -308,7 +308,7 @@ public class RequestsDbClient { public void saveRequestProcessingData(RequestProcessingData requestProcessingData) { HttpHeaders headers = getHttpHeaders(); - URI uri = getUri(endpoint + requestProcessingDataURI); + URI uri = getUri(requestProcessingDataURI); HttpEntity<RequestProcessingData> entity = new HttpEntity<>(requestProcessingData, headers); restTemplate.postForLocation(uri, entity); } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcCustomization.java index b1ad0de5ca..9f081ccd34 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcCustomization.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/CvnfcCustomization.java @@ -121,7 +121,7 @@ public class CvnfcCustomization implements Serializable { @Override public int hashCode() { - return new HashCodeBuilder().append(modelCustomizationUUID).toHashCode(); + return new HashCodeBuilder().append(modelCustomizationUUID).append(vfModuleCustomization).append(vnfcCustomization).append(vnfResourceCustomization).toHashCode(); } @Override @@ -249,6 +249,7 @@ public class CvnfcCustomization implements Serializable { this.created = created; } + @LinkedResource public VfModuleCustomization getVfModuleCustomization() { return vfModuleCustomization; } @@ -257,6 +258,7 @@ public class CvnfcCustomization implements Serializable { this.vfModuleCustomization = vfModuleCustomization; } + @LinkedResource public VnfcCustomization getVnfcCustomization() { return vnfcCustomization; } @@ -265,6 +267,7 @@ public class CvnfcCustomization implements Serializable { this.vnfcCustomization = vnfcCustomization; } + @LinkedResource public VnfResourceCustomization getVnfResourceCustomization() { return vnfResourceCustomization; } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java index b893cec0f2..6902d8f36a 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/OrchestrationStatus.java @@ -29,7 +29,8 @@ public enum OrchestrationStatus { PENDING_ACTIVATION("PendingActivation", "pending.?activation"), PENDING_CREATE("PendingCreate", "pending.?create"), PENDING_DELETE("PendingDelete", "pending.?delete"), - PRECREATED("PreCreated", "pre.?created"); + PRECREATED("PreCreated", "pre.?created"), + CONFIGASSIGNED("ConfigAssigned", "config.?assigned"); private final String name; private final String fuzzyMatcher; diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfVfmoduleCvnfcConfigurationCustomization.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfVfmoduleCvnfcConfigurationCustomization.java index 7ce657c5c7..e425ebbc64 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfVfmoduleCvnfcConfigurationCustomization.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/beans/VnfVfmoduleCvnfcConfigurationCustomization.java @@ -31,6 +31,7 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; import javax.persistence.ManyToOne; import javax.persistence.PrePersist; import javax.persistence.Table; @@ -74,7 +75,8 @@ public class VnfVfmoduleCvnfcConfigurationCustomization implements Serializable private String configurationFunction; @Column(name = "POLICY_NAME") - private String policyName; + private String policyName; + @Column(name = "CREATION_TIMESTAMP", updatable = false) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") @@ -87,7 +89,7 @@ public class VnfVfmoduleCvnfcConfigurationCustomization implements Serializable @BusinessKey @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) - @JoinColumn(name = "CVNFC_MODEL_CUSTOMIZATION_UUID", referencedColumnName = "MODEL_CUSTOMIZATION_UUID") + @JoinColumn(name = "CVNFC_CUSTOMIZATION_ID") private CvnfcCustomization cvnfcCustomization; @BusinessKey @@ -98,7 +100,7 @@ public class VnfVfmoduleCvnfcConfigurationCustomization implements Serializable @BusinessKey @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID") - private VnfResourceCustomization vnfResourceCustomization; + private VnfResourceCustomization vnfResourceCustomization; @Override public boolean equals(final Object other) { @@ -222,6 +224,7 @@ public class VnfVfmoduleCvnfcConfigurationCustomization implements Serializable this.cvnfcCustomization = cvnfcCustomization; } + @LinkedResource public VfModuleCustomization getVfModuleCustomization() { return vfModuleCustomization; } @@ -230,6 +233,7 @@ public class VnfVfmoduleCvnfcConfigurationCustomization implements Serializable this.vfModuleCustomization = vfModuleCustomization; } + @LinkedResource public VnfResourceCustomization getVnfResourceCustomization() { return vnfResourceCustomization; } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java index f73044747c..3e35e78e7a 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/client/CatalogDbClient.java @@ -234,8 +234,6 @@ public class CatalogDbClient { private final Client<ControllerSelectionReference> controllerSelectionReferenceClient; - private final Client<VnfVfmoduleCvnfcConfigurationCustomization> vnfVfmoduleCvnfcConfigurationCustomizationClient; - private final Client<PnfResource> pnfResourceClient; private final Client<PnfResourceCustomization> pnfResourceCustomizationClient; @@ -365,7 +363,6 @@ public class CatalogDbClient { cvnfcCustomizationClient = clientFactory.create(CvnfcCustomization.class); controllerSelectionReferenceClient = clientFactory.create(ControllerSelectionReference.class); externalServiceToInternalServiceClient = clientFactory.create(ExternalServiceToInternalService.class); - vnfVfmoduleCvnfcConfigurationCustomizationClient = clientFactory.create(VnfVfmoduleCvnfcConfigurationCustomization.class); pnfResourceClient = clientFactory.create(PnfResource.class); pnfResourceCustomizationClient = clientFactory.create(PnfResourceCustomization.class); } @@ -415,7 +412,6 @@ public class CatalogDbClient { cvnfcCustomizationClient = clientFactory.create(CvnfcCustomization.class); controllerSelectionReferenceClient = clientFactory.create(ControllerSelectionReference.class); externalServiceToInternalServiceClient = clientFactory.create(ExternalServiceToInternalService.class); - vnfVfmoduleCvnfcConfigurationCustomizationClient = clientFactory.create(VnfVfmoduleCvnfcConfigurationCustomization.class); pnfResourceClient = clientFactory.create(PnfResource.class); pnfResourceCustomizationClient = clientFactory.create(PnfResourceCustomization.class); } @@ -801,12 +797,26 @@ public class CatalogDbClient { .queryParam("VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID", vfModuleCustomizationUUID).build().toString())); } - public VnfVfmoduleCvnfcConfigurationCustomization getVnfVfmoduleCvnfcConfigurationCustomizationByVnfCustomizationUuidAndVfModuleCustomizationUuidAndCvnfcCustomizationUuid(String vnfCustomizationUuid, - String vfModuleCustomizationUuid, String cvnfcCustomizationUuid) { - return this.getSingleResource(vnfVfmoduleCvnfcConfigurationCustomizationClient, getUri(UriBuilder - .fromUri(endpoint + "/vnfVfmoduleCvnfcConfigurationCustomization/search/findOneByVnfResourceCustomizationAndVfModuleCustomizationAndCvnfcCustomization") - .queryParam("VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID", vnfCustomizationUuid) - .queryParam("VF_MODULE_MODEL_CUSTOMIZATION_UUID", vfModuleCustomizationUuid) - .queryParam("CVNFC_MODEL_CUSTOMIZATION_UUID", cvnfcCustomizationUuid).build().toString())); + public CvnfcCustomization getCvnfcCustomizationByCustomizationUUID(String cvnfcCustomizationUuid){ + return this.getSingleResource(cvnfcCustomizationClient,getUri(UriBuilder + .fromUri(endpoint + "/cvnfcCustomization/search/findOneByModelCustomizationUUID").queryParam("modelCustomizationUuid", cvnfcCustomizationUuid) + .build().toString())); + } + + //fetch all VnfVfmoduleCvnfcConfigurationCustomization underneath a vnfc + //find the VnfVfmoduleCvnfcConfigurationCustomization that is related to our vnf and our vf-module, filter all others. + public VnfVfmoduleCvnfcConfigurationCustomization getVnfVfmoduleCvnfcConfigurationCustomizationByVnfCustomizationUuidAndVfModuleCustomizationUuidAndCvnfcCustomizationUuid( + String vnfCustomizationUuid, String vfModuleCustomizationUuid, String cvnfcCustomizationUuid) { + CvnfcCustomization cvnfc = getCvnfcCustomizationByCustomizationUUID(cvnfcCustomizationUuid); + if (cvnfc != null) { + for(VnfVfmoduleCvnfcConfigurationCustomization vnfVfModuleCvnfcCust: cvnfc.getVnfVfmoduleCvnfcConfigurationCustomization()){ + if(vnfVfModuleCvnfcCust.getVnfResourceCustomization().getModelCustomizationUUID().equals(vnfCustomizationUuid) && + vnfVfModuleCvnfcCust.getVfModuleCustomization().getModelCustomizationUUID().equals(vfModuleCustomizationUuid)){ + return vnfVfModuleCvnfcCust; + } + } + } + return null; + } } diff --git a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfVfmoduleCvnfcConfigurationCustomizationRepository.java b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfVfmoduleCvnfcConfigurationCustomizationRepository.java index aad75a15be..8664c1e2bc 100644 --- a/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfVfmoduleCvnfcConfigurationCustomizationRepository.java +++ b/mso-catalog-db/src/main/java/org/onap/so/db/catalog/data/repository/VnfVfmoduleCvnfcConfigurationCustomizationRepository.java @@ -20,21 +20,11 @@ package org.onap.so.db.catalog.data.repository; -import java.util.List; - import org.onap.so.db.catalog.beans.VnfVfmoduleCvnfcConfigurationCustomization; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(collectionResourceRel = "vnfVfmoduleCvnfcConfigurationCustomization", path = "vnfVfmoduleCvnfcConfigurationCustomization") public interface VnfVfmoduleCvnfcConfigurationCustomizationRepository extends JpaRepository<VnfVfmoduleCvnfcConfigurationCustomization, Integer> { - List<VnfVfmoduleCvnfcConfigurationCustomization> findByModelCustomizationUUID(String modelCustomizationUUID); - - @Query(value = "SELECT * FROM vnf_vfmodule_cvnfc_configuration_customization WHERE VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID = ?1 AND VF_MODULE_MODEL_CUSTOMIZATION_UUID = ?2 AND CVNFC_MODEL_CUSTOMIZATION_UUID = ?3", nativeQuery = true) - VnfVfmoduleCvnfcConfigurationCustomization findOneByVnfResourceCustomizationAndVfModuleCustomizationAndCvnfcCustomization ( - @Param("VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID") String vnfResourceCustomizationUuid, - @Param("VF_MODULE_MODEL_CUSTOMIZATION_UUID") String vfModuleCustomizationUuid, - @Param("CVNFC_MODEL_CUSTOMIZATION_UUID") String cvnfcCustomizationUuid); + }
\ No newline at end of file diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java index 8de5366ff3..4b6598427e 100644 --- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java +++ b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/CvnfcCustomizationRepositoryTest.java @@ -309,6 +309,8 @@ public class CvnfcCustomizationRepositoryTest extends BaseTest { Set<VnfVfmoduleCvnfcConfigurationCustomization> vnfVfmoduleCvnfcConfigurationCustomizationSet = new HashSet<VnfVfmoduleCvnfcConfigurationCustomization>(); vnfVfmoduleCvnfcConfigurationCustomizationSet.add(vnfVfmoduleCvnfcConfigurationCustomization); cvnfcCustomization.setVnfVfmoduleCvnfcConfigurationCustomization(vnfVfmoduleCvnfcConfigurationCustomizationSet); + vfModuleCustomization.setVnfVfmoduleCvnfcConfigurationCustomization(vnfVfmoduleCvnfcConfigurationCustomizationSet); + vnfResourceCustomization.setVnfVfmoduleCvnfcConfigurationCustomization(vnfVfmoduleCvnfcConfigurationCustomizationSet); cvnfcCustomizationRepository.save(cvnfcCustomization); diff --git a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfVfmoduleCvnfcConfigurationCustomizationRepositoryTest.java b/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfVfmoduleCvnfcConfigurationCustomizationRepositoryTest.java deleted file mode 100644 index a953fc8a3c..0000000000 --- a/mso-catalog-db/src/test/java/org/onap/so/db/catalog/data/repository/VnfVfmoduleCvnfcConfigurationCustomizationRepositoryTest.java +++ /dev/null @@ -1,133 +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.db.catalog.data.repository; - -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.onap.so.db.catalog.BaseTest; -import org.onap.so.db.catalog.beans.ConfigurationResource; -import org.onap.so.db.catalog.beans.CvnfcCustomization; -import org.onap.so.db.catalog.beans.VfModule; -import org.onap.so.db.catalog.beans.VfModuleCustomization; -import org.onap.so.db.catalog.beans.VnfResource; -import org.onap.so.db.catalog.beans.VnfResourceCustomization; -import org.onap.so.db.catalog.beans.VnfVfmoduleCvnfcConfigurationCustomization; -import org.onap.so.db.catalog.beans.VnfcCustomization; -import org.onap.so.db.catalog.exceptions.NoEntityFoundException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.CollectionUtils; - -public class VnfVfmoduleCvnfcConfigurationCustomizationRepositoryTest extends BaseTest { - @Autowired - private VnfVfmoduleCvnfcConfigurationCustomizationRepository vnfVfmoduleCvnfcConfigurationCustomizationRepository; - @Autowired - private CvnfcCustomizationRepository cvnfcCustomizationRepository; - - @Test - public void findAllTest() throws Exception { - List<VnfVfmoduleCvnfcConfigurationCustomization> vnfVfmoduleCvnfcConfigurationCustomizationList = vnfVfmoduleCvnfcConfigurationCustomizationRepository.findAll(); - Assert.assertFalse(CollectionUtils.isEmpty(vnfVfmoduleCvnfcConfigurationCustomizationList)); - - VnfVfmoduleCvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization = - vnfVfmoduleCvnfcConfigurationCustomizationRepository.findById(1).orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation")); - - - Assert.assertTrue(vnfVfmoduleCvnfcConfigurationCustomization.getConfigurationFunction().equalsIgnoreCase("testConfigurationFunction")); - } - - @Test - @Transactional - public void createAndGetTest() throws Exception { - - VnfVfmoduleCvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization = new VnfVfmoduleCvnfcConfigurationCustomization(); - vnfVfmoduleCvnfcConfigurationCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459"); - vnfVfmoduleCvnfcConfigurationCustomization.setModelInstanceName("testModelInstanceName"); - vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationType("testConfigurationType"); - vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationRole("testConfigurationRole"); - vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationFunction("testConfigurationFunction"); - vnfVfmoduleCvnfcConfigurationCustomization.setPolicyName("testPolicyName"); - - ConfigurationResource configurationResource = new ConfigurationResource(); - configurationResource.setModelUUID("98b42780-9f13-11e8-98d0-529269fb1459"); - configurationResource.setModelInvariantUUID("c9338d1a-9f13-11e8-98d0-529269fb1459"); - configurationResource.setModelVersion("testModelVertsion"); - configurationResource.setModelName("testModelName"); - configurationResource.setToscaNodeType("testToscaNodeType"); - configurationResource.setDescription("testConfigurationDescription"); - vnfVfmoduleCvnfcConfigurationCustomization.setConfigurationResource(configurationResource); - - CvnfcCustomization cvnfcCustomization = setUpCvnfcCustomization(); - cvnfcCustomization.setModelCustomizationUUID("0c3a8b76-3f5b-11e9-b210-d663bd873d93"); - - VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); - vfModuleCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459"); - - VfModule vFModule = setUpVfModule(); - VnfResource vnfResource = setUpVnfResource(); - - vFModule.setVnfResources(vnfResource); - vfModuleCustomization.setVfModule(vFModule); - cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization); - - VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization(); - vnfResourceCustomization.setModelCustomizationUUID("cf9f6efc-9f14-11e8-98d0-529269fb1459"); - vnfResourceCustomization.setModelInstanceName("testModelInstanceName"); - - List<VnfResourceCustomization> vnfResourceCustomizations = new ArrayList(); - vnfResourceCustomizations.add(vnfResourceCustomization); - vnfResource.setVnfResourceCustomizations(vnfResourceCustomizations); - vnfResourceCustomization.setVnfResources(vnfResource); - - cvnfcCustomization.setVnfResourceCustomization(vnfResourceCustomization); - - VnfcCustomization vnfcCustomization = setUpVnfcCustomization(); - vnfcCustomization.setModelCustomizationUUID("0aa015ea-9ff3-11e8-98d0-529269fb1459"); - cvnfcCustomization.setVnfcCustomization(vnfcCustomization); - - cvnfcCustomizationRepository.save(cvnfcCustomization); - - vnfVfmoduleCvnfcConfigurationCustomization.setCvnfcCustomization(cvnfcCustomization); - vnfVfmoduleCvnfcConfigurationCustomization.setVfModuleCustomization(vfModuleCustomization); - vnfVfmoduleCvnfcConfigurationCustomization.setVnfResourceCustomization(vnfResourceCustomization); - - vnfVfmoduleCvnfcConfigurationCustomizationRepository.save(vnfVfmoduleCvnfcConfigurationCustomization); - - VnfVfmoduleCvnfcConfigurationCustomization foundVnfVfmoduleCvnfcConfigurationCustomization = - vnfVfmoduleCvnfcConfigurationCustomizationRepository.findById(1).orElseThrow(() -> new NoEntityFoundException("Cannot Find Operation")); - - - if(foundVnfVfmoduleCvnfcConfigurationCustomization == null) - fail("should not be null"); - - VnfVfmoduleCvnfcConfigurationCustomization foundOneVnfVfmoduleCvnfcConfigurationCustomization = - vnfVfmoduleCvnfcConfigurationCustomizationRepository.findOneByVnfResourceCustomizationAndVfModuleCustomizationAndCvnfcCustomization("cf9f6efc-9f14-11e8-98d0-529269fb1459", "cf9f6efc-9f14-11e8-98d0-529269fb1459", "0c3a8b76-3f5b-11e9-b210-d663bd873d93"); - - if(foundOneVnfVfmoduleCvnfcConfigurationCustomization == null) - fail("should not be null"); - Assert.assertTrue(foundOneVnfVfmoduleCvnfcConfigurationCustomization.getConfigurationFunction().equalsIgnoreCase("testConfigurationFunction")); - } -}
\ No newline at end of file diff --git a/mso-catalog-db/src/test/resources/data.sql b/mso-catalog-db/src/test/resources/data.sql index a59137d023..ffd126545d 100644 --- a/mso-catalog-db/src/test/resources/data.sql +++ b/mso-catalog-db/src/test/resources/data.sql @@ -736,9 +736,7 @@ VALUES ( '1', INSERT INTO vnf_vfmodule_cvnfc_configuration_customization (id, model_customization_uuid, - vnf_resource_cust_model_customization_uuid, - vf_module_model_customization_uuid, - cvnfc_model_customization_uuid, + CVNFC_CUSTOMIZATION_ID, model_instance_name, configuration_type, configuration_role, @@ -748,9 +746,7 @@ INSERT INTO vnf_vfmodule_cvnfc_configuration_customization configuration_model_uuid) VALUES ( '1', '7bcce658-9b37-11e8-98d0-529269fb1450', - '68dc9a92-214c-11e7-93ae-92361f002671', - 'cb82ffd8-252a-11e7-93ae-92361f002671', - '9bcce658-9b37-11e8-98d0-529269fb1459', + '1', 'testModelInstanceName', 'testConfigurationType', 'testConfigurationRole', diff --git a/mso-catalog-db/src/test/resources/logback-test.xml b/mso-catalog-db/src/test/resources/logback-test.xml index 0bf39bdad1..68e4fcf64d 100644 --- a/mso-catalog-db/src/test/resources/logback-test.xml +++ b/mso-catalog-db/src/test/resources/logback-test.xml @@ -39,9 +39,14 @@ <appender-ref ref="STDOUT" /> </logger> - <logger name="org.onap" level="${so.log.level:-DEBUG}" additivity="false"> + <logger name="org.onap" level="DEBUG" additivity="false"> <appender-ref ref="STDOUT" /> </logger> + + <logger name="org.hibernate" level="DEBUG" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + <root level="info"> <appender-ref ref="STDOUT" /> </root> diff --git a/mso-catalog-db/src/test/resources/schema.sql b/mso-catalog-db/src/test/resources/schema.sql index 6bd9baee80..d53d8925e2 100644 --- a/mso-catalog-db/src/test/resources/schema.sql +++ b/mso-catalog-db/src/test/resources/schema.sql @@ -893,61 +893,67 @@ AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = latin1; CREATE TABLE IF NOT EXISTS cvnfc_customization ( -`ID` INT(11) NOT NULL AUTO_INCREMENT, -`MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, -`MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, -`MODEL_UUID` VARCHAR(200) NOT NULL, -`MODEL_INVARIANT_UUID` VARCHAR(200) NOT NULL, -`MODEL_VERSION` VARCHAR(20) NOT NULL, -`MODEL_NAME` VARCHAR(200) NOT NULL, -`TOSCA_NODE_TYPE` VARCHAR(200) NOT NULL, -`DESCRIPTION` VARCHAR(1200) NULL DEFAULT NULL, -`NFC_FUNCTION` VARCHAR(200) NULL, -`NFC_NAMING_CODE` VARCHAR(200) NULL, -`CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, -`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, -`VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, -`VNFC_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, PRIMARY KEY (`ID`), INDEX `fk_cvnfc_customization__vf_module_customization1_idx` (`VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` ASC), INDEX `fk_cvnfc_customization__vnfc_customization1_idx` (`VNFC_CUST_MODEL_CUSTOMIZATION_UUID` ASC), INDEX `fk_cvnfc_customization__vnf_resource_customization1_idx` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC), UNIQUE INDEX `UK_cvnfc_customization` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC, `VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` ASC, `MODEL_CUSTOMIZATION_UUID` ASC), INDEX `fk_cvnfc_customization__vnf_vfmod_cvnfc_config_cust1_idx` (`MODEL_CUSTOMIZATION_UUID` ASC), CONSTRAINT `fk_cvnfc_customization__vf_module_customization1` FOREIGN KEY (`VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID`) REFERENCES `vf_module_customization` (`MODEL_CUSTOMIZATION_UUID`) ON -DELETE CASCADE ON -UPDATE CASCADE, CONSTRAINT `fk_cvnfc_customization__vnfc_customization1` FOREIGN KEY (`VNFC_CUST_MODEL_CUSTOMIZATION_UUID`) REFERENCES `vnfc_customization` (`MODEL_CUSTOMIZATION_UUID`) ON -DELETE CASCADE ON -UPDATE CASCADE, CONSTRAINT `fk_cvnfc_customization__vnf_resource_customization1` FOREIGN KEY (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID`) REFERENCES `vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) ON -DELETE CASCADE ON -UPDATE CASCADE) ENGINE = InnoDB AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = latin1; - + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + `MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, + `MODEL_UUID` VARCHAR(200) NOT NULL, + `MODEL_INVARIANT_UUID` VARCHAR(200) NOT NULL, + `MODEL_VERSION` VARCHAR(20) NOT NULL, + `MODEL_NAME` VARCHAR(200) NOT NULL, + `TOSCA_NODE_TYPE` VARCHAR(200) NOT NULL, + `DESCRIPTION` VARCHAR(1200) NULL DEFAULT NULL, + `NFC_FUNCTION` VARCHAR(200) NULL, + `NFC_NAMING_CODE` VARCHAR(200) NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + `VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + `VNFC_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + PRIMARY KEY (`ID`), + INDEX `fk_cvnfc_customization__vf_module_customization1_idx` ( + `VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` ASC + ), + INDEX `fk_cvnfc_customization__vnfc_customization1_idx` ( + `VNFC_CUST_MODEL_CUSTOMIZATION_UUID` ASC + ), + INDEX `fk_cvnfc_customization__vnf_resource_customization1_idx` ( + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC + ), + UNIQUE INDEX `UK_cvnfc_customization` ( + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC, + `VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` ASC, + `MODEL_CUSTOMIZATION_UUID` ASC + ), + INDEX `fk_cvnfc_customization__vnf_vfmod_cvnfc_config_cust1_idx` (`MODEL_CUSTOMIZATION_UUID` ASC), + CONSTRAINT `fk_cvnfc_customization__vf_module_customization1` FOREIGN KEY ( + `VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` + ) REFERENCES `vf_module_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_cvnfc_customization__vnfc_customization1` FOREIGN KEY ( + `VNFC_CUST_MODEL_CUSTOMIZATION_UUID` + ) REFERENCES `vnfc_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_cvnfc_customization__vnf_resource_customization1` FOREIGN KEY ( + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` + ) REFERENCES `vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = InnoDB AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = latin1; CREATE TABLE IF NOT EXISTS vnf_vfmodule_cvnfc_configuration_customization ( - `ID` INT(11) NOT NULL AUTO_INCREMENT, - `MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `VF_MODULE_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `CVNFC_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, - `CONFIGURATION_TYPE` VARCHAR(200) NULL, - `CONFIGURATION_ROLE` VARCHAR(200) NULL, - `CONFIGURATION_FUNCTION` VARCHAR(200) NULL, - `POLICY_NAME` VARCHAR(200) NULL, - `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - `CONFIGURATION_MODEL_UUID` VARCHAR(200) NOT NULL, - PRIMARY KEY (`ID`), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__configuration_idx` (`CONFIGURATION_MODEL_UUID` ASC), - UNIQUE INDEX `UK_vnf_vfmodule_cvnfc_configuration_customization` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC , `VF_MODULE_MODEL_CUSTOMIZATION_UUID` ASC , `CVNFC_MODEL_CUSTOMIZATION_UUID` ASC , `MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__cvnfc_cust1_idx` (`CVNFC_MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__vf_module_cust_idx` (`VF_MODULE_MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__vnf_res_cust_idx` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC), - CONSTRAINT `fk_vnf_vfmod_cvnfc_config_cust__configuration_resource` FOREIGN KEY (`CONFIGURATION_MODEL_UUID`) - REFERENCES `configuration` (`MODEL_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_cvnfc_configuration_customization__cvnfc_customization1` FOREIGN KEY (`CVNFC_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `cvnfc_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_vnf_configuration_cvnfc_customization__vf_module_customiza1` FOREIGN KEY (`VF_MODULE_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `vf_module_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_vfmodule_cvnfc_configuration_customization__vnf_resource_c1` FOREIGN KEY (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=INNODB AUTO_INCREMENT=20654 DEFAULT CHARACTER SET=LATIN1; + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, + `MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, + `CONFIGURATION_TYPE` VARCHAR(200) NULL, + `CONFIGURATION_ROLE` VARCHAR(200) NULL, + `CONFIGURATION_FUNCTION` VARCHAR(200) NULL, + `POLICY_NAME` VARCHAR(200) NULL, + `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + `CONFIGURATION_MODEL_UUID` VARCHAR(200) NOT NULL, + `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) DEFAULT NULL, + `VF_MODULE_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) DEFAULT NULL, + `CVNFC_CUSTOMIZATION_ID` INT(11) DEFAULT NULL, + PRIMARY KEY (`ID`), + INDEX `fk_vnf_vfmodule_cvnfc_config_cust__configuration_idx` (`CONFIGURATION_MODEL_UUID` ASC), + + CONSTRAINT `fk_vnf_vfmod_cvnfc_config_cust__configuration_resource` FOREIGN KEY (`CONFIGURATION_MODEL_UUID`) + REFERENCES `configuration` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE = INNODB AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = LATIN1; CREATE TABLE IF NOT EXISTS `pnf_resource` ( `ORCHESTRATION_MODE` varchar(20) NOT NULL DEFAULT 'HEAT', diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/BasicAuthorizationHttpRequestInterceptor.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/BasicAuthorizationHttpRequestInterceptor.java deleted file mode 100644 index 34afd825cb..0000000000 --- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/BasicAuthorizationHttpRequestInterceptor.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ -package org.onap.so.monitoring.configuration.rest; - -import java.io.IOException; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; - -/** - * @author waqas.ikram@ericsson.com - * - */ -public class BasicAuthorizationHttpRequestInterceptor implements ClientHttpRequestInterceptor { - - private final String authorization; - - public BasicAuthorizationHttpRequestInterceptor(final String authorization) { - this.authorization = authorization; - } - - @Override - public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, - final ClientHttpRequestExecution execution) throws IOException { - final HttpHeaders headers = request.getHeaders(); - headers.add("Authorization", authorization); - return execution.execute(request, body); - } -} diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/HttpServiceProviderConfiguration.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/HttpServiceProviderConfiguration.java index a590d7908f..11c4d1b4f4 100644 --- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/HttpServiceProviderConfiguration.java +++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/configuration/rest/HttpServiceProviderConfiguration.java @@ -19,17 +19,17 @@ */ package org.onap.so.monitoring.configuration.rest; -import static org.onap.so.monitoring.configuration.rest.RestTemplateConfiguration.CAMUNDA_REST_TEMPLATE; -import static org.onap.so.monitoring.configuration.rest.RestTemplateConfiguration.DATABASE_REST_TEMPLATE; +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; -import org.onap.so.monitoring.rest.service.HttpRestServiceProvider; -import org.onap.so.monitoring.rest.service.HttpRestServiceProviderImpl; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.configuration.rest.HttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProviderImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.web.client.RestTemplate; /** @@ -45,28 +45,22 @@ public class HttpServiceProviderConfiguration { @Bean @Qualifier(CAMUNDA_HTTP_REST_SERVICE_PROVIDER) public HttpRestServiceProvider camundaHttpRestServiceProvider( - @Qualifier(CAMUNDA_REST_TEMPLATE) @Autowired final RestTemplate restTemplate, + @Qualifier(CONFIGURABLE_REST_TEMPLATE) @Autowired final RestTemplate restTemplate, @Value(value = "${camunda.rest.api.auth:#{null}}") final String authorization) { - return getHttpRestServiceProvider(restTemplate, authorization); + return getHttpRestServiceProvider(restTemplate, new BasicHttpHeadersProvider(authorization)); } @Bean @Qualifier(DATABASE_HTTP_REST_SERVICE_PROVIDER) public HttpRestServiceProvider databaseHttpRestServiceProvider( - @Qualifier(DATABASE_REST_TEMPLATE) @Autowired final RestTemplate restTemplate, + @Qualifier(CONFIGURABLE_REST_TEMPLATE) @Autowired final RestTemplate restTemplate, @Value(value = "${mso.database.rest.api.auth:#{null}}") final String authorization) { - - return getHttpRestServiceProvider(restTemplate, authorization); + return getHttpRestServiceProvider(restTemplate, new BasicHttpHeadersProvider(authorization)); } private HttpRestServiceProvider getHttpRestServiceProvider(final RestTemplate restTemplate, - final String authorization) { - if (authorization != null && !authorization.isEmpty()) { - final ClientHttpRequestInterceptor authorizationInterceptor = - new BasicAuthorizationHttpRequestInterceptor(authorization); - restTemplate.getInterceptors().add(authorizationInterceptor); - } - return new HttpRestServiceProviderImpl(restTemplate); + final HttpHeadersProvider httpHeadersProvider) { + return new HttpRestServiceProviderImpl(restTemplate, httpHeadersProvider); } diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProviderImpl.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProviderImpl.java index 6be6367302..49e3d4f92f 100644 --- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProviderImpl.java +++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/db/service/DatabaseServiceProviderImpl.java @@ -30,7 +30,7 @@ import org.onap.so.monitoring.camunda.model.SoActiveInfraRequests; import org.onap.so.monitoring.configuration.database.DatabaseUrlProvider; import org.onap.so.monitoring.model.SoInfraRequest; import org.onap.so.monitoring.model.SoInfraRequestBuilder; -import org.onap.so.monitoring.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @@ -60,7 +60,7 @@ public class DatabaseServiceProviderImpl implements DatabaseServiceProvider { final String url = urlProvider.getSearchUrl(startTime, endTime, maxResult); final Optional<SoActiveInfraRequests[]> optionalRequests = - httpRestServiceProvider.postHttpRequest(filters, url, SoActiveInfraRequests[].class); + httpRestServiceProvider.post(filters, url, SoActiveInfraRequests[].class); if (optionalRequests.isPresent()) { return getSoInfraRequest(optionalRequests.get()); } diff --git a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderImpl.java b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderImpl.java index e6fbb68456..b7a439fc28 100644 --- a/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderImpl.java +++ b/so-monitoring/so-monitoring-handler/src/main/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderImpl.java @@ -35,15 +35,15 @@ import org.onap.so.monitoring.model.ProcessDefinitionDetail; import org.onap.so.monitoring.model.ProcessInstanceDetail; import org.onap.so.monitoring.model.ProcessInstanceIdDetail; import org.onap.so.monitoring.model.ProcessInstanceVariableDetail; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.google.common.base.Optional; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @author waqas.ikram@ericsson.com */ @@ -64,13 +64,12 @@ public class CamundaProcessDataServiceProviderImpl implements CamundaProcessData @Override public Optional<ProcessInstanceIdDetail> getProcessInstanceIdDetail(final String requestId) { final String url = urlProvider.getHistoryProcessInstanceUrl(requestId); - final Optional<ProcessInstance[]> processInstances = - httpRestServiceProvider.getHttpResponse(url, ProcessInstance[].class); + final Optional<ProcessInstance[]> processInstances = httpRestServiceProvider.get(url, ProcessInstance[].class); if (processInstances.isPresent()) { final ProcessInstance[] instances = processInstances.get(); - final String message = "found process instance for request id: " + requestId + - ", result size: " + instances.length; + final String message = + "found process instance for request id: " + requestId + ", result size: " + instances.length; LOGGER.debug(message); if (instances.length > 0) { @@ -79,8 +78,8 @@ public class CamundaProcessDataServiceProviderImpl implements CamundaProcessData if (processInstance.getSuperProcessInstanceId() == null) { return Optional.of(new ProcessInstanceIdDetail(processInstance.getId())); } - LOGGER.debug("found sub process instance id with super process instanceId: " + - processInstance.getSuperProcessInstanceId()); + LOGGER.debug("found sub process instance id with super process instanceId: " + + processInstance.getSuperProcessInstanceId()); } } } @@ -91,8 +90,7 @@ public class CamundaProcessDataServiceProviderImpl implements CamundaProcessData @Override public Optional<ProcessInstanceDetail> getSingleProcessInstanceDetail(final String processInstanceId) { final String url = urlProvider.getSingleProcessInstanceUrl(processInstanceId); - final Optional<ProcessInstance> processInstances = - httpRestServiceProvider.getHttpResponse(url, ProcessInstance.class); + final Optional<ProcessInstance> processInstances = httpRestServiceProvider.get(url, ProcessInstance.class); if (processInstances.isPresent()) { final ProcessInstance processInstance = processInstances.get(); @@ -111,8 +109,7 @@ public class CamundaProcessDataServiceProviderImpl implements CamundaProcessData @Override public Optional<ProcessDefinitionDetail> getProcessDefinition(final String processDefinitionId) { final String url = urlProvider.getProcessDefinitionUrl(processDefinitionId); - final Optional<ProcessDefinition> response = - httpRestServiceProvider.getHttpResponse(url, ProcessDefinition.class); + final Optional<ProcessDefinition> response = httpRestServiceProvider.get(url, ProcessDefinition.class); if (response.isPresent()) { final ProcessDefinition processDefinition = response.get(); final String xmlDefinition = processDefinition.getBpmn20Xml(); @@ -120,16 +117,14 @@ public class CamundaProcessDataServiceProviderImpl implements CamundaProcessData return Optional.of(new ProcessDefinitionDetail(processDefinitionId, xmlDefinition)); } } - LOGGER.error("Unable to find process definition for processDefinitionId: " + - processDefinitionId); + LOGGER.error("Unable to find process definition for processDefinitionId: " + processDefinitionId); return Optional.absent(); } @Override public List<ActivityInstanceDetail> getActivityInstance(final String processInstanceId) { final String url = urlProvider.getActivityInstanceUrl(processInstanceId); - final Optional<ActivityInstance[]> response = - httpRestServiceProvider.getHttpResponse(url, ActivityInstance[].class); + final Optional<ActivityInstance[]> response = httpRestServiceProvider.get(url, ActivityInstance[].class); if (response.isPresent()) { final ActivityInstance[] activityInstances = response.get(); final List<ActivityInstanceDetail> activityInstanceDetails = new ArrayList<>(activityInstances.length); @@ -148,8 +143,7 @@ public class CamundaProcessDataServiceProviderImpl implements CamundaProcessData } return activityInstanceDetails; } - LOGGER.error("Unable to find activity intance detail for process instance id: " + - processInstanceId); + LOGGER.error("Unable to find activity intance detail for process instance id: " + processInstanceId); return Collections.emptyList(); } @@ -157,7 +151,7 @@ public class CamundaProcessDataServiceProviderImpl implements CamundaProcessData public List<ProcessInstanceVariableDetail> getProcessInstanceVariable(final String processInstanceId) { final String url = urlProvider.getProcessInstanceVariablesUrl(processInstanceId); final Optional<ProcessInstanceVariable[]> response = - httpRestServiceProvider.getHttpResponse(url, ProcessInstanceVariable[].class); + httpRestServiceProvider.get(url, ProcessInstanceVariable[].class); if (response.isPresent()) { final ProcessInstanceVariable[] instanceVariables = response.get(); final List<ProcessInstanceVariableDetail> instanceVariableDetails = @@ -171,8 +165,7 @@ public class CamundaProcessDataServiceProviderImpl implements CamundaProcessData } return instanceVariableDetails; } - LOGGER.error("Unable to find process intance variable details for process instance id: " - + processInstanceId); + LOGGER.error("Unable to find process intance variable details for process instance id: " + processInstanceId); return Collections.emptyList(); } diff --git a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/HttpServiceProviderConfigurationTest.java b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/HttpServiceProviderConfigurationTest.java index 1b3e168c12..9df24c1921 100644 --- a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/HttpServiceProviderConfigurationTest.java +++ b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/configuration/HttpServiceProviderConfigurationTest.java @@ -23,7 +23,7 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.onap.so.monitoring.configuration.rest.HttpServiceProviderConfiguration; -import org.onap.so.monitoring.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; import org.springframework.web.client.RestTemplate; /** diff --git a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/db/api/DatabaseServiceProviderTest.java b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/db/api/DatabaseServiceProviderTest.java index 58666671a7..3a7ce18bf7 100644 --- a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/db/api/DatabaseServiceProviderTest.java +++ b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/db/api/DatabaseServiceProviderTest.java @@ -38,7 +38,7 @@ import org.onap.so.monitoring.configuration.database.DatabaseUrlProvider; import org.onap.so.monitoring.db.service.DatabaseServiceProvider; import org.onap.so.monitoring.db.service.DatabaseServiceProviderImpl; import org.onap.so.monitoring.model.SoInfraRequest; -import org.onap.so.monitoring.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; import com.google.common.base.Optional; @@ -57,8 +57,8 @@ public class DatabaseServiceProviderTest { final String searchUrl = URL_PROVIDER.getSearchUrl(0, 0, null); final Optional<SoActiveInfraRequests[]> response = Optional.of(new SoActiveInfraRequests[] {}); - when(mockServiceProvider.postHttpRequest(eq(Collections.emptyMap()), eq(searchUrl), - eq(SoActiveInfraRequests[].class))).thenReturn(response); + when(mockServiceProvider.post(eq(Collections.emptyMap()), eq(searchUrl), eq(SoActiveInfraRequests[].class))) + .thenReturn(response); final DatabaseServiceProvider objUnderTest = new DatabaseServiceProviderImpl(URL_PROVIDER, mockServiceProvider); @@ -71,8 +71,8 @@ public class DatabaseServiceProviderTest { final String searchUrl = URL_PROVIDER.getSearchUrl(0, 0, null); final Optional<SoActiveInfraRequests[]> response = Optional.absent(); - when(mockServiceProvider.postHttpRequest(eq(Collections.emptyMap()), eq(searchUrl), - eq(SoActiveInfraRequests[].class))).thenReturn(response); + when(mockServiceProvider.post(eq(Collections.emptyMap()), eq(searchUrl), eq(SoActiveInfraRequests[].class))) + .thenReturn(response); final DatabaseServiceProvider objUnderTest = new DatabaseServiceProviderImpl(URL_PROVIDER, mockServiceProvider); @@ -94,7 +94,7 @@ public class DatabaseServiceProviderTest { final HttpRestServiceProvider mockServiceProvider = mock(HttpRestServiceProvider.class); - when(mockServiceProvider.postHttpRequest(eq(filters), eq(searchUrl), eq(SoActiveInfraRequests[].class))) + when(mockServiceProvider.post(eq(filters), eq(searchUrl), eq(SoActiveInfraRequests[].class))) .thenReturn(response); final DatabaseServiceProvider objUnderTest = new DatabaseServiceProviderImpl(URL_PROVIDER, mockServiceProvider); diff --git a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderTest.java b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderTest.java index c3930df196..d21cf6d02b 100644 --- a/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderTest.java +++ b/so-monitoring/so-monitoring-handler/src/test/java/org/onap/so/monitoring/rest/service/CamundaProcessDataServiceProviderTest.java @@ -38,6 +38,7 @@ import org.onap.so.monitoring.model.ActivityInstanceDetail; import org.onap.so.monitoring.model.ProcessDefinitionDetail; import org.onap.so.monitoring.model.ProcessInstanceIdDetail; import org.onap.so.monitoring.model.ProcessInstanceVariableDetail; +import org.onap.so.rest.service.HttpRestServiceProvider; import com.google.common.base.Optional; @@ -65,7 +66,7 @@ public class CamundaProcessDataServiceProviderTest { public void test_GetProcessInstanceDetail_EmptyResponse() { final Optional<ProcessInstance[]> response = Optional.<ProcessInstance[]>absent(); final String url = CAMUNDA_REST_API_URL + DEFAULT + "/history/process-instance?variables=requestId_eq_" + ID; - when(httpRestServiceProvider.getHttpResponse(url, ProcessInstance[].class)).thenReturn(response); + when(httpRestServiceProvider.get(url, ProcessInstance[].class)).thenReturn(response); final CamundaProcessDataServiceProvider objUnderTest = new CamundaProcessDataServiceProviderImpl(camundaRestUrlProvider, httpRestServiceProvider); @@ -77,7 +78,7 @@ public class CamundaProcessDataServiceProviderTest { public void test_GetProcessInstanceDetail_NonEmptyResponseWithSuperProcessIdNull() { final Optional<ProcessInstance[]> response = Optional.of(getProcessInstance()); final String url = CAMUNDA_REST_API_URL + DEFAULT + "/history/process-instance?variables=requestId_eq_" + ID; - when(httpRestServiceProvider.getHttpResponse(url, ProcessInstance[].class)).thenReturn(response); + when(httpRestServiceProvider.get(url, ProcessInstance[].class)).thenReturn(response); final CamundaProcessDataServiceProvider objUnderTest = new CamundaProcessDataServiceProviderImpl(camundaRestUrlProvider, httpRestServiceProvider); @@ -92,7 +93,7 @@ public class CamundaProcessDataServiceProviderTest { public void test_GetProcessInstanceDetail_NonEmptyResponseWithSuperProcessIdNotNull() { final Optional<ProcessInstance[]> response = Optional.of(getProcessInstance(SUPER_PROCESS_ID)); final String url = CAMUNDA_REST_API_URL + DEFAULT + "/history/process-instance?variables=requestId_eq_" + ID; - when(httpRestServiceProvider.getHttpResponse(url, ProcessInstance[].class)).thenReturn(response); + when(httpRestServiceProvider.get(url, ProcessInstance[].class)).thenReturn(response); final CamundaProcessDataServiceProvider objUnderTest = new CamundaProcessDataServiceProviderImpl(camundaRestUrlProvider, httpRestServiceProvider); @@ -105,7 +106,7 @@ public class CamundaProcessDataServiceProviderTest { public void test_GetProcessDefinition_EmptyResponse() { final Optional<ProcessDefinition> response = Optional.<ProcessDefinition>absent(); final String url = CAMUNDA_REST_API_URL + DEFAULT + "/process-definition/" + ID + "/xml"; - when(httpRestServiceProvider.getHttpResponse(url, ProcessDefinition.class)).thenReturn(response); + when(httpRestServiceProvider.get(url, ProcessDefinition.class)).thenReturn(response); final CamundaProcessDataServiceProvider objUnderTest = new CamundaProcessDataServiceProviderImpl(camundaRestUrlProvider, httpRestServiceProvider); @@ -117,7 +118,7 @@ public class CamundaProcessDataServiceProviderTest { public void test_GetProcessDefinition_NonEmptyResponse() { final Optional<ProcessDefinition> response = getProcessDefinition(); final String url = CAMUNDA_REST_API_URL + DEFAULT + "/process-definition/" + PROCESS_ID + "/xml"; - when(httpRestServiceProvider.getHttpResponse(url, ProcessDefinition.class)).thenReturn(response); + when(httpRestServiceProvider.get(url, ProcessDefinition.class)).thenReturn(response); final CamundaProcessDataServiceProvider objUnderTest = new CamundaProcessDataServiceProviderImpl(camundaRestUrlProvider, httpRestServiceProvider); @@ -132,7 +133,7 @@ public class CamundaProcessDataServiceProviderTest { final Optional<ActivityInstance[]> response = Optional.<ActivityInstance[]>absent(); final String url = CAMUNDA_REST_API_URL + DEFAULT + "/history/activity-instance?processInstanceId=" + PROCESS_ID + "&sortBy=startTime&sortOrder=asc"; - when(httpRestServiceProvider.getHttpResponse(url, ActivityInstance[].class)).thenReturn(response); + when(httpRestServiceProvider.get(url, ActivityInstance[].class)).thenReturn(response); final CamundaProcessDataServiceProvider objUnderTest = new CamundaProcessDataServiceProviderImpl(camundaRestUrlProvider, httpRestServiceProvider); @@ -146,7 +147,7 @@ public class CamundaProcessDataServiceProviderTest { final Optional<ActivityInstance[]> response = getActivityInstance(); final String url = CAMUNDA_REST_API_URL + DEFAULT + "/history/activity-instance?processInstanceId=" + PROCESS_ID + "&sortBy=startTime&sortOrder=asc"; - when(httpRestServiceProvider.getHttpResponse(url, ActivityInstance[].class)).thenReturn(response); + when(httpRestServiceProvider.get(url, ActivityInstance[].class)).thenReturn(response); final CamundaProcessDataServiceProvider objUnderTest = new CamundaProcessDataServiceProviderImpl(camundaRestUrlProvider, httpRestServiceProvider); @@ -164,7 +165,7 @@ public class CamundaProcessDataServiceProviderTest { final Optional<ProcessInstanceVariable[]> response = Optional.<ProcessInstanceVariable[]>absent(); final String url = CAMUNDA_REST_API_URL + DEFAULT + "/history/variable-instance?processInstanceId=" + PROCESS_ID; - when(httpRestServiceProvider.getHttpResponse(url, ProcessInstanceVariable[].class)).thenReturn(response); + when(httpRestServiceProvider.get(url, ProcessInstanceVariable[].class)).thenReturn(response); final CamundaProcessDataServiceProvider objUnderTest = new CamundaProcessDataServiceProviderImpl(camundaRestUrlProvider, httpRestServiceProvider); @@ -178,7 +179,7 @@ public class CamundaProcessDataServiceProviderTest { final Optional<ProcessInstanceVariable[]> response = getProcessInstanceVariable(); final String url = CAMUNDA_REST_API_URL + DEFAULT + "/history/variable-instance?processInstanceId=" + PROCESS_ID; - when(httpRestServiceProvider.getHttpResponse(url, ProcessInstanceVariable[].class)).thenReturn(response); + when(httpRestServiceProvider.get(url, ProcessInstanceVariable[].class)).thenReturn(response); final CamundaProcessDataServiceProvider objUnderTest = new CamundaProcessDataServiceProviderImpl(camundaRestUrlProvider, httpRestServiceProvider); diff --git a/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java b/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java index 155b4e65a4..d2fa08fdfd 100644 --- a/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java +++ b/so-monitoring/so-monitoring-service/src/main/java/org/onap/so/monitoring/rest/api/SoMonitoringController.java @@ -33,8 +33,6 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.onap.so.monitoring.db.service.DatabaseServiceProvider; -import org.onap.so.monitoring.exception.InvalidRestRequestException; -import org.onap.so.monitoring.exception.RestProcessingException; import org.onap.so.monitoring.model.ActivityInstanceDetail; import org.onap.so.monitoring.model.ProcessDefinitionDetail; import org.onap.so.monitoring.model.ProcessInstanceDetail; @@ -42,14 +40,15 @@ import org.onap.so.monitoring.model.ProcessInstanceIdDetail; import org.onap.so.monitoring.model.ProcessInstanceVariableDetail; import org.onap.so.monitoring.model.SoInfraRequest; import org.onap.so.monitoring.rest.service.CamundaProcessDataServiceProvider; +import org.onap.so.rest.exceptions.InvalidRestRequestException; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.google.common.base.Optional; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @author waqas.ikram@ericsson.com */ @@ -134,8 +133,7 @@ public class SoMonitoringController { @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getProcessDefinitionXml(final @PathParam("processDefinitionId") String processDefinitionId) { if (processDefinitionId == null || processDefinitionId.isEmpty()) { - return Response.status(Status.BAD_REQUEST).entity("Invalid process definition id: " + - processDefinitionId) + return Response.status(Status.BAD_REQUEST).entity("Invalid process definition id: " + processDefinitionId) .build(); } try { @@ -145,18 +143,15 @@ public class SoMonitoringController { final ProcessDefinitionDetail definitionDetail = response.get(); return Response.status(Status.OK).entity(definitionDetail).build(); } - LOGGER.error("Unable to find process definition xml for processDefinitionId: " + - processDefinitionId); + LOGGER.error("Unable to find process definition xml for processDefinitionId: " + processDefinitionId); return Response.status(Status.NO_CONTENT).build(); } catch (final InvalidRestRequestException extensions) { final String message = - "Unable to find process definition xml for processDefinitionId: {}" + - processDefinitionId; + "Unable to find process definition xml for processDefinitionId: {}" + processDefinitionId; return Response.status(Status.BAD_REQUEST).entity(message).build(); } catch (final RestProcessingException restProcessingException) { - final String message = "Unable to get process definition xml for id: " + - processDefinitionId; + final String message = "Unable to get process definition xml for id: " + processDefinitionId; LOGGER.error(message); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(message).build(); } @@ -175,13 +170,11 @@ public class SoMonitoringController { camundaProcessDataServiceProvider.getActivityInstance(processInstanceId); return Response.status(Status.OK).entity(activityInstanceDetails).build(); } catch (final InvalidRestRequestException extensions) { - final String message = "Unable to find activity instance for processInstanceId: " + - processInstanceId; + final String message = "Unable to find activity instance for processInstanceId: " + processInstanceId; LOGGER.error(message); return Response.status(Status.BAD_REQUEST).entity(message).build(); } catch (final RestProcessingException restProcessingException) { - final String message = "Unable to get activity instance detail for id: " + - processInstanceId; + final String message = "Unable to get activity instance detail for id: " + processInstanceId; LOGGER.error(message); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(message).build(); } @@ -201,13 +194,11 @@ public class SoMonitoringController { return Response.status(Status.OK).entity(processInstanceVariable).build(); } catch (final InvalidRestRequestException extensions) { final String message = - "Unable to find process instance variables for processInstanceId: " + - processInstanceId; + "Unable to find process instance variables for processInstanceId: " + processInstanceId; LOGGER.error(message); return Response.status(Status.BAD_REQUEST).entity(message).build(); } catch (final RestProcessingException restProcessingException) { - final String message = "Unable to get process instance variables for id: " + - processInstanceId; + final String message = "Unable to get process instance variables for id: " + processInstanceId; LOGGER.error(message); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(message).build(); } @@ -230,13 +221,13 @@ public class SoMonitoringController { return Response.status(Status.OK).entity(requests).build(); } catch (final InvalidRestRequestException extensions) { - final String message = "Unable to search request for filters: " + filters + ", from: " + - startTime + ", to: " + endTime + ", maxResult: " + maxResult; + final String message = "Unable to search request for filters: " + filters + ", from: " + startTime + + ", to: " + endTime + ", maxResult: " + maxResult; LOGGER.error(message); return Response.status(Status.BAD_REQUEST).entity(message).build(); } catch (final RestProcessingException restProcessingException) { - final String message = "Unable to search request for filters: " + filters + ", from: " + - startTime + ", to: " + endTime + ", maxResult: " + maxResult; + final String message = "Unable to search request for filters: " + filters + ", from: " + startTime + + ", to: " + endTime + ", maxResult: " + maxResult; LOGGER.error(message); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(message).build(); } diff --git a/so-monitoring/so-monitoring-service/src/test/java/org/onap/so/monitoring/rest/api/SoMonitoringControllerTest.java b/so-monitoring/so-monitoring-service/src/test/java/org/onap/so/monitoring/rest/api/SoMonitoringControllerTest.java index 3ca184ebaa..2c4d036397 100644 --- a/so-monitoring/so-monitoring-service/src/test/java/org/onap/so/monitoring/rest/api/SoMonitoringControllerTest.java +++ b/so-monitoring/so-monitoring-service/src/test/java/org/onap/so/monitoring/rest/api/SoMonitoringControllerTest.java @@ -22,8 +22,8 @@ package org.onap.so.monitoring.rest.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.onap.so.monitoring.configuration.rest.RestTemplateConfiguration.CAMUNDA_REST_TEMPLATE; -import static org.onap.so.monitoring.configuration.rest.RestTemplateConfiguration.DATABASE_REST_TEMPLATE; +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.onap.so.configuration.rest.BasicHttpHeadersProvider.AUTHORIZATION_HEADER; import static org.onap.so.monitoring.rest.api.Constants.ACTIVITY_INSTANCE_RESPONSE_JSON_FILE; import static org.onap.so.monitoring.rest.api.Constants.EMPTY_ARRAY_RESPONSE; import static org.onap.so.monitoring.rest.api.Constants.EMPTY_STRING; @@ -37,6 +37,7 @@ import static org.onap.so.monitoring.rest.api.Constants.PROCRESS_DEF_ID; import static org.onap.so.monitoring.rest.api.Constants.SEARCH_RESULT_RESPONSE_JSON_FILE; import static org.onap.so.monitoring.rest.api.Constants.SINGLE_PROCCESS_INSTANCE_RESPONSE_JSON_FILE; import static org.onap.so.monitoring.rest.api.Constants.START_TIME_IN_MS; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.header; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withBadRequest; import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; @@ -81,14 +82,14 @@ import org.springframework.web.client.RestTemplate; @ActiveProfiles("test") @SpringBootTest public class SoMonitoringControllerTest { + private static final String CAMUNDA_BASIC_AUTH = + "Basic YWRtaW46S3A4Yko0U1hzek0wV1hsaGFrM2VIbGNzZTJnQXc4NHZhb0dHbUp2VXkyVQ=="; - @Autowired - @Qualifier(CAMUNDA_REST_TEMPLATE) - private RestTemplate restTemplate; + private static final String DATABASE_BASIC_AUTH = "Basic YnBlbDpwYXNzd29yZDEk"; @Autowired - @Qualifier(DATABASE_REST_TEMPLATE) - private RestTemplate dataBaseRestTemplate; + @Qualifier(CONFIGURABLE_REST_TEMPLATE) + private RestTemplate restTemplate; @Autowired private CamundaRestUrlProvider urlProvider; @@ -96,23 +97,22 @@ public class SoMonitoringControllerTest { @Autowired private DatabaseUrlProvider databaseUrlProvider; - private MockRestServiceServer camundaMockServer; + private MockRestServiceServer mockRestServiceServer; - private MockRestServiceServer databaseMockServer; @Autowired private SoMonitoringController objUnderTest; @Before public void setUp() throws Exception { - camundaMockServer = MockRestServiceServer.bindTo(restTemplate).build(); - databaseMockServer = MockRestServiceServer.bindTo(dataBaseRestTemplate).build(); + mockRestServiceServer = MockRestServiceServer.bindTo(restTemplate).build(); } @Test public void test_GetProcessInstance_SuccessResponseWithDataFromCamunda() throws Exception { final String jsonString = getJsonResponse(PROCCESS_INSTANCE_RESPONSE_JSON_FILE); - this.camundaMockServer.expect(requestTo(urlProvider.getHistoryProcessInstanceUrl(ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getHistoryProcessInstanceUrl(ID))) + .andExpect(header(AUTHORIZATION_HEADER, CAMUNDA_BASIC_AUTH)) .andRespond(withSuccess(jsonString, MediaType.APPLICATION_JSON)); final Response response = objUnderTest.getProcessInstanceId(ID); @@ -125,7 +125,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetProcessInstance_SuccessResponseWithEmptyDataFromCamunda() throws Exception { final String jsonString = EMPTY_ARRAY_RESPONSE; - this.camundaMockServer.expect(requestTo(urlProvider.getHistoryProcessInstanceUrl(ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getHistoryProcessInstanceUrl(ID))) .andRespond(withSuccess(jsonString, MediaType.APPLICATION_JSON)); final Response response = objUnderTest.getProcessInstanceId(ID); @@ -135,7 +135,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetProcessInstance_FailureResponseWithEmptyDataFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getHistoryProcessInstanceUrl(ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getHistoryProcessInstanceUrl(ID))) .andRespond(withBadRequest()); final Response response = objUnderTest.getProcessInstanceId(ID); @@ -144,7 +144,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetProcessInstance_UnauthorizedRequestFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getHistoryProcessInstanceUrl(ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getHistoryProcessInstanceUrl(ID))) .andRespond(withUnauthorizedRequest()); final Response response = objUnderTest.getProcessInstanceId(ID); @@ -155,7 +155,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetSinlgeProcessInstance_SuccessResponseWithDataFromCamunda() throws Exception { final String jsonString = getJsonResponse(SINGLE_PROCCESS_INSTANCE_RESPONSE_JSON_FILE); - this.camundaMockServer.expect(requestTo(urlProvider.getSingleProcessInstanceUrl(PROCESS_INSTACE_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getSingleProcessInstanceUrl(PROCESS_INSTACE_ID))) .andRespond(withSuccess(jsonString, MediaType.APPLICATION_JSON)); final Response response = objUnderTest.getSingleProcessInstance(PROCESS_INSTACE_ID); @@ -171,7 +171,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetSingleProcessInstance_WithBadRequestResponseFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getSingleProcessInstanceUrl(PROCESS_INSTACE_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getSingleProcessInstanceUrl(PROCESS_INSTACE_ID))) .andRespond(withBadRequest()); final Response response = objUnderTest.getSingleProcessInstance(PROCESS_INSTACE_ID); @@ -181,7 +181,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetSingleProcessInstance_WithUnauthorizedRequestResponseFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getSingleProcessInstanceUrl(PROCESS_INSTACE_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getSingleProcessInstanceUrl(PROCESS_INSTACE_ID))) .andRespond(withUnauthorizedRequest()); final Response response = objUnderTest.getSingleProcessInstance(PROCESS_INSTACE_ID); @@ -216,7 +216,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetProcessDefinitionXml_SuccessResponseWithDataFromCamunda() throws Exception { final String jsonString = getJsonResponse(PROCESS_DEF_RESPONSE_JSON_FILE); - this.camundaMockServer.expect(requestTo(urlProvider.getProcessDefinitionUrl(PROCRESS_DEF_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getProcessDefinitionUrl(PROCRESS_DEF_ID))) .andRespond(withSuccess(jsonString, MediaType.APPLICATION_JSON)); final Response response = objUnderTest.getProcessDefinitionXml(PROCRESS_DEF_ID); @@ -228,7 +228,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetProcessDefinitionXml_BadRequestResponseFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getProcessDefinitionUrl(PROCRESS_DEF_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getProcessDefinitionUrl(PROCRESS_DEF_ID))) .andRespond(withBadRequest()); final Response response = objUnderTest.getProcessDefinitionXml(PROCRESS_DEF_ID); @@ -238,7 +238,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetProcessDefinitionXml_UnauthorizedRequestFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getProcessDefinitionUrl(PROCRESS_DEF_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getProcessDefinitionUrl(PROCRESS_DEF_ID))) .andRespond(withUnauthorizedRequest()); final Response response = objUnderTest.getProcessDefinitionXml(PROCRESS_DEF_ID); @@ -260,7 +260,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetActivityInstanceDetail_SuccessResponseWithDataFromCamunda() throws Exception { final String jsonString = getJsonResponse(ACTIVITY_INSTANCE_RESPONSE_JSON_FILE); - this.camundaMockServer.expect(requestTo(urlProvider.getActivityInstanceUrl(PROCESS_INSTACE_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getActivityInstanceUrl(PROCESS_INSTACE_ID))) .andRespond(withSuccess(jsonString, MediaType.APPLICATION_JSON)); final Response response = objUnderTest.getActivityInstanceDetail(PROCESS_INSTACE_ID); @@ -287,7 +287,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetActivityInstanceDetail_SuccessResponseWithEmptyDataFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getActivityInstanceUrl(PROCESS_INSTACE_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getActivityInstanceUrl(PROCESS_INSTACE_ID))) .andRespond(withSuccess(EMPTY_ARRAY_RESPONSE, MediaType.APPLICATION_JSON)); final Response response = objUnderTest.getActivityInstanceDetail(PROCESS_INSTACE_ID); @@ -297,7 +297,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetActivityInstanceDetail_UnauthorizedRequestFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getActivityInstanceUrl(PROCESS_INSTACE_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getActivityInstanceUrl(PROCESS_INSTACE_ID))) .andRespond(withUnauthorizedRequest()); final Response response = objUnderTest.getActivityInstanceDetail(PROCESS_INSTACE_ID); @@ -307,7 +307,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetActivityInstanceDetail_BadRequestFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getActivityInstanceUrl(PROCESS_INSTACE_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getActivityInstanceUrl(PROCESS_INSTACE_ID))) .andRespond(withBadRequest()); final Response response = objUnderTest.getActivityInstanceDetail(PROCESS_INSTACE_ID); @@ -329,7 +329,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetProcessInstanceVariables_SuccessResponseWithDataFromCamunda() throws Exception { final String jsonString = getJsonResponse(PROCESS_INSTANCE_VARIABLES_RESPONSE_JSON_FILE); - this.camundaMockServer.expect(requestTo(urlProvider.getProcessInstanceVariablesUrl(PROCESS_INSTACE_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getProcessInstanceVariablesUrl(PROCESS_INSTACE_ID))) .andRespond(withSuccess(jsonString, MediaType.APPLICATION_JSON)); final Response response = objUnderTest.getProcessInstanceVariables(PROCESS_INSTACE_ID); @@ -347,7 +347,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetProcessInstanceVariables_SuccessResponseWithEmptyDataFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getProcessInstanceVariablesUrl(PROCESS_INSTACE_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getProcessInstanceVariablesUrl(PROCESS_INSTACE_ID))) .andRespond(withSuccess(EMPTY_ARRAY_RESPONSE, MediaType.APPLICATION_JSON)); final Response response = objUnderTest.getProcessInstanceVariables(PROCESS_INSTACE_ID); @@ -358,7 +358,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetProcessInstanceVariables_BadRequestFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getProcessInstanceVariablesUrl(PROCESS_INSTACE_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getProcessInstanceVariablesUrl(PROCESS_INSTACE_ID))) .andRespond(withBadRequest()); final Response response = objUnderTest.getProcessInstanceVariables(PROCESS_INSTACE_ID); @@ -369,7 +369,7 @@ public class SoMonitoringControllerTest { @Test public void test_GetProcessInstanceVariables_UnauthorizedRequestFromCamunda() throws Exception { - this.camundaMockServer.expect(requestTo(urlProvider.getProcessInstanceVariablesUrl(PROCESS_INSTACE_ID))) + this.mockRestServiceServer.expect(requestTo(urlProvider.getProcessInstanceVariablesUrl(PROCESS_INSTACE_ID))) .andRespond(withUnauthorizedRequest()); final Response response = objUnderTest.getProcessInstanceVariables(PROCESS_INSTACE_ID); @@ -396,8 +396,9 @@ public class SoMonitoringControllerTest { @Test public void test_GetInfraActiveRequests_SuccessResponseWithSoInfraRequestList() throws Exception { final String jsonString = getJsonResponse(SEARCH_RESULT_RESPONSE_JSON_FILE); - this.databaseMockServer + this.mockRestServiceServer .expect(requestTo(databaseUrlProvider.getSearchUrl(START_TIME_IN_MS, END_TIME_IN_MS, null))) + .andExpect(header(AUTHORIZATION_HEADER, DATABASE_BASIC_AUTH)) .andRespond(withSuccess(jsonString, MediaType.APPLICATION_JSON)); final Response response = |