Changes for checkstyle 8.32
[policy/apex-pdp.git] / model / basic-model / src / main / java / org / onap / policy / apex / model / basicmodel / test / TestApexModel.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  * 
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * 
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.model.basicmodel.test;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.File;
26 import java.net.URL;
27 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
28 import org.onap.policy.apex.model.basicmodel.concepts.AxModel;
29 import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
30 import org.onap.policy.apex.model.basicmodel.dao.ApexDao;
31 import org.onap.policy.apex.model.basicmodel.dao.ApexDaoFactory;
32 import org.onap.policy.apex.model.basicmodel.dao.DaoParameters;
33 import org.onap.policy.apex.model.basicmodel.handling.ApexModelFileWriter;
34 import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
35 import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
36 import org.onap.policy.common.utils.resources.ResourceUtils;
37 import org.slf4j.ext.XLogger;
38 import org.slf4j.ext.XLoggerFactory;
39
40 /**
41  * This class tests reading and writing of Apex models to file and to a database using JPA. It also tests validation of
42  * Apex models. This class is designed for use in unit tests in modules that define Apex models.
43  *
44  * @author Liam Fallon (liam.fallon@ericsson.com)
45  * @param <M> the generic type
46  */
47 public class TestApexModel<M extends AxModel> {
48     private static final String MODEL_IS_INVALID = "model is invalid ";
49     private static final String ERROR_PROCESSING_FILE = "error processing file ";
50     private static final String TEST_MODEL_UNEQUAL_STR = "test model does not equal model read from XML file ";
51     private static final String TEMP_FILE_CREATE_ERR_STR = "error creating temporary file for Apex model";
52
53     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestApexModel.class);
54
55     // The root model class that specifies the root to import and export from
56     private final Class<M> rootModelClass;
57
58     // The class that provides the model
59     private TestApexModelCreator<M> modelCreator = null;
60
61     /**
62      * Constructor, defines the subclass of {@link AxModel} that is being tested and the {@link TestApexModelCreator}
63      * object that is used to generate Apex models.
64      *
65      * @param rootModelClass the Apex model class, a sub class of {@link AxModel}
66      * @param modelCreator the @link TestApexModelCreator} that will generate Apex models of various types for testing
67      */
68     public TestApexModel(final Class<M> rootModelClass, final TestApexModelCreator<M> modelCreator) {
69         this.rootModelClass = rootModelClass;
70         this.modelCreator = modelCreator;
71     }
72
73     /**
74      * Get a test Apex model using the model creator.
75      *
76      * @return the test Apex model
77      */
78     public final M getModel() {
79         return modelCreator.getModel();
80     }
81
82     /**
83      * Test write and read in XML format.
84      *
85      * @throws ApexException on write/read errors
86      */
87     public final void testApexModelWriteReadXml() throws ApexException {
88         LOGGER.debug("running testApexModelWriteReadXML . . .");
89
90         final M model = modelCreator.getModel();
91
92         // Write the file to disk
93         File xmlFile;
94
95         try {
96             xmlFile = File.createTempFile("ApexModel", ".xml");
97             xmlFile.deleteOnExit();
98         } catch (final Exception e) {
99             LOGGER.warn(TEMP_FILE_CREATE_ERR_STR, e);
100             throw new ApexException(TEMP_FILE_CREATE_ERR_STR, e);
101         }
102         new ApexModelFileWriter<M>(true).apexModelWriteXmlFile(model, rootModelClass, xmlFile.getPath());
103
104         // Read the file from disk
105         final ApexModelReader<M> modelReader = new ApexModelReader<>(rootModelClass);
106
107         try {
108             final URL apexModelUrl = ResourceUtils.getLocalFile(xmlFile.getAbsolutePath());
109             final M fileModel = modelReader.read(apexModelUrl.openStream());
110             checkModelEquality(model, fileModel, TEST_MODEL_UNEQUAL_STR + xmlFile.getAbsolutePath());
111         } catch (final Exception e) {
112             LOGGER.warn(ERROR_PROCESSING_FILE + xmlFile.getAbsolutePath(), e);
113             throw new ApexException(ERROR_PROCESSING_FILE + xmlFile.getAbsolutePath(), e);
114         }
115
116         final ApexModelWriter<M> modelWriter = new ApexModelWriter<>(rootModelClass);
117         modelWriter.getCDataFieldSet().add("description");
118         modelWriter.getCDataFieldSet().add("logic");
119         modelWriter.getCDataFieldSet().add("uiLogic");
120
121         final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
122         modelWriter.write(model, baOutputStream);
123         final ByteArrayInputStream baInputStream = new ByteArrayInputStream(baOutputStream.toByteArray());
124         final M byteArrayModel = modelReader.read(baInputStream);
125
126         checkModelEquality(model, byteArrayModel, "test model does not equal XML marshalled and unmarshalled model");
127
128         LOGGER.debug("ran testApexModelWriteReadXML");
129     }
130
131     /**
132      * Test write and read in JSON format.
133      *
134      * @throws ApexException on write/read errors
135      */
136     public final void testApexModelWriteReadJson() throws ApexException {
137         LOGGER.debug("running testApexModelWriteReadJSON . . .");
138
139         final M model = modelCreator.getModel();
140
141         // Write the file to disk
142         File jsonFile;
143         try {
144             jsonFile = File.createTempFile("ApexModel", ".xml");
145             jsonFile.deleteOnExit();
146         } catch (final Exception e) {
147             LOGGER.warn(TEMP_FILE_CREATE_ERR_STR, e);
148             throw new ApexException(TEMP_FILE_CREATE_ERR_STR, e);
149         }
150         new ApexModelFileWriter<M>(true).apexModelWriteJsonFile(model, rootModelClass, jsonFile.getPath());
151
152         // Read the file from disk
153         final ApexModelReader<M> modelReader = new ApexModelReader<>(rootModelClass);
154
155         try {
156             final URL apexModelUrl = ResourceUtils.getLocalFile(jsonFile.getAbsolutePath());
157             final M fileModel = modelReader.read(apexModelUrl.openStream());
158             checkModelEquality(model, fileModel, TEST_MODEL_UNEQUAL_STR + jsonFile.getAbsolutePath());
159         } catch (final Exception e) {
160             LOGGER.warn(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e);
161             throw new ApexException(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e);
162         }
163
164         final ApexModelWriter<M> modelWriter = new ApexModelWriter<>(rootModelClass);
165         modelWriter.setJsonOutput(true);
166
167         final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
168         modelWriter.write(model, baOutputStream);
169         final ByteArrayInputStream baInputStream = new ByteArrayInputStream(baOutputStream.toByteArray());
170         final M byteArrayModel = modelReader.read(baInputStream);
171         
172         checkModelEquality(model, byteArrayModel, "test model does not equal JSON marshalled and unmarshalled model");
173
174         LOGGER.debug("ran testApexModelWriteReadJSON");
175     }
176
177     /**
178      * Test write and read of an Apex model to database using JPA.
179      *
180      * @param daoParameters the DAO parameters to use for JPA/JDBC
181      * @throws ApexException thrown on errors writing or reading the model to database
182      */
183     public final void testApexModelWriteReadJpa(final DaoParameters daoParameters) throws ApexException {
184         LOGGER.debug("running testApexModelWriteReadJPA . . .");
185
186         final M model = modelCreator.getModel();
187
188         final ApexDao apexDao = new ApexDaoFactory().createApexDao(daoParameters);
189         apexDao.init(daoParameters);
190
191         apexDao.create(model);
192         final M dbJpaModel = apexDao.get(rootModelClass, model.getKey());
193         apexDao.close();
194
195         checkModelEquality(model, dbJpaModel, "test model does not equal model written and read using generic JPA");
196
197         LOGGER.debug("ran testApexModelWriteReadJPA");
198     }
199
200     /**
201      * Test that an Apex model is valid.
202      *
203      * @return the result of the validation
204      * @throws ApexException thrown on errors validating the Apex model
205      */
206     public final AxValidationResult testApexModelValid() throws ApexException {
207         LOGGER.debug("running testApexModelVaid . . .");
208
209         final M model = modelCreator.getModel();
210         final AxValidationResult result = model.validate(new AxValidationResult());
211
212         if (!result.isValid()) {
213             String message = MODEL_IS_INVALID + result.toString();
214             LOGGER.warn(message);
215             throw new ApexException(message);
216         }
217
218         LOGGER.debug("ran testApexModelVaid");
219         return result;
220     }
221
222     /**
223      * Test that an Apex model is structured incorrectly.
224      *
225      * @return the result of the validation
226      * @throws ApexException thrown on errors validating the Apex model
227      */
228     public final AxValidationResult testApexModelVaidateMalstructured() throws ApexException {
229         LOGGER.debug("running testApexModelVaidateMalstructured . . .");
230
231         final M model = modelCreator.getMalstructuredModel();
232         final AxValidationResult result = model.validate(new AxValidationResult());
233
234         if (result.isValid()) {
235             String message = "model should not be valid " + result.toString();
236             LOGGER.warn(message);
237             throw new ApexException(message);
238         }
239
240         LOGGER.debug("ran testApexModelVaidateMalstructured");
241         return result;
242     }
243
244     /**
245      * Test that an Apex model has observations.
246      *
247      * @return the result of the validation
248      * @throws ApexException thrown on errors validating the Apex model
249      */
250     public final AxValidationResult testApexModelVaidateObservation() throws ApexException {
251         LOGGER.debug("running testApexModelVaidateObservation . . .");
252
253         final M model = modelCreator.getObservationModel();
254         final AxValidationResult result = model.validate(new AxValidationResult());
255
256         if (!result.isValid()) {
257             String message = MODEL_IS_INVALID + result.toString();
258             LOGGER.warn(message);
259             throw new ApexException(message);
260         }
261
262         if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.OBSERVATION)) {
263             LOGGER.warn("model should have observations");
264             throw new ApexException("model should have observations");
265         }
266
267         LOGGER.debug("ran testApexModelVaidateObservation");
268         return result;
269     }
270
271     /**
272      * Test that an Apex model has warnings.
273      *
274      * @return the result of the validation
275      * @throws ApexException thrown on errors validating the Apex model
276      */
277     public final AxValidationResult testApexModelVaidateWarning() throws ApexException {
278         LOGGER.debug("running testApexModelVaidateWarning . . .");
279
280         final M model = modelCreator.getWarningModel();
281         final AxValidationResult result = model.validate(new AxValidationResult());
282
283         if (!result.isValid()) {
284             String message = MODEL_IS_INVALID + result.toString();
285             LOGGER.warn(message);
286             throw new ApexException(message);
287         }
288
289         if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.WARNING)) {
290             LOGGER.warn("model should have warnings");
291             throw new ApexException("model should have warnings");
292         }
293
294         LOGGER.debug("ran testApexModelVaidateWarning");
295         return result;
296     }
297
298     /**
299      * Test that an Apex model is invalid.
300      *
301      * @return the result of the validation
302      * @throws ApexException thrown on errors validating the Apex model
303      */
304     public final AxValidationResult testApexModelVaidateInvalidModel() throws ApexException {
305         LOGGER.debug("running testApexModelVaidateInvalidModel . . .");
306
307         final M model = modelCreator.getInvalidModel();
308         final AxValidationResult result = model.validate(new AxValidationResult());
309
310         if (result.isValid()) {
311             String message = "model should not be valid " + result.toString();
312             LOGGER.warn(message);
313             throw new ApexException(message);
314         }
315
316         LOGGER.debug("ran testApexModelVaidateInvalidModel");
317         return result;
318     }
319
320     /**
321      * Check if two models are equal.
322      * 
323      * @param leftModel the left model
324      * @param rightModel the right model
325      * @param errorMessage the error message to output on inequality
326      * @throws ApexException the exception to throw on inequality
327      */
328     public void checkModelEquality(final M leftModel, final M rightModel, final String errorMessage)
329         throws ApexException {
330         if (!leftModel.equals(rightModel)) {
331             LOGGER.warn(errorMessage);
332             throw new ApexException(errorMessage);
333         }
334     }
335 }