Adding pdpGroup to PdpRegistrationHandler
[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 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 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
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.provider.PolicyModelsProvider;
42 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
43 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
44 import org.onap.policy.pap.main.PolicyPapRuntimeException;
45 import org.onap.policy.pap.main.parameters.PapParameterGroup;
46 import org.onap.policy.pap.main.rest.CommonPapRestServer;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.yaml.snakeyaml.Yaml;
50
51 public class End2EndBase extends CommonPapRestServer {
52     private static final Logger logger = LoggerFactory.getLogger(End2EndBase.class);
53
54     private static final Coder coder = new StandardCoder();
55     private static final Yaml yaml = new Yaml();
56
57     /**
58      * DB connection. This is kept open until {@link #stop()} is invoked so that the in-memory DB is not destroyed.
59      */
60     private static PolicyModelsProvider dbConn;
61
62     /**
63      * DAO provider factory.
64      */
65     private static PolicyModelsProviderFactoryWrapper daoFactory;
66
67     /**
68      * Context - should be initialized by setUp() method.
69      */
70     protected End2EndContext context = null;
71
72
73     /**
74      * Starts Main and connects to the DB.
75      *
76      * @throws Exception if an error occurs
77      */
78     @BeforeClass
79     public static void setUpBeforeClass() throws Exception {
80         setUpBeforeClass(true);
81     }
82
83     /**
84      * Starts Main, if specified, and connects to the DB.
85      *
86      * @param shouldStart {@code true} if Main should be started, {@code false} otherwise
87      * @throws Exception if an error occurs
88      */
89     public static void setUpBeforeClass(final boolean shouldStart) throws Exception {
90         CommonPapRestServer.setUpBeforeClass(shouldStart);
91
92         final PapParameterGroup params = new StandardCoder().decode(new File(CONFIG_FILE), PapParameterGroup.class);
93         daoFactory = new PolicyModelsProviderFactoryWrapper(params.getDatabaseProviderParameters());
94         dbConn = daoFactory.create();
95     }
96
97     /**
98      * Tears down.
99      */
100     @AfterClass
101     public static void tearDownAfterClass() {
102         try {
103             dbConn.close();
104         } catch (final PfModelException e) {
105             logger.warn("failed to close the DB", e);
106         }
107
108         try {
109             daoFactory.close();
110         } catch (final Exception e) {
111             logger.warn("failed to close DAO factory", e);
112         }
113
114         CommonPapRestServer.teardownAfterClass();
115     }
116
117     /**
118      * Tears down.
119      */
120     @Override
121     @After
122     public void tearDown() {
123         if (context != null) {
124             try {
125                 context.stop();
126             } catch (final Exception e) {
127                 logger.warn("failed to stop end-to-end context", e);
128             }
129             context = null;
130         }
131
132         super.tearDown();
133     }
134
135     /**
136      * Adds Tosca Policy Types to the DB.
137      *
138      * @param yamlFile name of the YAML file specifying the data to be loaded
139      * @throws PfModelException if a DAO error occurs
140      */
141     public static void addToscaPolicyTypes(final String yamlFile) throws PfModelException {
142         final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
143         dbConn.createPolicyTypes(serviceTemplate);
144     }
145
146     /**
147      * Adds Tosca Policies to the DB.
148      *
149      * @param yamlFile name of the YAML file specifying the data to be loaded
150      * @throws PfModelException if a DAO error occurs
151      */
152     public static void addToscaPolicies(final String yamlFile) throws PfModelException {
153         final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
154         dbConn.createPolicies(serviceTemplate);
155     }
156
157     /**
158      * Adds PDP groups to the DB.
159      *
160      * @param jsonFile name of the JSON file specifying the data to be loaded
161      * @throws PfModelException if a DAO error occurs
162      */
163     public static void addGroups(final String jsonFile) throws PfModelException {
164         final PdpGroups groups = loadJsonFile(jsonFile, PdpGroups.class);
165
166         final ValidationResult result = groups.validatePapRest();
167         if (!result.isValid()) {
168             throw new PolicyPapRuntimeException("cannot init DB groups from " + jsonFile + ":\n" + result.getResult());
169         }
170
171         dbConn.createPdpGroups(groups.getGroups());
172     }
173
174     /**
175      * Fetch PDP groups from the DB.
176      *
177      * @param name name of the pdpGroup
178      * @throws PfModelException if a DAO error occurs
179      */
180     public static List<PdpGroup> fetchGroups(final String name) throws PfModelException {
181         return dbConn.getPdpGroups(name);
182     }
183
184     /**
185      * Loads an object from a YAML file.
186      *
187      * @param fileName name of the file from which to load
188      * @param clazz the class of the object to be loaded
189      * @return the object that was loaded from the file
190      */
191     protected static <T> T loadYamlFile(final String fileName, final Class<T> clazz) {
192         final File propFile = new File(ResourceUtils.getFilePath4Resource("e2e/" + fileName));
193
194         try (FileInputStream input = new FileInputStream(propFile)) {
195             final Object yamlObject = yaml.load(input);
196             final String json = coder.encode(yamlObject);
197             final T result = coder.decode(json, clazz);
198
199             if (result == null) {
200                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
201             }
202
203             return result;
204
205         } catch (final FileNotFoundException e) {
206             throw new PolicyPapRuntimeException("cannot find " + fileName, e);
207
208         } catch (IOException | CoderException e) {
209             throw new PolicyPapRuntimeException("cannot decode " + fileName, e);
210         }
211     }
212
213     /**
214      * Loads an object from a JSON file.
215      *
216      * @param fileName name of the file from which to load
217      * @param clazz the class of the object to be loaded
218      * @return the object that was loaded from the file
219      */
220     protected static <T> T loadJsonFile(final String fileName, final Class<T> clazz) {
221         final String fileName2 = (fileName.startsWith("src/") ? fileName : "e2e/" + fileName);
222         final File propFile = new File(ResourceUtils.getFilePath4Resource(fileName2));
223         try {
224             final T result = coder.decode(propFile, clazz);
225
226             if (result == null) {
227                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
228             }
229
230             return result;
231
232         } catch (final CoderException e) {
233             throw new RuntimeException(e);
234         }
235     }
236 }