diff options
Diffstat (limited to 'models-provider/src')
8 files changed, 725 insertions, 185 deletions
diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java index 970aa8fef..43f75d2a9 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java @@ -41,7 +41,7 @@ import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy; import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; -import org.onap.policy.models.tosca.legacy.provider.LegacyToscaProvider; +import org.onap.policy.models.tosca.legacy.provider.LegacyProvider; import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider; import org.slf4j.Logger; @@ -190,53 +190,53 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { @Override public LegacyOperationalPolicy getOperationalPolicy(@NonNull final String policyId) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().getOperationalPolicy(pfDao, policyId); + return new LegacyProvider().getOperationalPolicy(pfDao, policyId); } @Override public LegacyOperationalPolicy createOperationalPolicy( @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy); + return new LegacyProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy); } @Override public LegacyOperationalPolicy updateOperationalPolicy( @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy); + return new LegacyProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy); } @Override public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().deleteOperationalPolicy(pfDao, policyId); + return new LegacyProvider().deleteOperationalPolicy(pfDao, policyId); } @Override public LegacyGuardPolicy getGuardPolicy(@NonNull final String policyId) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().getGuardPolicy(pfDao, policyId); + return new LegacyProvider().getGuardPolicy(pfDao, policyId); } @Override public LegacyGuardPolicy createGuardPolicy(@NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().createGuardPolicy(pfDao, legacyGuardPolicy); + return new LegacyProvider().createGuardPolicy(pfDao, legacyGuardPolicy); } @Override public LegacyGuardPolicy updateGuardPolicy(@NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().updateGuardPolicy(pfDao, legacyGuardPolicy); + return new LegacyProvider().updateGuardPolicy(pfDao, legacyGuardPolicy); } @Override public LegacyGuardPolicy deleteGuardPolicy(@NonNull final String policyId) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().deleteGuardPolicy(pfDao, policyId); + return new LegacyProvider().deleteGuardPolicy(pfDao, policyId); } @Override diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java index d8750192c..8d833a53d 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,10 +24,8 @@ package org.onap.policy.models.provider.impl; import com.google.gson.Gson; import javax.ws.rs.core.Response; - import lombok.NonNull; - -import org.onap.policy.common.utils.resources.TextFileUtils; +import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; @@ -42,6 +41,7 @@ import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMes * This class provides a dummy implementation of the Policy Models Provider for the ONAP Policy Framework. * * @author Liam Fallon (liam.fallon@est.tech) + * @author Chenfei Gao (cgao@research.att.com) */ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { /** @@ -64,7 +64,7 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { @Override public ToscaServiceTemplate getPolicyTypes(@NonNull final PfConceptKey policyTypeKey) throws PfModelException { - return getDummyResponse("src/main/resources/dummyimpl/DummyToscaPolicyTypeGetResponse.json"); + return getDummyResponse("dummyimpl/DummyToscaPolicyTypeGetResponse.json"); } @Override @@ -81,12 +81,12 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { @Override public ToscaServiceTemplate deletePolicyTypes(@NonNull final PfConceptKey policyTypeKey) throws PfModelException { - return getDummyResponse("src/main/resources/dummyimpl/DummyToscaPolicyTypeDeleteResponse.json"); + return getDummyResponse("dummyimpl/DummyToscaPolicyTypeDeleteResponse.json"); } @Override public ToscaServiceTemplate getPolicies(@NonNull final PfConceptKey policyKey) throws PfModelException { - return getDummyResponse("src/main/resources/dummyimpl/DummyToscaPolicyGetResponse.json"); + return getDummyResponse("dummyimpl/DummyToscaPolicyGetResponse.json"); } @Override @@ -103,7 +103,7 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { @Override public ToscaServiceTemplate deletePolicies(@NonNull final PfConceptKey policyKey) throws PfModelException { - return getDummyResponse("src/main/resources/dummyimpl/DummyToscaPolicyDeleteResponse.json"); + return getDummyResponse("dummyimpl/DummyToscaPolicyDeleteResponse.json"); } @Override @@ -182,7 +182,10 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { ToscaServiceTemplate serviceTemplate; try { - serviceTemplate = gson.fromJson(TextFileUtils.getTextFileAsString(fileName), ToscaServiceTemplate.class); + serviceTemplate = gson.fromJson(ResourceUtils.getResourceAsString(fileName), ToscaServiceTemplate.class); + if (serviceTemplate == null) { + throw new PfModelException(Response.Status.INTERNAL_SERVER_ERROR, "error reading specified file"); + } } catch (Exception exc) { throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, "error serializing object", exc); } diff --git a/models-provider/src/main/resources/dummyimpl/DummyToscaPolicyTypeGetResponse.json b/models-provider/src/main/resources/dummyimpl/DummyToscaPolicyTypeGetResponse.json index 27de380c2..c28c2d2f2 100644 --- a/models-provider/src/main/resources/dummyimpl/DummyToscaPolicyTypeGetResponse.json +++ b/models-provider/src/main/resources/dummyimpl/DummyToscaPolicyTypeGetResponse.json @@ -1,48 +1,223 @@ { - "tosca_definitions_version": "tosca_simple_yaml_1_0_0", - "topology_template": { - "policies": [ - { - "onap.vcpe.tca": { - "type": "onap.policies.monitoring.cdap.tca.hi.lo.app", - "version": "1.0.0", - "metadata": { - "policy-id": "onap.vcpe.tca" - }, - "properties": { - "domain": "measurementsForVfScaling", - "metricsPerEventName": [ - { - "eventName": "Measurement_vGMUX", - "controlLoopSchemaType": "VNF", - "policyScope": "DCAE", - "policyName": "DCAE.Config_tca-hi-lo", - "policyVersion": "v0.0.1", - "thresholds": [ - { - "closedLoopControlName": "ControlLoop-vCPE-48f0c2c3-a172-4192-9ae3-052274181b6e", - "version": "1.0.2", - "fieldPath": "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value", - "thresholdValue": 0, - "direction": "EQUAL", - "severity": "MAJOR", - "closedLoopEventStatus": "ABATED" - }, - { - "closedLoopControlName": "ControlLoop-vCPE-48f0c2c3-a172-4192-9ae3-052274181b6e", - "version": "1.0.2", - "fieldPath": "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value", - "thresholdValue": 0, - "direction": "GREATER", - "severity": "CRITICAL", - "closedLoopEventStatus": "ONSET" - } - ] - } + "tosca_definitions_version": "tosca_simple_yaml_1_0_0", + "policy_types": [ + { + "onap.policies.Monitoring": { + "derived_from": "tosca.policies.Root", + "description": "a base policy type for all policies that governs monitoring provisioning" + } + }, + { + "onap.policy.monitoring.cdap.tca.hi.lo.app": { + "derived_from": "onap.policies.Monitoring", + "version": "1.0.0", + "properties": { + "tca_policy": { + "type": "map", + "description": "TCA Policy JSON", + "entry_schema": { + "type": "onap.datatypes.monitoring.tca_policy" + } + } + } + } + } + ], + "data_types": [ + { + "onap.datatypes.monitoring.metricsPerEventName": { + "derived_from": "tosca.datatypes.Root", + "properties": { + "controlLoopSchemaType": { + "type": "string", + "required": true, + "description": "Specifies Control Loop Schema Type for the event Name e.g. VNF, VM", + "constraints": [ + { + "valid_values": [ + "VM", + "VNF" + ] + } + ] + }, + "eventName": { + "type": "string", + "required": true, + "description": "Event name to which thresholds need to be applied" + }, + "policyName": { + "type": "string", + "required": true, + "description": "TCA Policy Scope Name" + }, + "policyScope": { + "type": "string", + "required": true, + "description": "TCA Policy Scope" + }, + "policyVersion": { + "type": "string", + "required": true, + "description": "TCA Policy Scope Version" + }, + "thresholds": { + "type": "list", + "required": true, + "description": "Thresholds associated with eventName", + "entry_schema": { + "type": "onap.datatypes.monitoring.thresholds" + } + } + } + } + }, + { + "onap.datatypes.monitoring.tca_policy": { + "derived_from": "tosca.datatypes.Root", + "properties": { + "domain": { + "type": "string", + "required": true, + "description": "Domain name to which TCA needs to be applied", + "default": "measurementsForVfScaling", + "constraints": [ + { + "equal": "measurementsForVfScaling" + } + ] + }, + "metricsPerEventName": { + "type": "list", + "required": true, + "description": "Contains eventName and threshold details that need to be applied to given eventName", + "entry_schema": { + "type": "onap.datatypes.monitoring.metricsPerEventName" + } + } + } + } + }, + { + "onap.datatypes.monitoring.thresholds": { + "derived_from": "tosca.datatypes.Root", + "properties": { + "closedLoopControlName": { + "type": "string", + "required": true, + "description": "Closed Loop Control Name associated with the threshold" + }, + "closedLoopEventStatus": { + "type": "string", + "required": true, + "description": "Closed Loop Event Status of the threshold", + "constraints": [ + { + "valid_values": [ + "ONSET", + "ABATED" + ] + } + ] + }, + "direction": { + "type": "string", + "required": true, + "description": "Direction of the threshold", + "constraints": [ + { + "valid_values": [ + "LESS", + "LESS_OR_EQUAL", + "GREATER", + "GREATER_OR_EQUAL", + "EQUAL" + ] + } + ] + }, + "fieldPath": { + "type": "string", + "required": true, + "description": "Json field Path as per CEF message which needs to be analyzed for TCA", + "constraints": [ + { + "valid_values": [ + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsAccumulated", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuIdle", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageInterrupt", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageNice", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSoftIrq", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSteal", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSystem", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuWait", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].percentUsage", + "$.event.measurementsForVfScalingFields.meanRequestLatency", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryBuffered", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryCached", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryConfigured", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryFree", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryUsed", + "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value" + ] + } + ] + }, + "severity": { + "type": "string", + "required": true, + "description": "Threshold Event Severity", + "constraints": [ + { + "valid_values": [ + "CRITICAL", + "MAJOR", + "MINOR", + "WARNING", + "NORMAL" ] - } - } + } + ] + }, + "thresholdValue": { + "type": "integer", + "required": true, + "description": "Threshold value for the field Path inside CEF message" + }, + "version": { + "type": "string", + "required": true, + "description": "Version number associated with the threshold" + } } - ] - } + } + } + ] }
\ No newline at end of file diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java index 498000a89..e4ecb9d1d 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java @@ -37,7 +37,6 @@ import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy; import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; -import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,7 +46,7 @@ import org.slf4j.LoggerFactory; * @author Liam Fallon (liam.fallon@est.tech) */ public class DatabasePolicyModelsProviderTest { - private static final Logger LOGGER = LoggerFactory.getLogger(SimpleToscaProvider.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DatabasePolicyModelsProviderTest.class); PolicyModelsProviderParameters parameters; @@ -317,10 +316,30 @@ public class DatabasePolicyModelsProviderTest { assertEquals("policy not found: NULL:0.0.0", npe.getMessage()); } - assertNull(databaseProvider.getOperationalPolicy("policy_id")); - assertNull(databaseProvider.createOperationalPolicy(new LegacyOperationalPolicy())); - assertNull(databaseProvider.updateOperationalPolicy(new LegacyOperationalPolicy())); - assertNull(databaseProvider.deleteOperationalPolicy("policy_id")); + try { + assertNull(databaseProvider.getOperationalPolicy("policy_id")); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("no policy found for policy ID: policy_id", npe.getMessage()); + } + try { + assertNull(databaseProvider.createOperationalPolicy(new LegacyOperationalPolicy())); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("name is marked @NonNull but is null", npe.getMessage()); + } + try { + assertNull(databaseProvider.updateOperationalPolicy(new LegacyOperationalPolicy())); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("no policy found for policy ID: null", npe.getMessage()); + } + try { + assertNull(databaseProvider.deleteOperationalPolicy("policy_id")); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("no policy found for policy ID: policy_id", npe.getMessage()); + } assertNull(databaseProvider.getGuardPolicy("policy_id")); assertNull(databaseProvider.createGuardPolicy(new LegacyGuardPolicy())); diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/MonitoringPolicyPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/MonitoringPolicyPersistenceTest.java deleted file mode 100644 index b26e762af..000000000 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/MonitoringPolicyPersistenceTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/*- - * ============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.policy.models.provider.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.google.gson.Gson; -import com.google.gson.JsonSyntaxException; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.utils.resources.ResourceUtils; -import org.onap.policy.models.base.PfConceptKey; -import org.onap.policy.models.base.PfValidationResult; -import org.onap.policy.models.dao.DaoParameters; -import org.onap.policy.models.dao.PfDao; -import org.onap.policy.models.dao.PfDaoFactory; -import org.onap.policy.models.dao.impl.DefaultPfDao; -import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; -import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; -import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Test persistence of monitoring policies to and from the database. - * - * @author Liam Fallon (liam.fallon@est.tech) - */ -public class MonitoringPolicyPersistenceTest { - // Logger for this class - private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPolicyPersistenceTest.class); - - private Gson gson; - - private Connection connection; - private PfDao pfDao; - - /** - * Set up the DAO towards the database. - * - * @throws Exception on database errors - */ - @Before - public void setupDao() throws Exception { - // Use the JDBC UI "jdbc:h2:mem:testdb" to test towards the h2 database - // Use the JDBC UI "jdbc:mariadb://localhost:3306/policy" to test towards a locally installed mariadb instance - connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "policy", "P01icY"); - - final DaoParameters daoParameters = new DaoParameters(); - daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); - - // Use the persistence unit ToscaConceptTest to test towards the h2 database - // Use the persistence unit ToscaConceptMariaDBTest to test towards a locally installed mariadb instance - daoParameters.setPersistenceUnit("ToscaConceptTest"); - - pfDao = new PfDaoFactory().createPfDao(daoParameters); - pfDao.init(daoParameters); - } - - /** - * Set up GSON. - */ - @Before - public void setupGson() { - gson = new ToscaServiceTemplateMessageBodyHandler().getGson(); - } - - @After - public void teardown() throws Exception { - pfDao.close(); - connection.close(); - } - - @Test - public void testJsonDeserialization() throws JsonSyntaxException, IOException { - ToscaServiceTemplate serviceTemplate = - gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), - ToscaServiceTemplate.class); - - assertNotNull(serviceTemplate); - LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); - assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); - - ToscaPolicy policyBeforeDb = serviceTemplate.getTopologyTemplate().getPolicies().get("onap.restart.tca"); - - pfDao.create(policyBeforeDb); - - ToscaPolicy policyAfterDb = pfDao.get(ToscaPolicy.class, new PfConceptKey("onap.restart.tca:1.0.0")); - - assertEquals(policyBeforeDb, policyAfterDb); - } -} diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java new file mode 100644 index 000000000..90d00fc58 --- /dev/null +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java @@ -0,0 +1,143 @@ +/*- + * ============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.policy.models.provider.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; + +import java.util.Base64; + +import lombok.NonNull; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.provider.PolicyModelsProvider; +import org.onap.policy.models.provider.PolicyModelsProviderFactory; +import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test persistence of monitoring policies to and from the database. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class PolicyLegacyOperationalPersistenceTest { + // Logger for this class + private static final Logger LOGGER = LoggerFactory.getLogger(PolicyLegacyOperationalPersistenceTest.class); + + private Gson gson; + + private PolicyModelsProvider databaseProvider; + + // @formatter:off + private String[] policyInputResourceNames = { + "policies/vCPE.policy.operational.input.json", + "policies/vDNS.policy.operational.input.json", + "policies/vFirewall.policy.operational.input.json" + }; + + private String[] policyOutputResourceNames = { + "policies/vCPE.policy.operational.output.json", + "policies/vDNS.policy.operational.output.json", + "policies/vFirewall.policy.operational.output.json" + }; + // @formatter:on + + /** + * Initialize provider. + * + * @throws PfModelException on exceptions in the tests + */ + @Before + public void setupParameters() throws PfModelException { + PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); + parameters.setDatabaseUser("policy"); + parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); + parameters.setPersistenceUnit("ToscaConceptTest"); + + databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); + databaseProvider.init(); + } + + /** + * Set up GSON. + */ + @Before + public void setupGson() { + gson = new Gson(); + } + + @After + public void teardown() throws Exception { + databaseProvider.close(); + } + + @Test + public void testPolicyPersistence() { + try { + for (int i = 0; i < policyInputResourceNames.length; i++) { + String policyInputString = ResourceUtils.getResourceAsString(policyInputResourceNames[i]); + String policyOutputString = ResourceUtils.getResourceAsString(policyOutputResourceNames[i]); + testJsonStringPolicyPersistence(policyInputString, policyOutputString); + } + } catch (Exception exc) { + LOGGER.warn("error processing policies", exc); + fail("test should not throw an exception"); + } + } + + /** + * Check persistence of a policy. + * + * @param policyInputString the policy as a string + * @param policyOutputString the expected output string + * @throws Exception any exception thrown + */ + public void testJsonStringPolicyPersistence(@NonNull final String policyInputString, + final String policyOutputString) throws Exception { + LegacyOperationalPolicy lop = gson.fromJson(policyInputString, LegacyOperationalPolicy.class); + + assertNotNull(lop); + + LegacyOperationalPolicy createdLop = databaseProvider.createOperationalPolicy(lop); + assertEquals(createdLop, lop); + + LegacyOperationalPolicy gotLop = databaseProvider.getOperationalPolicy(lop.getPolicyId()); + assertEquals(gotLop, lop); + + String actualRetrievedJson = gson.toJson(gotLop); + + // All of this dash/underscore stuff is to avoid a checkstyle error around escaping unicode characters + assertEquals( + policyOutputString.replaceAll("\\s+", "").replaceAll("u0027", "_-_-_-_").replaceAll("\\\\_-_-_-_", "'"), + actualRetrievedJson.replaceAll("\\s+", "").replaceAll("u0027", "_-_-_-_").replaceAll("\\\\_-_-_-_", + "'")); + } +} diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyPersistenceTest.java new file mode 100644 index 000000000..de299772f --- /dev/null +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyPersistenceTest.java @@ -0,0 +1,159 @@ +/*- + * ============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.policy.models.provider.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.util.Base64; + +import lombok.NonNull; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.provider.PolicyModelsProvider; +import org.onap.policy.models.provider.PolicyModelsProviderFactory; +import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +/** + * Test persistence of monitoring policies to and from the database. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class PolicyPersistenceTest { + // Logger for this class + private static final Logger LOGGER = LoggerFactory.getLogger(PolicyPersistenceTest.class); + + private Gson gson; + + private PolicyModelsProvider databaseProvider; + + // @formatter:off + private String[] policyResourceNames = { + "policies/vCPE.policy.monitoring.input.tosca.json", + "policies/vCPE.policy.monitoring.input.tosca.yaml", + "policies/vCPE.policy.operational.input.tosca.yaml", + "policies/vDNS.policy.guard.frequency.input.tosca.json", + "policies/vDNS.policy.guard.frequency.input.tosca.yaml", + "policies/vDNS.policy.monitoring.input.tosca.json", + "policies/vDNS.policy.monitoring.input.tosca.yaml", + "policies/vDNS.policy.operational.input.tosca.yaml", + "policies/vFirewall.policy.monitoring.input.tosca.json", + "policies/vFirewall.policy.monitoring.input.tosca.yaml", + "policies/vFirewall.policy.operational.input.tosca.json", + "policies/vFirewall.policy.operational.input.tosca.yaml" + }; + // @formatter:on + + /** + * Initialize provider. + * + * @throws PfModelException on exceptions in the tests + */ + @Before + public void setupParameters() throws PfModelException { + PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); + parameters.setDatabaseUser("policy"); + parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); + parameters.setPersistenceUnit("ToscaConceptTest"); + + databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); + databaseProvider.init(); + } + + /** + * Set up GSON. + */ + @Before + public void setupGson() { + gson = new ToscaServiceTemplateMessageBodyHandler().getGson(); + } + + @After + public void teardown() throws Exception { + databaseProvider.close(); + } + + @Test + public void testPolicyPersistence() { + try { + for (String policyResourceName : policyResourceNames) { + String policyString = ResourceUtils.getResourceAsString(policyResourceName); + + if (policyResourceName.endsWith("yaml")) { + testYamlStringPolicyPersistence(policyString); + } else { + testJsonStringPolicyPersistence(policyString); + } + } + } catch (Exception exc) { + LOGGER.warn("error processing policies", exc); + fail("test should not throw an exception"); + } + } + + private void testYamlStringPolicyPersistence(final String policyString) throws Exception { + Object yamlObject = new Yaml().load(policyString); + String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject); + + testJsonStringPolicyPersistence(yamlAsJsonString); + } + + /** + * Check persistence of a policy. + * + * @param policyString the policy as a string + * @throws Exception any exception thrown + */ + public void testJsonStringPolicyPersistence(@NonNull final String policyString) throws Exception { + ToscaServiceTemplate serviceTemplate = gson.fromJson(policyString, ToscaServiceTemplate.class); + + assertNotNull(serviceTemplate); + LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); + assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); + + databaseProvider.createPolicies(serviceTemplate); + + for (PfConceptKey policyKey : serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().keySet()) { + ToscaPolicy incomingPolicy = serviceTemplate.getTopologyTemplate().getPolicies().get(policyKey); + ToscaPolicy databasePolicy = + databaseProvider.getPolicies(policyKey).getTopologyTemplate().getPolicies().get(policyKey); + assertEquals(incomingPolicy, databasePolicy); + } + } +} diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java new file mode 100644 index 000000000..a4b1dcd03 --- /dev/null +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java @@ -0,0 +1,159 @@ +/*- + * ============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.policy.models.provider.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.util.Base64; + +import lombok.NonNull; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.provider.PolicyModelsProvider; +import org.onap.policy.models.provider.PolicyModelsProviderFactory; +import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +/** + * Test persistence of monitoring policies to and from the database. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class PolicyToscaPersistenceTest { + // Logger for this class + private static final Logger LOGGER = LoggerFactory.getLogger(PolicyToscaPersistenceTest.class); + + private Gson gson; + + private PolicyModelsProvider databaseProvider; + + // @formatter:off + private String[] policyResourceNames = { + "policies/vCPE.policy.monitoring.input.tosca.json", + "policies/vCPE.policy.monitoring.input.tosca.yaml", + "policies/vCPE.policy.operational.input.tosca.yaml", + "policies/vDNS.policy.guard.frequency.input.tosca.json", + "policies/vDNS.policy.guard.frequency.input.tosca.yaml", + "policies/vDNS.policy.monitoring.input.tosca.json", + "policies/vDNS.policy.monitoring.input.tosca.yaml", + "policies/vDNS.policy.operational.input.tosca.yaml", + "policies/vFirewall.policy.monitoring.input.tosca.json", + "policies/vFirewall.policy.monitoring.input.tosca.yaml", + "policies/vFirewall.policy.operational.input.tosca.json", + "policies/vFirewall.policy.operational.input.tosca.yaml" + }; + // @formatter:on + + /** + * Initialize provider. + * + * @throws PfModelException on exceptions in the tests + */ + @Before + public void setupParameters() throws PfModelException { + PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); + parameters.setDatabaseUser("policy"); + parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); + parameters.setPersistenceUnit("ToscaConceptTest"); + + databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); + databaseProvider.init(); + } + + /** + * Set up GSON. + */ + @Before + public void setupGson() { + gson = new ToscaServiceTemplateMessageBodyHandler().getGson(); + } + + @After + public void teardown() throws Exception { + databaseProvider.close(); + } + + @Test + public void testPolicyPersistence() { + try { + for (String policyResourceName : policyResourceNames) { + String policyString = ResourceUtils.getResourceAsString(policyResourceName); + + if (policyResourceName.endsWith("yaml")) { + testYamlStringPolicyPersistence(policyString); + } else { + testJsonStringPolicyPersistence(policyString); + } + } + } catch (Exception exc) { + LOGGER.warn("error processing policies", exc); + fail("test should not throw an exception"); + } + } + + private void testYamlStringPolicyPersistence(final String policyString) throws Exception { + Object yamlObject = new Yaml().load(policyString); + String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject); + + testJsonStringPolicyPersistence(yamlAsJsonString); + } + + /** + * Check persistence of a policy. + * + * @param policyString the policy as a string + * @throws Exception any exception thrown + */ + public void testJsonStringPolicyPersistence(@NonNull final String policyString) throws Exception { + ToscaServiceTemplate serviceTemplate = gson.fromJson(policyString, ToscaServiceTemplate.class); + + assertNotNull(serviceTemplate); + LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); + assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); + + databaseProvider.createPolicies(serviceTemplate); + + for (PfConceptKey policyKey : serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().keySet()) { + ToscaPolicy incomingPolicy = serviceTemplate.getTopologyTemplate().getPolicies().get(policyKey); + ToscaPolicy databasePolicy = + databaseProvider.getPolicies(policyKey).getTopologyTemplate().getPolicies().get(policyKey); + assertEquals(incomingPolicy, databasePolicy); + } + } +} |