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