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