fea434cf997d7bb1a49aea28c086dc4cf1c8061e
[policy/apex-pdp.git] / services / services-engine / src / test / java / org / onap / policy / apex / service / engine / event / JsonEventHandlerTest.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.service.engine.event;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertNull;
27 import static org.junit.Assert.assertTrue;
28 import static org.junit.Assert.fail;
29
30 import java.io.ByteArrayInputStream;
31 import java.io.IOException;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35
36 import org.junit.AfterClass;
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.SchemaParameters;
41 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
42 import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
43 import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
44 import org.onap.policy.apex.model.basicmodel.service.ModelService;
45 import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
46 import org.onap.policy.apex.model.eventmodel.concepts.AxEvents;
47 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
48 import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.Apex2JsonEventConverter;
49 import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters;
50 import org.onap.policy.common.parameters.ParameterService;
51 import org.onap.policy.common.utils.resources.TextFileUtils;
52 import org.slf4j.ext.XLogger;
53 import org.slf4j.ext.XLoggerFactory;
54
55 /**
56  * Test JSON Event Handler.
57  *
58  * @author Liam Fallon (liam.fallon@ericsson.com)
59  */
60 public class JsonEventHandlerTest {
61     private static final XLogger logger = XLoggerFactory.getXLogger(JsonEventHandlerTest.class);
62
63     /**
64      * Setup event model.
65      *
66      * @throws IOException Signals that an I/O exception has occurred.
67      * @throws ApexModelException the apex model exception
68      */
69     @BeforeClass
70     public static void setupEventModel() throws IOException, ApexModelException {
71         final String policyModelString =
72                 TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModel.json");
73         final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<AxPolicyModel>(AxPolicyModel.class);
74         final AxPolicyModel apexPolicyModel = modelReader.read(new ByteArrayInputStream(policyModelString.getBytes()));
75
76         // Set up the models in the model service
77         apexPolicyModel.register();
78     }
79
80     /**
81      * Initialize default schema parameters.
82      */
83     @BeforeClass
84     public static void initializeDefaultSchemaParameters() {
85         ParameterService.clear();
86         final SchemaParameters schemaParameters = new SchemaParameters();
87         schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME);
88         ParameterService.register(schemaParameters);
89     }
90
91     /**
92      * Teardown default schema parameters.
93      */
94     @AfterClass
95     public static void teardownDefaultSchemaParameters() {
96         ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME);
97         ModelService.clear();
98     }
99
100     /**
101      * Test JSON to apex event.
102      *
103      * @throws ApexException the apex exception
104      */
105     @Test
106     public void testJsontoApexEvent() throws ApexException {
107         try {
108             final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter();
109             assertNotNull(jsonEventConverter);
110             jsonEventConverter.init(new JsonEventProtocolParameters());
111
112             final String apexEventJsonStringIn = SupportJsonEventGenerator.jsonEvent();
113
114             logger.debug("input event\n" + apexEventJsonStringIn);
115
116             final List<ApexEvent> apexEventList = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
117             for (final ApexEvent apexEvent : apexEventList) {
118                 assertNotNull(apexEvent);
119
120                 logger.debug(apexEvent.toString());
121
122                 assertEquals("BasicEvent", apexEvent.getName());
123                 assertEquals("0.0.1", apexEvent.getVersion());
124                 assertEquals("org.onap.policy.apex.events", apexEvent.getNameSpace());
125                 assertEquals("test", apexEvent.getSource());
126                 assertEquals("apex", apexEvent.getTarget());
127                 assertEquals(12345, apexEvent.get("intPar"));
128
129                 final Object testMatchCaseSelected = apexEvent.get("TestMatchCaseSelected");
130                 assertNull(testMatchCaseSelected);
131             }
132         } catch (final Exception e) {
133             e.printStackTrace();
134             throw new ApexException("Exception reading Apex event JSON file", e);
135         }
136     }
137
138     /**
139      * Test JSON to apex bad event.
140      *
141      * @throws ApexException the apex exception
142      */
143     @Test
144     public void testJsontoApexBadEvent() throws ApexException {
145         try {
146             final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter();
147             assertNotNull(jsonEventConverter);
148             jsonEventConverter.init(new JsonEventProtocolParameters());
149
150             String apexEventJsonStringIn = null;
151
152             try {
153                 apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoName();
154                 jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
155                 fail("Test should throw an exception here");
156             } catch (final ApexEventException e) {
157                 assertEquals("Failed to unmarshal JSON event: event received without mandatory parameter \"name\" ",
158                         e.getMessage().substring(0, 82));
159             }
160
161             try {
162                 apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventBadName();
163                 jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
164                 fail("Test should throw an exception here");
165             } catch (final ApexEventException e) {
166                 assertEquals("Failed to unmarshal JSON event: field \"name\" with value \"%%%%\" is invalid",
167                         e.getMessage().substring(0, 73));
168             }
169
170             try {
171                 apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoExName();
172                 jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
173                 fail("Test should throw an exception here");
174             } catch (final ApexEventException e) {
175                 assertEquals("Failed to unmarshal JSON event: an event definition for an event named \"I_DONT_EXI",
176                         e.getMessage().substring(0, 82));
177             }
178
179             apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoVersion();
180             ApexEvent event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0);
181             assertEquals("0.0.1", event.getVersion());
182
183             try {
184                 apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventBadVersion();
185                 jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
186                 fail("Test should throw an exception here");
187             } catch (final ApexEventException e) {
188                 assertEquals("Failed to unmarshal JSON event: field \"version\" with value \"#####\" is invalid",
189                         e.getMessage().substring(0, 77));
190             }
191
192             try {
193                 apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoExVersion();
194                 jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
195                 fail("Test should throw an exception here");
196             } catch (final ApexEventException e) {
197                 assertEquals(
198                         "Failed to unmarshal JSON event: an event definition for an event named "
199                                 + "\"BasicEvent\" with version \"1.2.3\" not found in Apex model",
200                         e.getMessage().substring(0, 128));
201             }
202
203             apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoNamespace();
204             event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0);
205             assertEquals("org.onap.policy.apex.events", event.getNameSpace());
206
207             try {
208                 apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventBadNamespace();
209                 jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
210                 fail("Test should throw an exception here");
211             } catch (final ApexEventException e) {
212                 assertEquals(
213                         "Failed to unmarshal JSON event: " + "field \"nameSpace\" with value \"hello.&&&&\" is invalid",
214                         e.getMessage().substring(0, 84));
215             }
216
217             try {
218                 apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoExNamespace();
219                 jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
220                 fail("Test should throw an exception here");
221             } catch (final ApexEventException e) {
222                 assertEquals("Failed to unmarshal JSON event: namespace \"pie.in.the.sky\" "
223                         + "on event \"BasicEvent\" does not" + " match namespace \"org.onap.policy.apex.events\" "
224                         + "for that event in the Apex model", e.getMessage().substring(0, 168));
225             }
226
227             apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoSource();
228             event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0);
229             assertEquals("source", event.getSource());
230
231             try {
232                 apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventBadSource();
233                 jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
234                 fail("Test should throw an exception here");
235             } catch (final ApexEventException e) {
236                 assertEquals("Failed to unmarshal JSON event: field \"source\" with value \"%!@**@!\" is invalid",
237                         e.getMessage().substring(0, 78));
238             }
239
240             apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNoTarget();
241             event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0);
242             assertEquals("target", event.getTarget());
243
244             try {
245                 apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventBadTarget();
246                 jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
247                 fail("Test should throw an exception here");
248             } catch (final ApexEventException e) {
249                 assertEquals("Failed to unmarshal JSON event: field \"target\" with value \"KNIO(*S)A(S)D\" is invalid",
250                         e.getMessage().substring(0, 84));
251             }
252
253             try {
254                 apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventMissingFields();
255                 jsonEventConverter.toApexEvent(null, apexEventJsonStringIn);
256                 fail("Test should throw an exception here");
257             } catch (final ApexEventException e) {
258                 assertEquals(
259                         "Failed to unmarshal JSON event: error parsing BasicEvent:0.0.1 "
260                                 + "event from Json. Field \"intPar\" is missing, but is mandatory.",
261                         e.getMessage().substring(0, 124));
262             }
263
264             apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventNullFields();
265             event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0);
266             assertEquals(null, event.get("TestSlogan"));
267             assertEquals(-1, event.get("intPar"));
268
269             // Set the missing fields as optional in the model
270             final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get("BasicEvent");
271             eventDefinition.getParameterMap().get("intPar").setOptional(true);
272
273             apexEventJsonStringIn = SupportJsonEventGenerator.jsonEventMissingFields();
274             event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn).get(0);
275             assertEquals(null, event.get("TestSlogan"));
276             assertEquals(null, event.get("intPar"));
277         } catch (final Exception e) {
278             e.printStackTrace();
279             throw new ApexException("Exception reading Apex event JSON file", e);
280         }
281     }
282
283     /**
284      * Test apex event to JSON.
285      *
286      * @throws ApexException the apex exception
287      */
288     @Test
289     public void testApexEventToJson() throws ApexException {
290         try {
291             final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter();
292             jsonEventConverter.init(new JsonEventProtocolParameters());
293             assertNotNull(jsonEventConverter);
294
295             final Map<String, Object> basicEventMap = new HashMap<String, Object>();
296             basicEventMap.put("intPar", 12345);
297
298             final ApexEvent basicEvent =
299                     new ApexEvent("BasicEvent", "0.0.1", "org.onap.policy.apex.events", "test", "apex");
300             basicEvent.putAll(basicEventMap);
301
302             final String apexEvent0000JsonString = (String) jsonEventConverter.fromApexEvent(basicEvent);
303
304             logger.debug(apexEvent0000JsonString);
305
306             assertTrue(apexEvent0000JsonString.contains("\"name\": \"BasicEvent\""));
307             assertTrue(apexEvent0000JsonString.contains("\"version\": \"0.0.1\""));
308             assertTrue(apexEvent0000JsonString.contains("\"nameSpace\": \"org.onap.policy.apex.events\""));
309             assertTrue(apexEvent0000JsonString.contains("\"source\": \"test\""));
310             assertTrue(apexEvent0000JsonString.contains("\"target\": \"apex\""));
311             assertTrue(apexEvent0000JsonString.contains("\"intPar\": 12345"));
312         } catch (final Exception e) {
313             e.printStackTrace();
314             throw new ApexException("Exception reading Apex event JSON file", e);
315         }
316     }
317 }