ecb50cdc30040edecb4c0f1edce8550bf8d95d3c
[policy/models.git] / models-provider / src / test / java / org / onap / policy / models / provider / impl / PolicyLegacyGuardPersistenceTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2020 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.models.provider.impl;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25
26 import java.net.URISyntaxException;
27 import java.util.Base64;
28 import java.util.Map;
29 import java.util.Set;
30
31 import lombok.NonNull;
32
33 import org.junit.After;
34 import org.junit.Before;
35 import org.junit.Test;
36 import org.onap.policy.common.utils.coder.CoderException;
37 import org.onap.policy.common.utils.coder.StandardCoder;
38 import org.onap.policy.common.utils.resources.ResourceUtils;
39 import org.onap.policy.models.base.PfModelException;
40 import org.onap.policy.models.provider.PolicyModelsProvider;
41 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
42 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
44 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput;
45 import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput;
46 import org.yaml.snakeyaml.Yaml;
47
48 /**
49  * Test persistence of monitoring policies to and from the database.
50  *
51  * @author Liam Fallon (liam.fallon@est.tech)
52  */
53 public class PolicyLegacyGuardPersistenceTest {
54     private StandardCoder standardCoder;
55
56     private PolicyModelsProvider databaseProvider;
57
58     // @formatter:off
59     private String[] policyInputResourceNames = {
60         "policies/vDNS.policy.guard.frequency.input.json",
61         "policies/vDNS.policy.guard.minmax.input.json"
62     };
63
64     private String[] policyOutputResourceNames = {
65         "policies/vDNS.policy.guard.frequency.output.json",
66         "policies/vDNS.policy.guard.minmax.output.json"
67     };
68     // @formatter:on
69
70     /**
71      * Initialize provider.
72      *
73      * @throws PfModelException on exceptions in the tests
74      * @throws CoderException on JSON encoding and decoding errors
75      */
76     @Before
77     public void setupParameters() throws Exception {
78         // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB
79
80         PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters();
81         parameters.setDatabaseDriver("org.h2.Driver");
82         parameters.setDatabaseUrl("jdbc:h2:mem:testdb");
83         parameters.setDatabaseUser("policy");
84         parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
85         parameters.setPersistenceUnit("ToscaConceptTest");
86
87         databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters);
88
89         createPolicyTypes();
90     }
91
92     /**
93      * Set up standard coder.
94      */
95     @Before
96     public void setupStandardCoder() {
97         standardCoder = new StandardCoder();
98     }
99
100     @After
101     public void teardown() throws Exception {
102         databaseProvider.close();
103     }
104
105     @Test
106     public void testLegacyGuardPolicyPersistence() throws Exception {
107         for (int i = 0; i < policyInputResourceNames.length; i++) {
108             String policyInputString = ResourceUtils.getResourceAsString(policyInputResourceNames[i]);
109             String policyOutputString = ResourceUtils.getResourceAsString(policyOutputResourceNames[i]);
110             testJsonStringPolicyPersistence(policyInputString, policyOutputString);
111         }
112     }
113
114     /**
115      * Check persistence of a policy.
116      *
117      * @param policyInputString the policy as a string
118      * @param policyOutputString the expected output string
119      * @throws Exception any exception thrown
120      */
121     public void testJsonStringPolicyPersistence(@NonNull final String policyInputString,
122             final String policyOutputString) throws Exception {
123         LegacyGuardPolicyInput gip = standardCoder.decode(policyInputString, LegacyGuardPolicyInput.class);
124
125         assertNotNull(gip);
126
127         Map<String, LegacyGuardPolicyOutput> createdGopm = databaseProvider.createGuardPolicy(gip);
128         assertEquals(gip.getPolicyId(), createdGopm.keySet().iterator().next());
129         assertEquals(gip.getContent(), createdGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
130
131         Map<String, LegacyGuardPolicyOutput> gotGopm = databaseProvider.getGuardPolicy(gip.getPolicyId(), null);
132         assertEquals(gip.getPolicyId(), gotGopm.keySet().iterator().next());
133         assertEquals(gip.getContent(), gotGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
134
135         Map<String, LegacyGuardPolicyOutput> updatedGopm = databaseProvider.updateGuardPolicy(gip);
136         assertEquals(gip.getPolicyId(), updatedGopm.keySet().iterator().next());
137         assertEquals(gip.getContent(), updatedGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
138
139         Map<String, LegacyGuardPolicyOutput> deletedGopm = databaseProvider.deleteGuardPolicy(gip.getPolicyId(), "1");
140         assertEquals(gip.getPolicyId(), deletedGopm.keySet().iterator().next());
141         assertEquals(gip.getContent(), deletedGopm.get(gip.getPolicyId()).getProperties().values().iterator().next());
142
143         String actualRetrievedJson = standardCoder.encode(gotGopm);
144
145         // All of this dash/underscore stuff is to avoid a checkstyle error around escaping unicode characters
146         assertEquals(policyOutputString.replaceAll("\\s+", ""), actualRetrievedJson.replaceAll("\\s+", ""));
147     }
148
149     private void createPolicyTypes() throws CoderException, PfModelException, URISyntaxException {
150         Set<String> policyTypeResources = ResourceUtils.getDirectoryContents("policytypes");
151
152         for (String policyTyoeResource : policyTypeResources) {
153             Object yamlObject = new Yaml().load(ResourceUtils.getResourceAsString(policyTyoeResource));
154             String yamlAsJsonString = new StandardCoder().encode(yamlObject);
155
156             ToscaServiceTemplate toscaServiceTemplatePolicyType =
157                     standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
158
159             assertNotNull(toscaServiceTemplatePolicyType);
160             databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
161         }
162     }
163 }