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 / ApexServiceTest.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.AfterClass;
36 import org.junit.Before;
37 import org.junit.BeforeClass;
38 import org.junit.Test;
39 import org.onap.policy.apex.context.parameters.ContextParameterConstants;
40 import org.onap.policy.apex.context.parameters.ContextParameters;
41 import org.onap.policy.apex.context.parameters.DistributorParameters;
42 import org.onap.policy.apex.context.parameters.LockManagerParameters;
43 import org.onap.policy.apex.context.parameters.PersistorParameters;
44 import org.onap.policy.apex.context.parameters.SchemaParameters;
45 import org.onap.policy.apex.core.engine.EngineParameterConstants;
46 import org.onap.policy.apex.core.engine.EngineParameters;
47 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
48 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
49 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
50 import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
51 import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
52 import org.onap.policy.apex.model.basicmodel.service.ModelService;
53 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
54 import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters;
55 import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters;
56 import org.onap.policy.apex.service.engine.event.ApexEvent;
57 import org.onap.policy.apex.service.engine.runtime.ApexEventListener;
58 import org.onap.policy.apex.service.engine.runtime.EngineService;
59 import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface;
60 import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl;
61 import org.onap.policy.apex.service.parameters.ApexParameterConstants;
62 import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters;
63 import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory;
64 import org.onap.policy.common.parameters.ParameterService;
65 import org.slf4j.ext.XLogger;
66 import org.slf4j.ext.XLoggerFactory;
67
68 /**
69  * The Class ApexServiceTest.
70  *
71  * @author Liam Fallon (liam.fallon@ericsson.com)
72  */
73 public class ApexServiceTest {
74     // Logger for this class
75     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServiceTest.class);
76
77     private static final long MAX_STOP_WAIT = 5000; // 5 sec
78     private static final long MAX_START_WAIT = 5000; // 5 sec
79     private static final long MAX_RECV_WAIT = 5000; // 5 sec
80
81     private static final AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0");
82     private static final EngineServiceParameters parameters = new EngineServiceParameters();
83     private static EngineService service = null;
84     private static TestListener listener = null;
85     private static AxPolicyModel apexPolicyModel = null;
86     private static int actionEventsReceived = 0;
87
88     private static String apexModelString;
89
90     private boolean waitFlag = true;
91
92     @BeforeClass
93     public static void beforeSetUp() throws Exception {
94         // create engine with 3 threads
95         parameters.setInstanceCount(3);
96         parameters.setName(engineServiceKey.getName());
97         parameters.setVersion(engineServiceKey.getVersion());
98         parameters.setId(100);
99         parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters());
100         service = EngineServiceImpl.create(parameters);
101
102         LOGGER.debug("Running TestApexEngine. . .");
103
104         apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JAVASCRIPT");
105         assertNotNull(apexPolicyModel);
106
107         apexModelString = getModelString(apexPolicyModel);
108
109         // create engine
110         listener = new TestListener();
111         service.registerActionListener("Listener", listener);
112     }
113
114     @AfterClass
115     public static void afterCleardown() throws Exception {
116         ModelService.clear();
117     }
118
119     /**
120      * Set up parameters.
121      */
122     @Before
123     public void setupParameters() {
124         ParameterService.register(new SchemaParameters());
125         ParameterService.register(new ContextParameters());
126         ParameterService.register(new DistributorParameters());
127         ParameterService.register(new LockManagerParameters());
128         ParameterService.register(new PersistorParameters());
129         ParameterService.register(new EngineServiceParameters());
130
131         EngineParameters engineParameters = new EngineParameters();
132         engineParameters.getExecutorParameterMap().put("JAVASCRIPT", new JavascriptExecutorParameters());
133         ParameterService.register(engineParameters);
134     }
135
136     /**
137      * Clear down parameters.
138      */
139     @After
140     public void teardownParameters() {
141         ParameterService.deregister(EngineParameterConstants.MAIN_GROUP_NAME);
142         ParameterService.deregister(ApexParameterConstants.ENGINE_SERVICE_GROUP_NAME);
143         ParameterService.deregister(ContextParameterConstants.PERSISTENCE_GROUP_NAME);
144         ParameterService.deregister(ContextParameterConstants.LOCKING_GROUP_NAME);
145         ParameterService.deregister(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME);
146         ParameterService.deregister(ContextParameterConstants.MAIN_GROUP_NAME);
147         ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME);
148     }
149
150     /**
151      * Update the engine then test the engine with 2 sample events.
152      *
153      * @throws ApexException if there is a problem
154      */
155     @Test
156     public void testExecutionSet1() throws ApexException {
157         service.updateModel(parameters.getEngineKey(), apexModelString, true);
158
159         final long starttime = System.currentTimeMillis();
160         for (final AxArtifactKey engineKey : service.getEngineKeys()) {
161             LOGGER.debug("{}", service.getStatus(engineKey));
162         }
163         while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) {
164             ThreadUtilities.sleep(200);
165         }
166         if (!service.isStarted()) {
167             fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms");
168         }
169
170         final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface();
171
172         // Send some events
173         final Date testStartTime = new Date();
174         final Map<String, Object> eventDataMap = new HashMap<String, Object>();
175         eventDataMap.put("TestSlogan", "This is a test slogan");
176         eventDataMap.put("TestMatchCase", (byte) 123);
177         eventDataMap.put("TestTimestamp", testStartTime.getTime());
178         eventDataMap.put("TestTemperature", 34.5445667);
179
180         final ApexEvent event =
181                 new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
182         event.setExecutionId(System.nanoTime());
183         event.putAll(eventDataMap);
184         engineServiceEventInterface.sendEvent(event);
185
186         final ApexEvent event2 =
187                 new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
188         event2.setExecutionId(System.nanoTime());
189         event2.putAll(eventDataMap);
190         engineServiceEventInterface.sendEvent(event2);
191
192         // Wait for results
193         final long recvtime = System.currentTimeMillis();
194         while (actionEventsReceived < 2 && System.currentTimeMillis() - recvtime < MAX_RECV_WAIT) {
195             ThreadUtilities.sleep(100);
196         }
197         ThreadUtilities.sleep(500);
198         assertEquals(2, actionEventsReceived);
199         actionEventsReceived = 0;
200
201         // Stop all engines on this engine service
202         final long stoptime = System.currentTimeMillis();
203         service.stop();
204         while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) {
205             ThreadUtilities.sleep(200);
206         }
207         if (!service.isStopped()) {
208             fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms");
209         }
210     }
211
212     /**
213      * Update the engine then test the engine with 2 sample events.
214      *
215      * @throws ApexException if there is a problem
216      */
217     @Test
218     public void testExecutionSet1Sync() throws ApexException {
219         service.updateModel(parameters.getEngineKey(), apexModelString, true);
220
221         final long starttime = System.currentTimeMillis();
222         for (final AxArtifactKey engineKey : service.getEngineKeys()) {
223             LOGGER.debug("{}", service.getStatus(engineKey));
224         }
225         while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) {
226             ThreadUtilities.sleep(200);
227         }
228         if (!service.isStarted()) {
229             fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms");
230         }
231
232         // Send some events
233         final Date testStartTime = new Date();
234         final Map<String, Object> eventDataMap = new HashMap<String, Object>();
235         eventDataMap.put("TestSlogan", "This is a test slogan");
236         eventDataMap.put("TestMatchCase", (byte) 123);
237         eventDataMap.put("TestTimestamp", testStartTime.getTime());
238         eventDataMap.put("TestTemperature", 34.5445667);
239
240         final ApexEvent event1 =
241                 new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
242         event1.putAll(eventDataMap);
243         event1.setExecutionId(System.nanoTime());
244
245         final ApexEventListener myEventListener1 = new ApexEventListener() {
246             @Override
247             public void onApexEvent(final ApexEvent responseEvent) {
248                 assertNotNull("Synchronous sendEventWait failed", responseEvent);
249                 assertEquals(event1.getExecutionId(), responseEvent.getExecutionId());
250                 waitFlag = false;
251             }
252         };
253
254         waitFlag = true;
255         service.registerActionListener("Listener1", myEventListener1);
256         service.getEngineServiceEventInterface().sendEvent(event1);
257
258         while (waitFlag) {
259             ThreadUtilities.sleep(100);
260         }
261
262         final ApexEvent event2 =
263                 new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
264         event2.setExecutionId(System.nanoTime());
265         event2.putAll(eventDataMap);
266
267         final ApexEventListener myEventListener2 = new ApexEventListener() {
268             @Override
269             public void onApexEvent(final ApexEvent responseEvent) {
270                 assertNotNull("Synchronous sendEventWait failed", responseEvent);
271                 assertEquals(event2.getExecutionId(), responseEvent.getExecutionId());
272                 assertEquals(2, actionEventsReceived);
273                 waitFlag = false;
274             }
275         };
276
277         waitFlag = true;
278         service.deregisterActionListener("Listener1");
279         service.registerActionListener("Listener2", myEventListener2);
280         service.getEngineServiceEventInterface().sendEvent(event2);
281
282         while (waitFlag) {
283             ThreadUtilities.sleep(100);
284         }
285         service.deregisterActionListener("Listener2");
286
287         actionEventsReceived = 0;
288
289         // Stop all engines on this engine service
290         final long stoptime = System.currentTimeMillis();
291         service.stop();
292         while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) {
293             ThreadUtilities.sleep(200);
294         }
295         if (!service.isStopped()) {
296             fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms");
297         }
298     }
299
300     /**
301      * Update the engine then test the engine with 2 sample events - again.
302      *
303      * @throws ApexException if there is a problem
304      */
305     @Test
306     public void testExecutionSet2() throws ApexException {
307         service.updateModel(parameters.getEngineKey(), apexModelString, true);
308
309         final long starttime = System.currentTimeMillis();
310         for (final AxArtifactKey engineKey : service.getEngineKeys()) {
311             LOGGER.debug("{}", service.getStatus(engineKey));
312         }
313         while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) {
314             ThreadUtilities.sleep(200);
315         }
316         if (!service.isStarted()) {
317             fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms");
318         }
319
320         final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface();
321
322         // Send some events
323         final Date testStartTime = new Date();
324         final Map<String, Object> eventDataMap = new HashMap<String, Object>();
325         eventDataMap.put("TestSlogan", "This is a test slogan");
326         eventDataMap.put("TestMatchCase", (byte) 123);
327         eventDataMap.put("TestTimestamp", testStartTime.getTime());
328         eventDataMap.put("TestTemperature", 34.5445667);
329
330         final ApexEvent event =
331                 new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
332         event.setExecutionId(System.nanoTime());
333         event.putAll(eventDataMap);
334         engineServiceEventInterface.sendEvent(event);
335
336         final ApexEvent event2 =
337                 new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
338         event2.setExecutionId(System.nanoTime());
339         event2.putAll(eventDataMap);
340         engineServiceEventInterface.sendEvent(event2);
341
342         // Wait for results
343         final long recvtime = System.currentTimeMillis();
344         while (actionEventsReceived < 2 && System.currentTimeMillis() - recvtime < MAX_RECV_WAIT) {
345             ThreadUtilities.sleep(100);
346         }
347         ThreadUtilities.sleep(500);
348         assertEquals(2, actionEventsReceived);
349         actionEventsReceived = 0;
350
351         // Stop all engines on this engine service
352         final long stoptime = System.currentTimeMillis();
353         service.stop();
354         while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) {
355             ThreadUtilities.sleep(200);
356         }
357         if (!service.isStopped()) {
358             fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms");
359         }
360     }
361
362     /**
363      * Update the engine then test the engine with 2 sample events - again.
364      *
365      * @throws ApexException if there is a problem
366      */
367     @Test
368     public void testExecutionSet2Sync() throws ApexException {
369         service.updateModel(parameters.getEngineKey(), apexModelString, true);
370
371         final long starttime = System.currentTimeMillis();
372         for (final AxArtifactKey engineKey : service.getEngineKeys()) {
373             LOGGER.debug("{}", service.getStatus(engineKey));
374         }
375         while (!service.isStarted() && System.currentTimeMillis() - starttime < MAX_START_WAIT) {
376             ThreadUtilities.sleep(200);
377         }
378         if (!service.isStarted()) {
379             fail("Apex Service " + service.getKey() + " failed to start after " + MAX_START_WAIT + " ms");
380         }
381
382         // Send some events
383         final Date testStartTime = new Date();
384         final Map<String, Object> eventDataMap = new HashMap<String, Object>();
385         eventDataMap.put("TestSlogan", "This is a test slogan");
386         eventDataMap.put("TestMatchCase", (byte) 123);
387         eventDataMap.put("TestTimestamp", testStartTime.getTime());
388         eventDataMap.put("TestTemperature", 34.5445667);
389
390         final ApexEvent event1 =
391                 new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
392         event1.putAll(eventDataMap);
393
394         final ApexEventListener myEventListener1 = new ApexEventListener() {
395             @Override
396             public void onApexEvent(final ApexEvent responseEvent) {
397                 assertNotNull("Synchronous sendEventWait failed", responseEvent);
398                 assertEquals(event1.getExecutionId(), responseEvent.getExecutionId());
399                 waitFlag = false;
400             }
401         };
402
403         waitFlag = true;
404         service.registerActionListener("Listener1", myEventListener1);
405         service.getEngineServiceEventInterface().sendEvent(event1);
406
407         while (waitFlag) {
408             ThreadUtilities.sleep(100);
409         }
410
411         final ApexEvent event2 =
412                 new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
413         event2.putAll(eventDataMap);
414
415         final ApexEventListener myEventListener2 = new ApexEventListener() {
416             @Override
417             public void onApexEvent(final ApexEvent responseEvent) {
418                 assertNotNull("Synchronous sendEventWait failed", responseEvent);
419                 assertEquals(event2.getExecutionId(), responseEvent.getExecutionId());
420                 waitFlag = false;
421             }
422         };
423
424         waitFlag = true;
425         service.registerActionListener("Listener2", myEventListener2);
426         service.deregisterActionListener("Listener1");
427         service.getEngineServiceEventInterface().sendEvent(event2);
428
429         while (waitFlag) {
430             ThreadUtilities.sleep(100);
431         }
432
433         service.deregisterActionListener("Listener2");
434
435         assertEquals(2, actionEventsReceived);
436
437         actionEventsReceived = 0;
438
439         // Stop all engines on this engine service
440         final long stoptime = System.currentTimeMillis();
441         service.stop();
442         while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) {
443             ThreadUtilities.sleep(200);
444         }
445         if (!service.isStopped()) {
446             fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms");
447         }
448     }
449
450     /**
451      * Tear down the the test infrastructure.
452      *
453      * @throws ApexException if there is an error
454      */
455     @AfterClass
456     public static void tearDown() throws Exception {
457         // Stop all engines on this engine service
458         final long stoptime = System.currentTimeMillis();
459         service.stop();
460         while (!service.isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT) {
461             ThreadUtilities.sleep(200);
462         }
463         if (!service.isStopped()) {
464             fail("Apex Service " + service.getKey() + " failed to stop after " + MAX_STOP_WAIT + " ms");
465         }
466         service = null;
467     }
468
469     /**
470      * The listener interface for receiving test events. The class that is interested in processing a test event
471      * implements this interface, and the object created with that class is registered with a component using the
472      * component's <code>addTestListener</code> method. When the test event occurs, that object's appropriate method is
473      * invoked.
474      *
475      * @see TestEvent
476      */
477     private static final class TestListener implements ApexEventListener {
478
479         /**
480          * {@inheritDoc}.
481          */
482         @Override
483         public synchronized void onApexEvent(final ApexEvent event) {
484             LOGGER.debug("result 1 is:" + event);
485             checkResult(event);
486             actionEventsReceived++;
487
488             final Date testStartTime = new Date((Long) event.get("TestTimestamp"));
489             final Date testEndTime = new Date();
490
491             LOGGER.debug("policy execution time: " + (testEndTime.getTime() - testStartTime.getTime()) + "ms");
492         }
493
494         /**
495          * Check result.
496          *
497          * @param result the result
498          */
499         private void checkResult(final ApexEvent result) {
500             assertTrue(result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104"));
501
502             assertTrue(result.get("TestSlogan").equals("This is a test slogan"));
503             assertTrue(result.get("TestMatchCase").equals((byte) 123));
504             assertTrue(result.get("TestTemperature").equals(34.5445667));
505             assertTrue(((byte) result.get("TestMatchCaseSelected")) >= 0
506                     && ((byte) result.get("TestMatchCaseSelected") <= 3));
507             assertTrue(((byte) result.get("TestEstablishCaseSelected")) >= 0
508                     && ((byte) result.get("TestEstablishCaseSelected") <= 3));
509             assertTrue(((byte) result.get("TestDecideCaseSelected")) >= 0
510                     && ((byte) result.get("TestDecideCaseSelected") <= 3));
511             assertTrue(
512                     ((byte) result.get("TestActCaseSelected")) >= 0 && ((byte) result.get("TestActCaseSelected") <= 3));
513         }
514     }
515
516     /**
517      * Gets the model string.
518      *
519      * @param policyModel the eca policy model
520      * @return the model string
521      * @throws ApexModelException the apex model exception
522      * @throws IOException Signals that an I/O exception has occurred.
523      */
524     private static String getModelString(final AxPolicyModel policyModel) throws ApexModelException, IOException {
525         try (final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream()) {
526             new ApexModelWriter<AxPolicyModel>(AxPolicyModel.class).write(policyModel, baOutputStream);
527             return baOutputStream.toString();
528         }
529     }
530 }