1aa40a280239fef6554a79f70076feb42c8767cf
[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, 2022-2023 Nordix Foundation.
7  * Modifications Copyright (C) 2021-2023 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 io.micrometer.core.instrument.MeterRegistry;
26 import java.io.File;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.IOException;
30 import java.util.List;
31 import java.util.Optional;
32 import lombok.Getter;
33 import org.junit.jupiter.api.AfterEach;
34 import org.onap.policy.common.parameters.ValidationResult;
35 import org.onap.policy.common.utils.coder.Coder;
36 import org.onap.policy.common.utils.coder.CoderException;
37 import org.onap.policy.common.utils.coder.StandardCoder;
38 import org.onap.policy.common.utils.resources.PrometheusUtils;
39 import org.onap.policy.common.utils.resources.ResourceUtils;
40 import org.onap.policy.models.base.PfConceptKey;
41 import org.onap.policy.models.pdp.concepts.PdpGroup;
42 import org.onap.policy.models.pdp.concepts.PdpGroups;
43 import org.onap.policy.models.pdp.concepts.PdpPolicyStatus;
44 import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.State;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
46 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
47 import org.onap.policy.pap.main.PolicyPapRuntimeException;
48 import org.onap.policy.pap.main.repository.ToscaServiceTemplateRepository;
49 import org.onap.policy.pap.main.rest.CommonPapRestServer;
50 import org.onap.policy.pap.main.service.PdpGroupService;
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.springframework.test.context.ActiveProfiles;
57 import org.yaml.snakeyaml.Yaml;
58
59 @ActiveProfiles({"test-e2e", "default"})
60 public abstract class End2EndBase extends CommonPapRestServer {
61     private static final Logger logger = LoggerFactory.getLogger(End2EndBase.class);
62
63     private static final Coder coder = new StandardCoder();
64     private static final Yaml yaml = new Yaml();
65
66     /**
67      * Context - should be initialized by setUp() method.
68      */
69     protected End2EndContext context = null;
70
71     @Autowired
72     public PdpGroupService pdpGroupService;
73
74     @Autowired
75     private ToscaServiceTemplateRepository serviceTemplateRepository;
76
77     @Autowired
78     public PolicyStatusService policyStatusService;
79
80     @Autowired
81     public ToscaServiceTemplateService toscaService;
82
83     @Autowired
84     public MeterRegistry meterRegistry;
85
86     @Getter
87     private final String topicPolicyPdpPap = "pdp-pap-topic";
88
89     @Getter
90     private final String topicPolicyNotification = "notification-topic";
91
92     public String deploymentsCounterName = "pap_" + PrometheusUtils.POLICY_DEPLOYMENTS_METRIC;
93     public String[] deploymentSuccessTag = {PrometheusUtils.OPERATION_METRIC_LABEL, PrometheusUtils.DEPLOY_OPERATION,
94         PrometheusUtils.STATUS_METRIC_LABEL, State.SUCCESS.name()};
95     public String[] unDeploymentSuccessTag = {PrometheusUtils.OPERATION_METRIC_LABEL,
96         PrometheusUtils.UNDEPLOY_OPERATION, PrometheusUtils.STATUS_METRIC_LABEL, State.SUCCESS.name()};
97
98     /**
99      * Tears down.
100      */
101     @Override
102     @AfterEach
103     public void tearDown() {
104         if (context != null) {
105             try {
106                 context.stop();
107             } catch (final Exception e) {
108                 logger.warn("failed to stop end-to-end context", e);
109             }
110             context = null;
111         }
112         meterRegistry.clear();
113         super.tearDown();
114     }
115
116     /**
117      * Adds Tosca Policy Types to the DB.
118      *
119      * @param yamlFile name of the YAML file specifying the data to be loaded
120      */
121     public void addToscaPolicyTypes(final String yamlFile) {
122         final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
123         JpaToscaServiceTemplate jpaToscaServiceTemplate = mergeWithExistingTemplate(serviceTemplate);
124         serviceTemplateRepository.save(jpaToscaServiceTemplate);
125     }
126
127     /**
128      * Adds Tosca Policies to the DB.
129      *
130      * @param yamlFile name of the YAML file specifying the data to be loaded
131      */
132     public void addToscaPolicies(final String yamlFile) {
133         final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
134         JpaToscaServiceTemplate jpaToscaServiceTemplate = mergeWithExistingTemplate(serviceTemplate);
135         serviceTemplateRepository.save(jpaToscaServiceTemplate);
136     }
137
138     private JpaToscaServiceTemplate mergeWithExistingTemplate(ToscaServiceTemplate serviceTemplate) {
139         JpaToscaServiceTemplate jpaToscaServiceTemplate = new JpaToscaServiceTemplate(serviceTemplate);
140         Optional<JpaToscaServiceTemplate> dbServiceTemplateOpt = serviceTemplateRepository
141             .findById(new PfConceptKey(JpaToscaServiceTemplate.DEFAULT_NAME, JpaToscaServiceTemplate.DEFAULT_VERSION));
142         if (dbServiceTemplateOpt.isPresent()) {
143             JpaToscaServiceTemplate dbServiceTemplate = dbServiceTemplateOpt.get();
144             if (dbServiceTemplate.getPolicyTypes() != null) {
145                 jpaToscaServiceTemplate.setPolicyTypes(dbServiceTemplate.getPolicyTypes());
146             }
147             if (dbServiceTemplate.getDataTypes() != null) {
148                 jpaToscaServiceTemplate.setDataTypes(dbServiceTemplate.getDataTypes());
149             }
150             if (dbServiceTemplate.getTopologyTemplate() != null) {
151                 jpaToscaServiceTemplate.setTopologyTemplate(dbServiceTemplate.getTopologyTemplate());
152             }
153         }
154
155         return jpaToscaServiceTemplate;
156     }
157
158     /**
159      * Adds PDP groups to the DB.
160      *
161      * @param jsonFile name of the JSON file specifying the data to be loaded
162      */
163     public void addGroups(final String jsonFile) {
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         pdpGroupService.createPdpGroups(groups.getGroups());
172     }
173
174     /**
175      * Fetch PDP groups from the DB.
176      *
177      * @param name name of the pdpGroup
178      */
179     public List<PdpGroup> fetchGroups(final String name) {
180         return pdpGroupService.getPdpGroups(name);
181     }
182
183     /**
184      * Adds PdpPolicyStatus records to the DB.
185      *
186      * @param jsonFile name of the JSON file specifying the data to be loaded
187      */
188     public void addPdpPolicyStatus(final String jsonFile) {
189         final PolicyStatusRecords data = loadJsonFile(jsonFile, PolicyStatusRecords.class);
190         policyStatusService.cudPolicyStatus(data.records, null, null);
191     }
192
193     /**
194      * Loads an object from a YAML file.
195      *
196      * @param fileName name of the file from which to load
197      * @param clazz    the class of the object to be loaded
198      * @return the object that was loaded from the file
199      */
200     protected static <T> T loadYamlFile(final String fileName, final Class<T> clazz) {
201         final File propFile = new File(ResourceUtils.getFilePath4Resource("e2e/" + fileName));
202
203         try (FileInputStream input = new FileInputStream(propFile)) {
204             final Object yamlObject = yaml.load(input);
205             final String json = coder.encode(yamlObject);
206             final T result = coder.decode(json, clazz);
207
208             if (result == null) {
209                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
210             }
211
212             return result;
213
214         } catch (final FileNotFoundException e) {
215             throw new PolicyPapRuntimeException("cannot find " + fileName, e);
216
217         } catch (IOException | CoderException e) {
218             throw new PolicyPapRuntimeException("cannot decode " + fileName, e);
219         }
220     }
221
222     /**
223      * Loads an object from a JSON file.
224      *
225      * @param fileName name of the file from which to load
226      * @param clazz    the class of the object to be loaded
227      * @return the object that was loaded from the file
228      */
229     protected static <T> T loadJsonFile(final String fileName, final Class<T> clazz) {
230         final String fileName2 = (fileName.startsWith("src/") ? fileName : "e2e/" + fileName);
231         final File propFile = new File(ResourceUtils.getFilePath4Resource(fileName2));
232         try {
233             final T result = coder.decode(propFile, clazz);
234
235             if (result == null) {
236                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
237             }
238
239             return result;
240
241         } catch (final CoderException e) {
242             throw new RuntimeException(e);
243         }
244     }
245
246     public class PolicyStatusRecords {
247         private List<PdpPolicyStatus> records;
248     }
249 }