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