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