34893ca5cae75429c8755fe870931a696c130c45
[policy/apex-pdp.git] /
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.testsuites.integration.uservice.engine;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
27
28 import java.io.ByteArrayOutputStream;
29 import java.io.IOException;
30 import java.util.Date;
31 import java.util.HashMap;
32 import java.util.Map;
33
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.policymodel.concepts.AxPolicyModel;
53 import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters;
54 import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters;
55 import org.onap.policy.apex.service.engine.event.ApexEvent;
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 ApexServiceTest {
73     // Logger for this class
74     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServiceTest.class);
75
76     private static final long MAX_STOP_WAIT = 5000; // 5 sec
77     private static final long MAX_START_WAIT = 5000; // 5 sec
78     private static final long MAX_RECV_WAIT = 5000; // 5 sec
79
80     private static final AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0");
81     private static final EngineServiceParameters parameters = new EngineServiceParameters();
82     private static EngineService service = null;
83     private static TestListener listener = null;
84     private static AxPolicyModel apexPolicyModel = null;
85     private static int actionEventsReceived = 0;
86
87     private static String apexModelString;
88
89     private boolean waitFlag = true;
90
91     /**
92      * Sets the up.
93      *
94      * @throws Exception the exception
95      */
96     @BeforeClass
97     public static void setUp() throws Exception {
98         // create engine with 3 threads
99         parameters.setInstanceCount(3);
100         parameters.setName(engineServiceKey.getName());
101         parameters.setVersion(engineServiceKey.getVersion());
102         parameters.setId(100);
103         parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters());
104         service = EngineServiceImpl.create(parameters);
105
106
107         LOGGER.debug("Running TestApexEngine. . .");
108
109         apexPolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("JAVASCRIPT");
110         assertNotNull(apexPolicyModel);
111
112         apexModelString = getModelString(apexPolicyModel);
113
114         // create engine
115         listener = new TestListener();
116         service.registerActionListener("Listener", listener);
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.info("{}", 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
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.info("{}", 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.info("{}", 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.info("{}", 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
472      * a test event implements this interface, and the object created with that class is registered
473      * with a component using the component's <code>addTestListener</code> method. When the test
474      * event occurs, that object's appropriate method is 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.info("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             assertTrue(result.get("TestSlogan").equals("This is a test slogan"));
504             assertTrue(result.get("TestMatchCase").equals(new Byte((byte) 123)));
505             assertTrue(result.get("TestTemperature").equals(34.5445667));
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 }