8e0dcb31ce22514abe436b3fe1588609f45f54a9
[policy/models.git] / models-provider / src / test / java / org / onap / policy / models / provider / impl / PolicyPersistenceTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 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 import static org.junit.Assert.fail;
26
27 import com.google.gson.GsonBuilder;
28
29 import java.util.Base64;
30 import java.util.List;
31 import java.util.Map;
32
33 import lombok.NonNull;
34
35 import org.junit.After;
36 import org.junit.Before;
37 import org.junit.Test;
38 import org.onap.policy.common.utils.coder.CoderException;
39 import org.onap.policy.common.utils.coder.StandardCoder;
40 import org.onap.policy.common.utils.resources.ResourceUtils;
41 import org.onap.policy.models.base.PfModelException;
42 import org.onap.policy.models.provider.PolicyModelsProvider;
43 import org.onap.policy.models.provider.PolicyModelsProviderFactory;
44 import org.onap.policy.models.provider.PolicyModelsProviderParameters;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.yaml.snakeyaml.Yaml;
51
52 /**
53  * Test persistence of monitoring policies to and from the database.
54  *
55  * @author Liam Fallon (liam.fallon@est.tech)
56  */
57 public class PolicyPersistenceTest {
58     // Logger for this class
59     private static final Logger LOGGER = LoggerFactory.getLogger(PolicyPersistenceTest.class);
60
61     private StandardCoder standardCoder;
62
63     private PolicyModelsProvider databaseProvider;
64
65     // @formatter:off
66     private String[] policyResourceNames = {
67         "policies/vCPE.policy.monitoring.input.tosca.json",
68         "policies/vCPE.policy.monitoring.input.tosca.yaml",
69         "policies/vCPE.policy.operational.input.tosca.yaml",
70         "policies/vDNS.policy.guard.frequency.input.tosca.json",
71         "policies/vDNS.policy.guard.frequency.input.tosca.yaml",
72         "policies/vDNS.policy.monitoring.input.tosca.json",
73         "policies/vDNS.policy.monitoring.input.tosca.yaml",
74         "policies/vDNS.policy.operational.input.tosca.yaml",
75         "policies/vFirewall.policy.monitoring.input.tosca.json",
76         "policies/vFirewall.policy.monitoring.input.tosca.yaml",
77         "policies/vFirewall.policy.operational.input.tosca.json",
78         "policies/vFirewall.policy.operational.input.tosca.yaml"
79     };
80     // @formatter:on
81
82     /**
83      * Initialize provider.
84      *
85      * @throws PfModelException on exceptions in the tests
86      * @throws CoderException on JSON encoding and decoding errors
87      */
88     @Before
89     public void setupParameters() throws Exception {
90         // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB
91
92         PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters();
93         parameters.setDatabaseDriver("org.h2.Driver");
94         parameters.setDatabaseUrl("jdbc:h2:mem:testdb");
95         parameters.setDatabaseUser("policy");
96         parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes()));
97         parameters.setPersistenceUnit("ToscaConceptTest");
98
99         databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters);
100
101         createPolicyTypes();
102     }
103
104     /**
105      * Set up GSON.
106      */
107     @Before
108     public void setupGson() {
109         standardCoder = new StandardCoder();
110     }
111
112     @After
113     public void teardown() throws Exception {
114         databaseProvider.close();
115     }
116
117     @Test
118     public void testPolicyPersistence() {
119         try {
120             for (String policyResourceName : policyResourceNames) {
121                 String policyString = ResourceUtils.getResourceAsString(policyResourceName);
122
123                 if (policyResourceName.endsWith("yaml")) {
124                     testYamlStringPolicyPersistence(policyString);
125                 } else {
126                     testJsonStringPolicyPersistence(policyString);
127                 }
128             }
129         } catch (Exception exc) {
130             LOGGER.warn("error processing policies", exc);
131             fail("test should not throw an exception");
132         }
133     }
134
135     private void testYamlStringPolicyPersistence(final String policyString) throws Exception {
136         Object yamlObject = new Yaml().load(policyString);
137         String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject);
138
139         testJsonStringPolicyPersistence(yamlAsJsonString);
140     }
141
142     /**
143      * Check persistence of a policy.
144      *
145      * @param policyString the policy as a string
146      * @throws Exception any exception thrown
147      */
148     public void testJsonStringPolicyPersistence(@NonNull final String policyString) throws Exception {
149         ToscaServiceTemplate serviceTemplate = standardCoder.decode(policyString, ToscaServiceTemplate.class);
150
151         assertNotNull(serviceTemplate);
152
153         databaseProvider.createPolicies(serviceTemplate);
154         databaseProvider.updatePolicies(serviceTemplate);
155
156         for (Map<String, ToscaPolicy> policyMap : serviceTemplate.getToscaTopologyTemplate().getPolicies()) {
157             for (ToscaPolicy policy : policyMap.values()) {
158                 ToscaServiceTemplate gotToscaServiceTemplate =
159                         databaseProvider.getPolicies(policy.getName(), policy.getVersion());
160
161                 assertEquals(gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
162                         .get(policy.getName()).getType(), policy.getType());
163
164                 gotToscaServiceTemplate = databaseProvider.getFilteredPolicies(ToscaPolicyFilter.builder().build());
165
166                 assertEquals(getToscaPolicyFromMapList(
167                         gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies(), policy.getName()).getType(),
168                         policy.getType());
169
170                 gotToscaServiceTemplate = databaseProvider.getFilteredPolicies(
171                         ToscaPolicyFilter.builder().name(policy.getName()).version(policy.getVersion()).build());
172
173                 assertEquals(gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
174                         .get(policy.getName()).getType(), policy.getType());
175             }
176         }
177     }
178
179     private ToscaPolicy getToscaPolicyFromMapList(List<Map<String, ToscaPolicy>> toscaPolicyMapList,
180             String policyName) {
181         ToscaPolicy toscaPolicy = new ToscaPolicy();
182         for (Map<String, ToscaPolicy> policyMap: toscaPolicyMapList) {
183             if (policyMap.get(policyName) != null) {
184                 toscaPolicy = policyMap.get(policyName);
185                 break;
186             }
187         }
188         return toscaPolicy;
189     }
190
191     private void createPolicyTypes() throws CoderException, PfModelException {
192         Object yamlObject = new Yaml().load(
193                 ResourceUtils.getResourceAsString("policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app.yaml"));
194         String yamlAsJsonString = new StandardCoder().encode(yamlObject);
195
196         ToscaServiceTemplate toscaServiceTemplatePolicyType =
197                 standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
198
199         assertNotNull(toscaServiceTemplatePolicyType);
200         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
201
202         yamlObject = new Yaml().load(
203                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.Operational.yaml"));
204         yamlAsJsonString = new StandardCoder().encode(yamlObject);
205
206         toscaServiceTemplatePolicyType = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
207
208         assertNotNull(toscaServiceTemplatePolicyType);
209         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
210
211         yamlObject = new Yaml().load(
212                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.operational.Common.yaml"));
213         yamlAsJsonString = new StandardCoder().encode(yamlObject);
214
215         toscaServiceTemplatePolicyType = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
216
217         assertNotNull(toscaServiceTemplatePolicyType);
218         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
219
220         yamlObject = new Yaml().load(
221                 ResourceUtils.getResourceAsString("policytypes/onap.policies.controlloop.guard.FrequencyLimiter.yaml"));
222         yamlAsJsonString = new StandardCoder().encode(yamlObject);
223
224         toscaServiceTemplatePolicyType = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class);
225
226         assertNotNull(toscaServiceTemplatePolicyType);
227         databaseProvider.createPolicyTypes(toscaServiceTemplatePolicyType);
228     }
229 }