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