Fix minor warnings in code
[policy/apex-pdp.git] / services / services-engine / src / test / java / org / onap / policy / apex / service / engine / runtime / impl / EngineWorkerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020,2022 Nordix Foundation.
5  *  Modifications Copyright (C) 2021-2022 Bell Canada Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.apex.service.engine.runtime.impl;
24
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertFalse;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.assertTrue;
30 import static org.junit.Assert.fail;
31
32 import java.io.ByteArrayInputStream;
33 import java.io.IOException;
34 import java.util.concurrent.BlockingQueue;
35 import java.util.concurrent.LinkedBlockingQueue;
36 import org.junit.After;
37 import org.junit.AfterClass;
38 import org.junit.BeforeClass;
39 import org.junit.Test;
40 import org.onap.policy.apex.context.parameters.ContextParameterConstants;
41 import org.onap.policy.apex.context.parameters.ContextParameters;
42 import org.onap.policy.apex.context.parameters.DistributorParameters;
43 import org.onap.policy.apex.context.parameters.LockManagerParameters;
44 import org.onap.policy.apex.context.parameters.PersistorParameters;
45 import org.onap.policy.apex.context.parameters.SchemaParameters;
46 import org.onap.policy.apex.core.engine.EngineParameterConstants;
47 import org.onap.policy.apex.core.engine.EngineParameters;
48 import org.onap.policy.apex.core.engine.ExecutorParameters;
49 import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
50 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
51 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
52 import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
53 import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
54 import org.onap.policy.apex.model.basicmodel.service.ModelService;
55 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
56 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
57 import org.onap.policy.apex.service.engine.event.ApexEvent;
58 import org.onap.policy.apex.service.engine.main.ApexPolicyStatisticsManager;
59 import org.onap.policy.common.parameters.ParameterService;
60 import org.onap.policy.common.utils.resources.TextFileUtils;
61 import org.onap.policy.common.utils.services.Registry;
62
63 /**
64  * Test the engine worker class.
65  */
66 public class EngineWorkerTest {
67     private final ApplicationThreadFactory atFactory = new ApplicationThreadFactory("apex-engine-service", 512);
68
69     private static String simpleModelString;
70     private static String differentModelString;
71     private static AxPolicyModel simpleModel;
72
73     /**
74      * Read the models into strings.
75      *
76      * @throws IOException on model reading errors
77      * @throws ApexModelException on model reading exceptions
78      */
79     @BeforeClass
80     public static void readSimpleModel() throws IOException, ApexModelException {
81         simpleModelString = TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModel.json");
82
83         differentModelString =
84                 TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModelDifferent.json");
85
86         final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class);
87         simpleModel = modelReader.read(new ByteArrayInputStream(simpleModelString.getBytes()));
88     }
89
90     /**
91      * Initialize default parameters.
92      */
93     @BeforeClass
94     public static void initializeDefaultParameters() {
95         ParameterService.clear();
96         final SchemaParameters schemaParameters = new SchemaParameters();
97         schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME);
98         ParameterService.register(schemaParameters);
99
100         final ContextParameters contextParameters = new ContextParameters();
101         contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME);
102         ParameterService.register(contextParameters);
103
104         final DistributorParameters distributorParameters = new DistributorParameters();
105         distributorParameters.setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME);
106         ParameterService.register(distributorParameters);
107
108         final LockManagerParameters lockManagerParameters = new LockManagerParameters();
109         lockManagerParameters.setName(ContextParameterConstants.LOCKING_GROUP_NAME);
110         ParameterService.register(lockManagerParameters);
111
112         final PersistorParameters persistorParameters = new PersistorParameters();
113         persistorParameters.setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME);
114         ParameterService.register(persistorParameters);
115
116         final EngineParameters engineParameters = new EngineParameters();
117         engineParameters.setName(EngineParameterConstants.MAIN_GROUP_NAME);
118         ExecutorParameters jsExecutorParameters = new ExecutorParameters();
119         jsExecutorParameters.setName("JAVASCRIPT");
120         jsExecutorParameters
121                 .setTaskSelectionExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTse");
122         jsExecutorParameters.setTaskExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTe");
123         jsExecutorParameters
124                 .setStateFinalizerExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummySfe");
125         engineParameters.getExecutorParameterMap().put("JAVASCRIPT", jsExecutorParameters);
126         ExecutorParameters mvvelExecutorParameters = new ExecutorParameters();
127         mvvelExecutorParameters.setName("MVEL");
128         mvvelExecutorParameters
129                 .setTaskSelectionExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTse");
130         mvvelExecutorParameters.setTaskExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTe");
131         mvvelExecutorParameters
132                 .setStateFinalizerExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummySfe");
133         engineParameters.getExecutorParameterMap().put("MVEL", jsExecutorParameters);
134         ParameterService.register(engineParameters);
135
136     }
137
138     /**
139      * Teardown default parameters.
140      */
141     @AfterClass
142     public static void teardownDefaultParameters() {
143         ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME);
144         ParameterService.deregister(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME);
145         ParameterService.deregister(ContextParameterConstants.LOCKING_GROUP_NAME);
146         ParameterService.deregister(ContextParameterConstants.PERSISTENCE_GROUP_NAME);
147         ParameterService.deregister(ContextParameterConstants.MAIN_GROUP_NAME);
148         ParameterService.deregister(EngineParameterConstants.MAIN_GROUP_NAME);
149     }
150
151     @After
152     public void cleardownTest() {
153         ModelService.clear();
154     }
155
156     @Test
157     public void testEngineWorker() {
158
159         BlockingQueue<ApexEvent> eventQueue = new LinkedBlockingQueue<>();
160
161         EngineWorker worker = new EngineWorker(new AxArtifactKey("Worker", "0.0.1"), eventQueue, atFactory);
162
163         try {
164             worker.registerActionListener(null, null);
165             fail("test should throw an exception");
166         } catch (Exception apEx) {
167             assertEquals("addEventListener()<-Worker:0.0.1,STOPPED, listenerName is null", apEx.getMessage());
168         }
169
170         worker.registerActionListener("DummyListener", null);
171
172         try {
173             worker.registerActionListener(null, new DummyApexEventListener());
174             fail("test should throw an exception");
175         } catch (Exception apEx) {
176             assertEquals("addEventListener()<-Worker:0.0.1,STOPPED, listenerName is null", apEx.getMessage());
177         }
178
179         worker.registerActionListener("DummyListener", new DummyApexEventListener());
180
181         try {
182             worker.deregisterActionListener(null);
183             fail("test should throw an exception");
184         } catch (Exception apEx) {
185             assertEquals("removeEventListener()<-Worker:0.0.1,STOPPED, listenerName is null", apEx.getMessage());
186         }
187
188         worker.deregisterActionListener("DummyListener");
189
190         try {
191             worker.getEngineServiceEventInterface();
192             fail("test should throw an exception");
193         } catch (Exception apEx) {
194             assertEquals("getEngineServiceEventInterface() call is not allowed on an Apex Engine Worker",
195                     apEx.getMessage());
196         }
197
198         try {
199             worker.startPeriodicEvents(100000);
200             fail("test should throw an exception");
201         } catch (Exception apEx) {
202             assertEquals("startPeriodicEvents() call is not allowed on an Apex Engine Worker", apEx.getMessage());
203         }
204
205         try {
206             worker.stopPeriodicEvents();
207             fail("test should throw an exception");
208         } catch (Exception apEx) {
209             assertEquals("stopPeriodicEvents() call is not allowed on an Apex Engine Worker", apEx.getMessage());
210         }
211
212         assertEquals("Worker:0.0.1", worker.getEngineKeys().iterator().next().getId());
213
214         assertNull(worker.getApexModelKey());
215
216         String runtimeInfo = worker.getRuntimeInfo(worker.getEngineKeys().iterator().next());
217         assertEquals("{\"TimeStamp\":", runtimeInfo.replaceAll("\\s+", "").substring(0, 13));
218
219         assertEquals(AxEngineState.STOPPED, worker.getState());
220
221         assertEquals("{\"TimeStamp\":", runtimeInfo.replaceAll("\\s+", "").substring(0, 13));
222
223         assertFalse(worker.isStarted());
224         assertFalse(worker.isStarted(null));
225         assertFalse(worker.isStarted(new AxArtifactKey("DummyKey", "0.0.1")));
226         assertFalse(worker.isStarted(worker.getEngineKeys().iterator().next()));
227         assertTrue(worker.isStopped());
228         assertTrue(worker.isStopped(null));
229         assertTrue(worker.isStopped(new AxArtifactKey("DummyKey", "0.0.1")));
230         assertTrue(worker.isStopped(worker.getEngineKeys().iterator().next()));
231
232         try {
233             worker.start(new AxArtifactKey("DummyKey", "0.0.1"));
234             fail("test should throw an exception");
235         } catch (ApexException apEx) {
236             assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
237                     apEx.getMessage());
238         }
239
240         try {
241             worker.start(worker.getEngineKeys().iterator().next());
242             fail("test should throw an exception");
243         } catch (ApexException apEx) {
244             assertEquals("start()<-Worker:0.0.1,STOPPED,  cannot start engine, engine has not been initialized, "
245                     + "its model is not loaded", apEx.getMessage());
246         }
247
248         try {
249             worker.startAll();
250             fail("test should throw an exception");
251         } catch (ApexException apEx) {
252             assertEquals("start()<-Worker:0.0.1,STOPPED,  cannot start engine, "
253                     + "engine has not been initialized, its model is not loaded", apEx.getMessage());
254         }
255
256         try {
257             worker.stop(new AxArtifactKey("DummyKey", "0.0.1"));
258             fail("test should throw an exception");
259         } catch (ApexException apEx) {
260             assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
261                     apEx.getMessage());
262         }
263
264         try {
265             worker.stop(worker.getEngineKeys().iterator().next());
266         } catch (ApexException apEx) {
267             fail("test should not throw an exception");
268         }
269
270         try {
271             worker.stop();
272         } catch (ApexException apEx) {
273             fail("test should not throw an exception");
274         }
275
276         try {
277             worker.clear(new AxArtifactKey("DummyKey", "0.0.1"));
278             fail("test should throw an exception");
279         } catch (ApexException apEx) {
280             assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
281                     apEx.getMessage());
282         }
283
284         try {
285             worker.clear(worker.getEngineKeys().iterator().next());
286         } catch (ApexException apEx) {
287             fail("test should not throw an exception");
288         }
289
290         try {
291             worker.clear();
292         } catch (ApexException apEx) {
293             fail("test should not throw an exception");
294         }
295
296         try {
297             worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), "", true);
298             fail("test should throw an exception");
299         } catch (ApexException apEx) {
300             assertEquals("failed to unmarshal the apex model on engine DummyKey:0.0.1", apEx.getMessage());
301         }
302
303         try {
304             worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), "I am not an Apex model", true);
305             fail("test should throw an exception");
306         } catch (ApexException apEx) {
307             assertEquals("failed to unmarshal the apex model on engine DummyKey:0.0.1", apEx.getMessage());
308         }
309
310         try {
311             worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), simpleModelString, true);
312             fail("test should throw an exception");
313         } catch (ApexException apEx) {
314             assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
315                     apEx.getMessage());
316         }
317
318         try {
319             worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), (AxPolicyModel) null, true);
320             fail("test should throw an exception");
321         } catch (ApexException apEx) {
322             assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
323                     apEx.getMessage());
324         }
325
326         try {
327             worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), simpleModel, true);
328             fail("test should throw an exception");
329         } catch (ApexException apEx) {
330             assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine",
331                     apEx.getMessage());
332         }
333     }
334
335     @Test
336     public void testApexImplModelWIthModel() throws ApexException {
337         Registry.newRegistry();
338         Registry.register(ApexPolicyStatisticsManager.REG_APEX_PDP_POLICY_COUNTER, new ApexPolicyStatisticsManager());
339         BlockingQueue<ApexEvent> eventQueue = new LinkedBlockingQueue<>();
340
341         EngineWorker worker = new EngineWorker(new AxArtifactKey("Worker", "0.0.1"), eventQueue, atFactory);
342         assertEquals("Worker:0.0.1", worker.getKey().getId());
343
344         try {
345             worker.updateModel(worker.getKey(), simpleModelString, false);
346         } catch (ApexException apEx) {
347             fail("test should not throw an exception");
348         }
349
350         eventQueue.add(new ApexEvent("SomeEvent", "0.0.1", "the.event.namespace", "EventSource", "EventTarget", ""));
351
352         try {
353             worker.updateModel(worker.getKey(), differentModelString, false);
354             fail("test should throw an exception");
355         } catch (ApexException apEx) {
356             assertEquals("apex model update failed, supplied model with key \"SmallModelDifferent:0.0.1\" is not a "
357                     + "compatible model update " + "from the existing engine model with key \"SmallModel:0.0.1\"",
358                     apEx.getMessage());
359         }
360
361         try {
362             worker.updateModel(worker.getKey(), differentModelString, true);
363         } catch (ApexException apEx) {
364             fail("test should not throw an exception");
365         }
366
367         try {
368             worker.updateModel(worker.getKey(), simpleModelString, true);
369         } catch (ApexException apEx) {
370             fail("test should not throw an exception");
371         }
372
373         String runtimeInfo = worker.getRuntimeInfo(worker.getEngineKeys().iterator().next());
374         assertEquals("{\"TimeStamp\":", runtimeInfo.replaceAll("\\s+", "").substring(0, 13));
375
376         assertEquals(AxEngineState.STOPPED, worker.getState());
377         worker.startAll();
378
379         assertEquals(AxEngineState.READY, worker.getState());
380
381         String status = worker.getStatus(worker.getEngineKeys().iterator().next());
382         assertEquals("{\"timestamp\":", status.replaceAll("\\s+", "").substring(0, 13));
383
384         assertTrue(worker.isStarted());
385         assertTrue(worker.isStarted(worker.getEngineKeys().iterator().next()));
386         assertFalse(worker.isStopped());
387         assertFalse(worker.isStopped(worker.getEngineKeys().iterator().next()));
388
389         try {
390             worker.start(worker.getEngineKeys().iterator().next());
391             fail("test should throw an exception");
392         } catch (ApexException apEx) {
393             assertEquals("apex engine for engine key Worker:0.0.1 is already running with state READY",
394                     apEx.getMessage());
395         }
396
397         try {
398             worker.startAll();
399             fail("test should throw an exception");
400         } catch (ApexException apEx) {
401             assertEquals("apex engine for engine key Worker:0.0.1 is already running with state READY",
402                     apEx.getMessage());
403         }
404
405         try {
406             worker.stop(worker.getEngineKeys().iterator().next());
407         } catch (ApexException apEx) {
408             fail("test should not throw an exception");
409         }
410
411         try {
412             worker.start(worker.getEngineKeys().iterator().next());
413         } catch (ApexException apEx) {
414             fail("test should not throw an exception");
415         }
416
417         try {
418             worker.stop();
419         } catch (ApexException apEx) {
420             fail("test should not throw an exception");
421         }
422
423         try {
424             worker.startAll();
425         } catch (ApexException apEx) {
426             fail("test should not throw an exception");
427         }
428
429         worker.stop();
430         worker.startAll();
431
432         try {
433             worker.clear(worker.getEngineKeys().iterator().next());
434             fail("test should throw an exception");
435         } catch (ApexException apEx) {
436             assertEquals("clear()<-Worker:0.0.1,READY, cannot clear engine, engine is not stopped", apEx.getMessage());
437         }
438
439         try {
440             worker.stop(worker.getEngineKeys().iterator().next());
441             worker.clear(worker.getEngineKeys().iterator().next());
442         } catch (ApexException apEx) {
443             fail("test should not throw an exception");
444         }
445
446         try {
447             worker.clear();
448         } catch (ApexException apEx) {
449             fail("test should not throw an exception");
450         }
451
452         assertNotNull(worker.getApexModelKey());
453
454         final ApexPolicyStatisticsManager policyCounter = ApexPolicyStatisticsManager.getInstanceFromRegistry();
455         assertNotNull(policyCounter);
456         assertEquals(policyCounter.getPolicyExecutedCount(),
457                 policyCounter.getPolicyExecutedFailCount() + policyCounter.getPolicyExecutedSuccessCount());
458     }
459 }