Make PAP stateless
[policy/pap.git] / main / src / test / java / org / onap / policy / pap / main / rest / e2e / End2EndBase.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP PAP
4  * ================================================================================
5  * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019-2020 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pap.main.rest.e2e;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.util.List;
29 import org.junit.After;
30 import org.junit.AfterClass;
31 import org.junit.BeforeClass;
32 import org.onap.policy.common.parameters.ValidationResult;
33 import org.onap.policy.common.utils.coder.Coder;
34 import org.onap.policy.common.utils.coder.CoderException;
35 import org.onap.policy.common.utils.coder.StandardCoder;
36 import org.onap.policy.common.utils.resources.ResourceUtils;
37 import org.onap.policy.models.base.PfModelException;
38 import org.onap.policy.models.pdp.concepts.PdpGroup;
39 import org.onap.policy.models.pdp.concepts.PdpGroups;
40 import org.onap.policy.models.pdp.concepts.PdpPolicyStatus;
41 import org.onap.policy.models.pdp.concepts.PdpStatistics;
42 import org.onap.policy.models.provider.PolicyModelsProvider;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
44 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
45 import org.onap.policy.pap.main.PolicyPapRuntimeException;
46 import org.onap.policy.pap.main.parameters.PapParameterGroup;
47 import org.onap.policy.pap.main.rest.CommonPapRestServer;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.yaml.snakeyaml.Yaml;
51
52 public class End2EndBase extends CommonPapRestServer {
53     private static final Logger logger = LoggerFactory.getLogger(End2EndBase.class);
54
55     private static final Coder coder = new StandardCoder();
56     private static final Yaml yaml = new Yaml();
57
58     /**
59      * DB connection. This is kept open until {@link #stop()} is invoked so that the in-memory DB is not destroyed.
60      */
61     private static PolicyModelsProvider dbConn;
62
63     /**
64      * DAO provider factory.
65      */
66     private static PolicyModelsProviderFactoryWrapper daoFactory;
67
68     /**
69      * Context - should be initialized by setUp() method.
70      */
71     protected End2EndContext context = null;
72
73
74     /**
75      * Starts Main and connects to the DB.
76      *
77      * @throws Exception if an error occurs
78      */
79     @BeforeClass
80     public static void setUpBeforeClass() throws Exception {
81         CommonPapRestServer.setUpBeforeClass(true);
82
83         final PapParameterGroup params = new StandardCoder().decode(new File(CONFIG_FILE), PapParameterGroup.class);
84         daoFactory = new PolicyModelsProviderFactoryWrapper(params.getDatabaseProviderParameters());
85         dbConn = daoFactory.create();
86     }
87
88     /**
89      * Tears down.
90      */
91     @AfterClass
92     public static void tearDownAfterClass() {
93         try {
94             dbConn.close();
95         } catch (final PfModelException e) {
96             logger.warn("failed to close the DB", e);
97         }
98
99         try {
100             daoFactory.close();
101         } catch (final Exception e) {
102             logger.warn("failed to close DAO factory", e);
103         }
104
105         CommonPapRestServer.teardownAfterClass();
106     }
107
108     /**
109      * Tears down.
110      */
111     @Override
112     @After
113     public void tearDown() {
114         if (context != null) {
115             try {
116                 context.stop();
117             } catch (final Exception e) {
118                 logger.warn("failed to stop end-to-end context", e);
119             }
120             context = null;
121         }
122
123         super.tearDown();
124     }
125
126     /**
127      * Adds Tosca Policy Types to the DB.
128      *
129      * @param yamlFile name of the YAML file specifying the data to be loaded
130      * @throws PfModelException if a DAO error occurs
131      */
132     public static void addToscaPolicyTypes(final String yamlFile) throws PfModelException {
133         final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
134         dbConn.createPolicyTypes(serviceTemplate);
135     }
136
137     /**
138      * Adds Tosca Policies to the DB.
139      *
140      * @param yamlFile name of the YAML file specifying the data to be loaded
141      * @throws PfModelException if a DAO error occurs
142      */
143     public static void addToscaPolicies(final String yamlFile) throws PfModelException {
144         final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
145         dbConn.createPolicies(serviceTemplate);
146     }
147
148     /**
149      * Adds PDP groups to the DB.
150      *
151      * @param jsonFile name of the JSON file specifying the data to be loaded
152      * @throws PfModelException if a DAO error occurs
153      */
154     public static void addGroups(final String jsonFile) throws PfModelException {
155         final PdpGroups groups = loadJsonFile(jsonFile, PdpGroups.class);
156
157         final ValidationResult result = groups.validatePapRest();
158         if (!result.isValid()) {
159             throw new PolicyPapRuntimeException("cannot init DB groups from " + jsonFile + ":\n" + result.getResult());
160         }
161
162         dbConn.createPdpGroups(groups.getGroups());
163     }
164
165     /**
166      * Fetch PDP groups from the DB.
167      *
168      * @param name name of the pdpGroup
169      * @throws PfModelException if a DAO error occurs
170      */
171     public static List<PdpGroup> fetchGroups(final String name) throws PfModelException {
172         return dbConn.getPdpGroups(name);
173     }
174
175     /**
176      * Fetch PDP statistics from the DB.
177      *
178      * @param instanceId name of the pdpStatistics
179      * @param groupName name of the pdpGroup
180      * @param subGroupName name of the pdpSubGroup
181      * @throws PfModelException if a DAO error occurs
182      */
183     public static List<PdpStatistics> fetchPdpStatistics(final String instanceId, final String groupName,
184            final String subGroupName) throws PfModelException {
185         return dbConn.getFilteredPdpStatistics(instanceId, groupName, subGroupName, null, null, null, 0);
186     }
187
188     /**
189      * Adds PdpPolicyStatus records to the DB.
190      *
191      * @param jsonFile name of the JSON file specifying the data to be loaded
192      * @throws PfModelException if a DAO error occurs
193      */
194     public static void addPdpPolicyStatus(final String jsonFile) throws PfModelException {
195         final PolicyStatusRecords data = loadJsonFile(jsonFile, PolicyStatusRecords.class);
196         dbConn.cudPolicyStatus(data.records, null, null);
197     }
198
199     /**
200      * Loads an object from a YAML file.
201      *
202      * @param fileName name of the file from which to load
203      * @param clazz the class of the object to be loaded
204      * @return the object that was loaded from the file
205      */
206     protected static <T> T loadYamlFile(final String fileName, final Class<T> clazz) {
207         final File propFile = new File(ResourceUtils.getFilePath4Resource("e2e/" + fileName));
208
209         try (FileInputStream input = new FileInputStream(propFile)) {
210             final Object yamlObject = yaml.load(input);
211             final String json = coder.encode(yamlObject);
212             final T result = coder.decode(json, clazz);
213
214             if (result == null) {
215                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
216             }
217
218             return result;
219
220         } catch (final FileNotFoundException e) {
221             throw new PolicyPapRuntimeException("cannot find " + fileName, e);
222
223         } catch (IOException | CoderException e) {
224             throw new PolicyPapRuntimeException("cannot decode " + fileName, e);
225         }
226     }
227
228     /**
229      * Loads an object from a JSON file.
230      *
231      * @param fileName name of the file from which to load
232      * @param clazz the class of the object to be loaded
233      * @return the object that was loaded from the file
234      */
235     protected static <T> T loadJsonFile(final String fileName, final Class<T> clazz) {
236         final String fileName2 = (fileName.startsWith("src/") ? fileName : "e2e/" + fileName);
237         final File propFile = new File(ResourceUtils.getFilePath4Resource(fileName2));
238         try {
239             final T result = coder.decode(propFile, clazz);
240
241             if (result == null) {
242                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
243             }
244
245             return result;
246
247         } catch (final CoderException e) {
248             throw new RuntimeException(e);
249         }
250     }
251
252     public class PolicyStatusRecords {
253         private List<PdpPolicyStatus> records;
254     }
255 }