Changes for checkstyle 8.32
[policy/apex-pdp.git] / testsuites / integration / integration-uservice-test / src / test / java / org / onap / policy / apex / testsuites / integration / uservice / engine / ApexServiceModelUpdateTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.testsuites.integration.uservice.engine;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28
29 import java.io.ByteArrayOutputStream;
30 import java.io.IOException;
31 import java.util.Date;
32 import java.util.HashMap;
33 import java.util.Map;
34 import org.junit.After;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.onap.policy.apex.context.parameters.ContextParameterConstants;
38 import org.onap.policy.apex.context.parameters.ContextParameters;
39 import org.onap.policy.apex.context.parameters.DistributorParameters;
40 import org.onap.policy.apex.context.parameters.LockManagerParameters;
41 import org.onap.policy.apex.context.parameters.PersistorParameters;
42 import org.onap.policy.apex.context.parameters.SchemaParameters;
43 import org.onap.policy.apex.core.engine.EngineParameterConstants;
44 import org.onap.policy.apex.core.engine.EngineParameters;
45 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
46 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
47 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
48 import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
49 import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
50 import org.onap.policy.apex.model.basicmodel.service.ModelService;
51 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
52 import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters;
53 import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters;
54 import org.onap.policy.apex.service.engine.event.ApexEvent;
55 import org.onap.policy.apex.service.engine.event.ApexEventException;
56 import org.onap.policy.apex.service.engine.runtime.ApexEventListener;
57 import org.onap.policy.apex.service.engine.runtime.EngineService;
58 import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface;
59 import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl;
60 import org.onap.policy.apex.service.parameters.ApexParameterConstants;
61 import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters;
62 import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory;
63 import org.onap.policy.common.parameters.ParameterService;
64 import org.slf4j.ext.XLogger;
65 import org.slf4j.ext.XLoggerFactory;
66
67 /**
68  * The Class ApexServiceTest.
69  *
70  * @author Liam Fallon (liam.fallon@ericsson.com)
71  */
72 public class ApexServiceModelUpdateTest {
73     // Logger for this class
74     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServiceModelUpdateTest.class);
75
76     private final AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0");
77     private final EngineServiceParameters parameters = new EngineServiceParameters();
78     private EngineService service = null;
79     private TestListener listener = null;
80     private int actionEventsReceived = 0;
81
82     private AxPolicyModel apexSamplePolicyModel = null;
83     private String apexSampleModelString;
84
85     /**
86      * Set up parameters.
87      */
88     @Before
89     public void setupParameters() {
90         ParameterService.register(new SchemaParameters());
91         ParameterService.register(new ContextParameters());
92         ParameterService.register(new DistributorParameters());
93         ParameterService.register(new LockManagerParameters());
94         ParameterService.register(new PersistorParameters());
95         ParameterService.register(new EngineServiceParameters());
96
97         EngineParameters engineParameters = new EngineParameters();
98         engineParameters.getExecutorParameterMap().put("JAVASCRIPT", new JavascriptExecutorParameters());
99         ParameterService.register(engineParameters);
100     }
101
102     /**
103      * Clear down parameters.
104      */
105     @After
106     public void teardownParameters() {
107         ParameterService.deregister(EngineParameterConstants.MAIN_GROUP_NAME);
108         ParameterService.deregister(ApexParameterConstants.ENGINE_SERVICE_GROUP_NAME);
109         ParameterService.deregister(ContextParameterConstants.PERSISTENCE_GROUP_NAME);
110         ParameterService.deregister(ContextParameterConstants.LOCKING_GROUP_NAME);
111         ParameterService.deregister(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME);
112         ParameterService.deregister(ContextParameterConstants.MAIN_GROUP_NAME);
113         ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME);
114     }
115
116     /**
117      * Sets up the test by creating an engine and reading in the test policy.
118      *
119      * @throws ApexException if something goes wrong
120      * @throws IOException on IO exceptions
121      */
122     @Before
123     public void setUp() throws ApexException, IOException {
124         // create engine with 3 threads
125         parameters.setInstanceCount(3);
126         parameters.setName(engineServiceKey.getName());
127         parameters.setVersion(engineServiceKey.getVersion());
128         parameters.setId(100);
129         parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters());
130         service = EngineServiceImpl.create(parameters);
131
132         LOGGER.debug("Running TestApexEngine. . .");
133
134         apexSamplePolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JAVASCRIPT");
135         assertNotNull(apexSamplePolicyModel);
136
137         apexSampleModelString = getModelString(apexSamplePolicyModel);
138
139         // create engine
140         listener = new TestListener();
141         service.registerActionListener("MyListener", listener);
142     }
143
144     /**
145      * Tear down the the test infrastructure.
146      *
147      * @throws ApexException if there is an error
148      */
149     @After
150     public void tearDown() throws Exception {
151         if (service != null) {
152             service.stop();
153         }
154         service = null;
155     }
156
157     /**
158      * Test start with no model.
159      */
160     @Test
161     public void testNoModelStart() {
162         try {
163             service.startAll();
164             fail("Engine should not start with no model");
165         } catch (final Exception e) {
166             e.printStackTrace();
167             assertEquals("start()<-Machine-1_process-1_engine-1-0:0.0.0,STOPPED,  cannot start engine, "
168                     + "engine has not been initialized, its model is not loaded", e.getMessage());
169         }
170     }
171
172     /**
173      * Test model update with string model without force.
174      *
175      * @throws ApexException if there is an error
176      */
177     @Test
178     public void testModelUpdateStringNewNoForce() throws ApexException {
179         service.updateModel(parameters.getEngineKey(), apexSampleModelString, false);
180
181         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
182     }
183
184     /**
185      * Test model update with string model with force.
186      *
187      * @throws ApexException if there is an error
188      */
189     @Test
190     public void testModelUpdateStringNewForce() throws ApexException {
191         service.updateModel(parameters.getEngineKey(), apexSampleModelString, true);
192
193         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
194     }
195
196     /**
197      * Test model update with a new string model without force.
198      *
199      * @throws ApexException if there is an error
200      */
201     @Test
202     public void testModelUpdateStringNewNewNoForce() throws ApexException {
203         service.updateModel(parameters.getEngineKey(), apexSampleModelString, false);
204
205         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
206
207         sendEvents();
208
209         service.updateModel(parameters.getEngineKey(), apexSampleModelString, false);
210         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
211
212         sendEvents();
213     }
214
215     /**
216      * Test incompatible model update with a model object without force.
217      *
218      * @throws ApexException if there is an error
219      */
220     @Test
221     public void testModelUpdateIncoNoForce() throws ApexException {
222         service.updateModel(parameters.getEngineKey(), apexSamplePolicyModel, false);
223
224         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
225
226         // Different model name, incompatible
227         final AxPolicyModel incoPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel);
228         incoPolicyModel0.getKey().setName("INCOMPATIBLE");
229
230         try {
231             service.updateModel(parameters.getEngineKey(), incoPolicyModel0, false);
232             fail("model update should fail on incompatible model without force being true");
233         } catch (final Exception e) {
234             System.err.println(e.getMessage());
235             assertEquals("apex model update failed, supplied model with key \"INCOMPATIBLE:0.0.1\" is not a compatible "
236                     + "model update from the existing engine model " + "with key \"SamplePolicyModelJAVASCRIPT:0.0.1\"",
237                     e.getMessage());
238         }
239
240         // Still on old model
241         sendEvents();
242
243         // Different major version, incompatible
244         final AxPolicyModel incoPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel);
245         incoPolicyModel1.getKey().setVersion("1.0.1");
246
247         try {
248             service.updateModel(parameters.getEngineKey(), incoPolicyModel1, false);
249             fail("model update should fail on incompatible model without force being true");
250         } catch (final Exception e) {
251             System.err.println(e.getMessage());
252             e.printStackTrace();
253             assertEquals("apex model update failed, supplied model with key \"SamplePolicyModelJAVASCRIPT:1.0.1\" "
254                     + "is not a compatible model update from the existing engine model with key "
255                     + "\"SamplePolicyModelJAVASCRIPT:0.0.1\"", e.getMessage());
256         }
257
258         // Still on old model
259         sendEvents();
260
261         // Different minor version, compatible
262         final AxPolicyModel coPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel);
263         coPolicyModel0.getKey().setVersion("0.1.0");
264         service.updateModel(parameters.getEngineKey(), coPolicyModel0, false);
265
266         // On new compatible model
267         sendEvents();
268
269         // Different patch version, compatible
270         final AxPolicyModel coPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel);
271         coPolicyModel1.getKey().setVersion("0.0.2");
272         service.updateModel(parameters.getEngineKey(), coPolicyModel1, false);
273
274         // On new compatible model
275         sendEvents();
276
277     }
278
279     /**
280      * Test incompatible model update with a model object with force.
281      *
282      * @throws ApexException if there is an error
283      */
284     @Test
285     public void testModelUpdateIncoForce() throws ApexException {
286         service.updateModel(parameters.getEngineKey(), apexSamplePolicyModel, false);
287
288         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
289
290         // Different model name, incompatible
291         final AxPolicyModel incoPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel);
292         incoPolicyModel0.getKey().setName("INCOMPATIBLE");
293         service.updateModel(parameters.getEngineKey(), incoPolicyModel0, true);
294
295         // On updated model
296         sendEvents();
297
298         // Different major version, incompatible
299         final AxPolicyModel incoPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel);
300         incoPolicyModel1.getKey().setVersion("1.0.1");
301         service.updateModel(parameters.getEngineKey(), incoPolicyModel1, true);
302
303         // On updated model
304         sendEvents();
305
306         // Different minor version, compatible
307         final AxPolicyModel coPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel);
308         coPolicyModel0.getKey().setVersion("0.1.0");
309         service.updateModel(parameters.getEngineKey(), coPolicyModel0, true);
310
311         // On new compatible model
312         sendEvents();
313
314         // Different patch version, compatible
315         final AxPolicyModel coPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel);
316         coPolicyModel1.getKey().setVersion("0.0.2");
317         service.updateModel(parameters.getEngineKey(), coPolicyModel1, true);
318
319         // On new compatible model
320         sendEvents();
321
322     }
323
324     /**
325      * Utility method to send some events into the test engine.
326      *
327      * @throws ApexEventException if there is an error
328      */
329     private void sendEvents() throws ApexEventException {
330         final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface();
331
332         // Send some events
333         final Date testStartTime = new Date();
334         final Map<String, Object> eventDataMap = new HashMap<String, Object>();
335         eventDataMap.put("TestSlogan", "This is a test slogan");
336         eventDataMap.put("TestMatchCase", (byte) 123);
337         eventDataMap.put("TestTimestamp", testStartTime.getTime());
338         eventDataMap.put("TestTemperature", 34.5445667);
339
340         final ApexEvent event =
341                 new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
342         event.putAll(eventDataMap);
343         engineServiceEventInterface.sendEvent(event);
344
345         final ApexEvent event2 =
346                 new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
347         event2.putAll(eventDataMap);
348         engineServiceEventInterface.sendEvent(event2);
349
350         // Wait for results
351         while (actionEventsReceived < 2) {
352             ThreadUtilities.sleep(100);
353         }
354         ThreadUtilities.sleep(500);
355     }
356
357     /**
358      * The listener interface for receiving test events. The class that is interested in processing a test event
359      * implements this interface, and the object created with that class is registered with a component using the
360      * component's <code>addTestListener</code> method. When the test event occurs, that object's appropriate method is
361      * invoked.
362      *
363      * @see TestEvent
364      */
365     private final class TestListener implements ApexEventListener {
366
367         /**
368          * {@inheritDoc}.
369          */
370         @Override
371         public synchronized void onApexEvent(final ApexEvent event) {
372             LOGGER.debug("result 1 is:" + event);
373             checkResult(event);
374             actionEventsReceived++;
375
376             final Date testStartTime = new Date((Long) event.get("TestTimestamp"));
377             final Date testEndTime = new Date();
378
379             LOGGER.info("policy execution time: " + (testEndTime.getTime() - testStartTime.getTime()) + "ms");
380         }
381
382         /**
383          * Check result.
384          *
385          * @param result the result
386          */
387         private void checkResult(final ApexEvent result) {
388             assertTrue(result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104"));
389
390             assertTrue(result.get("TestSlogan").equals("This is a test slogan"));
391             assertTrue(result.get("TestMatchCase").equals((byte) 123));
392             assertTrue(result.get("TestTemperature").equals(34.5445667));
393             assertTrue(((byte) result.get("TestMatchCaseSelected")) >= 0
394                     && ((byte) result.get("TestMatchCaseSelected") <= 3));
395             assertTrue(((byte) result.get("TestEstablishCaseSelected")) >= 0
396                     && ((byte) result.get("TestEstablishCaseSelected") <= 3));
397             assertTrue(((byte) result.get("TestDecideCaseSelected")) >= 0
398                     && ((byte) result.get("TestDecideCaseSelected") <= 3));
399             assertTrue(
400                     ((byte) result.get("TestActCaseSelected")) >= 0 && ((byte) result.get("TestActCaseSelected") <= 3));
401         }
402     }
403
404     /**
405      * Gets the model string.
406      *
407      * @param policyModel the eca policy model
408      * @return the model string
409      * @throws ApexModelException the apex model exception
410      * @throws IOException Signals that an I/O exception has occurred.
411      */
412     private String getModelString(final AxPolicyModel policyModel) throws ApexModelException, IOException {
413         try (final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream()) {
414             new ApexModelWriter<AxPolicyModel>(AxPolicyModel.class).write(policyModel, baOutputStream);
415             return baOutputStream.toString();
416         }
417     }
418 }