Move PAP database provider to spring boot default
[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-2022 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 java.util.Map;
31 import java.util.Optional;
32 import org.junit.After;
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.PfConceptKey;
39 import org.onap.policy.models.base.PfModelException;
40 import org.onap.policy.models.pdp.concepts.PdpGroup;
41 import org.onap.policy.models.pdp.concepts.PdpGroups;
42 import org.onap.policy.models.pdp.concepts.PdpPolicyStatus;
43 import org.onap.policy.models.pdp.concepts.PdpStatistics;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
45 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
46 import org.onap.policy.pap.main.PolicyPapRuntimeException;
47 import org.onap.policy.pap.main.repository.ToscaServiceTemplateRepository;
48 import org.onap.policy.pap.main.rest.CommonPapRestServer;
49 import org.onap.policy.pap.main.service.PdpGroupService;
50 import org.onap.policy.pap.main.service.PdpStatisticsService;
51 import org.onap.policy.pap.main.service.PolicyStatusService;
52 import org.onap.policy.pap.main.service.ToscaServiceTemplateService;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.yaml.snakeyaml.Yaml;
57
58 public abstract class End2EndBase extends CommonPapRestServer {
59     private static final Logger logger = LoggerFactory.getLogger(End2EndBase.class);
60
61     private static final Coder coder = new StandardCoder();
62     private static final Yaml yaml = new Yaml();
63
64     /**
65      * Context - should be initialized by setUp() method.
66      */
67     protected End2EndContext context = null;
68
69     @Autowired
70     public PdpGroupService pdpGroupService;
71
72     @Autowired
73     public PdpStatisticsService pdpStatisticsService;
74
75     @Autowired
76     private ToscaServiceTemplateRepository serviceTemplateRepository;
77
78     @Autowired
79     public PolicyStatusService policyStatusService;
80
81     @Autowired
82     public ToscaServiceTemplateService toscaService;
83
84     /**
85      * Tears down.
86      */
87     @Override
88     @After
89     public void tearDown() {
90         if (context != null) {
91             try {
92                 context.stop();
93             } catch (final Exception e) {
94                 logger.warn("failed to stop end-to-end context", e);
95             }
96             context = null;
97         }
98
99         super.tearDown();
100     }
101
102     /**
103      * Adds Tosca Policy Types to the DB.
104      *
105      * @param yamlFile name of the YAML file specifying the data to be loaded
106      * @throws PfModelException if a DAO error occurs
107      */
108     public void addToscaPolicyTypes(final String yamlFile) throws PfModelException {
109         final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
110         JpaToscaServiceTemplate jpaToscaServiceTemplate = mergeWithExistingTemplate(serviceTemplate);
111         serviceTemplateRepository.save(jpaToscaServiceTemplate);
112     }
113
114     /**
115      * Adds Tosca Policies to the DB.
116      *
117      * @param yamlFile name of the YAML file specifying the data to be loaded
118      * @throws PfModelException if a DAO error occurs
119      */
120     public void addToscaPolicies(final String yamlFile) throws PfModelException {
121         final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
122         JpaToscaServiceTemplate jpaToscaServiceTemplate = mergeWithExistingTemplate(serviceTemplate);
123         serviceTemplateRepository.save(jpaToscaServiceTemplate);
124     }
125
126     private JpaToscaServiceTemplate mergeWithExistingTemplate(ToscaServiceTemplate serviceTemplate) {
127         JpaToscaServiceTemplate jpaToscaServiceTemplate = new JpaToscaServiceTemplate(serviceTemplate);
128         Optional<JpaToscaServiceTemplate> dbServiceTemplateOpt = serviceTemplateRepository
129             .findById(new PfConceptKey(JpaToscaServiceTemplate.DEFAULT_NAME, JpaToscaServiceTemplate.DEFAULT_VERSION));
130         if (!dbServiceTemplateOpt.isEmpty()) {
131             JpaToscaServiceTemplate dbServiceTemplate = dbServiceTemplateOpt.get();
132             if (dbServiceTemplate.getPolicyTypes() != null) {
133                 jpaToscaServiceTemplate.setPolicyTypes(dbServiceTemplate.getPolicyTypes());
134             }
135             if (dbServiceTemplate.getDataTypes() != null) {
136                 jpaToscaServiceTemplate.setDataTypes(dbServiceTemplate.getDataTypes());
137             }
138             if (dbServiceTemplate.getTopologyTemplate() != null) {
139                 jpaToscaServiceTemplate.setTopologyTemplate(dbServiceTemplate.getTopologyTemplate());
140             }
141         }
142
143         return jpaToscaServiceTemplate;
144     }
145
146     /**
147      * Adds PDP groups to the DB.
148      *
149      * @param jsonFile name of the JSON file specifying the data to be loaded
150      * @throws PfModelException if a DAO error occurs
151      */
152     public void addGroups(final String jsonFile) throws PfModelException {
153         final PdpGroups groups = loadJsonFile(jsonFile, PdpGroups.class);
154
155         final ValidationResult result = groups.validatePapRest();
156         if (!result.isValid()) {
157             throw new PolicyPapRuntimeException("cannot init DB groups from " + jsonFile + ":\n" + result.getResult());
158         }
159
160         pdpGroupService.createPdpGroups(groups.getGroups());
161     }
162
163     /**
164      * Fetch PDP groups from the DB.
165      *
166      * @param name name of the pdpGroup
167      * @throws PfModelException if a DAO error occurs
168      */
169     public List<PdpGroup> fetchGroups(final String name) throws PfModelException {
170         return pdpGroupService.getPdpGroups(name);
171     }
172
173     /**
174      * Fetch PDP statistics from the DB.
175      *
176      * @param instanceId name of the pdpStatistics
177      * @param groupName name of the pdpGroup
178      * @param subGroupName name of the pdpSubGroup
179      * @throws PfModelException if a DAO error occurs
180      */
181     public Map<String, Map<String, List<PdpStatistics>>> fetchPdpStatistics(final String instanceId,
182         final String groupName, final String subGroupName) throws PfModelException {
183         return pdpStatisticsService.fetchDatabaseStatistics(groupName, subGroupName, instanceId, 100, null, null);
184     }
185
186     /**
187      * Adds PdpPolicyStatus records to the DB.
188      *
189      * @param jsonFile name of the JSON file specifying the data to be loaded
190      * @throws PfModelException if a DAO error occurs
191      */
192     public void addPdpPolicyStatus(final String jsonFile) throws PfModelException {
193         final PolicyStatusRecords data = loadJsonFile(jsonFile, PolicyStatusRecords.class);
194         policyStatusService.cudPolicyStatus(data.records, null, null);
195     }
196
197     /**
198      * Loads an object from a YAML file.
199      *
200      * @param fileName name of the file from which to load
201      * @param clazz the class of the object to be loaded
202      * @return the object that was loaded from the file
203      */
204     protected static <T> T loadYamlFile(final String fileName, final Class<T> clazz) {
205         final File propFile = new File(ResourceUtils.getFilePath4Resource("e2e/" + fileName));
206
207         try (FileInputStream input = new FileInputStream(propFile)) {
208             final Object yamlObject = yaml.load(input);
209             final String json = coder.encode(yamlObject);
210             final T result = coder.decode(json, clazz);
211
212             if (result == null) {
213                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
214             }
215
216             return result;
217
218         } catch (final FileNotFoundException e) {
219             throw new PolicyPapRuntimeException("cannot find " + fileName, e);
220
221         } catch (IOException | CoderException e) {
222             throw new PolicyPapRuntimeException("cannot decode " + fileName, e);
223         }
224     }
225
226     /**
227      * Loads an object from a JSON file.
228      *
229      * @param fileName name of the file from which to load
230      * @param clazz the class of the object to be loaded
231      * @return the object that was loaded from the file
232      */
233     protected static <T> T loadJsonFile(final String fileName, final Class<T> clazz) {
234         final String fileName2 = (fileName.startsWith("src/") ? fileName : "e2e/" + fileName);
235         final File propFile = new File(ResourceUtils.getFilePath4Resource(fileName2));
236         try {
237             final T result = coder.decode(propFile, clazz);
238
239             if (result == null) {
240                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
241             }
242
243             return result;
244
245         } catch (final CoderException e) {
246             throw new RuntimeException(e);
247         }
248     }
249
250     public class PolicyStatusRecords {
251         private List<PdpPolicyStatus> records;
252     }
253 }