59c9c21c1d5549d6469f17aa9c34b5a8670c2263
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019 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.plugins.event.protocol.yaml;
23
24 import java.util.ArrayList;
25 import java.util.LinkedHashMap;
26 import java.util.List;
27 import java.util.Map;
28 import org.onap.policy.apex.context.SchemaHelper;
29 import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory;
30 import org.onap.policy.apex.model.basicmodel.service.ModelService;
31 import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
32 import org.onap.policy.apex.model.eventmodel.concepts.AxEvents;
33 import org.onap.policy.apex.model.eventmodel.concepts.AxField;
34 import org.onap.policy.apex.service.engine.event.ApexEvent;
35 import org.onap.policy.apex.service.engine.event.ApexEventException;
36 import org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter;
37 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
38 import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters;
39 import org.slf4j.ext.XLogger;
40 import org.slf4j.ext.XLoggerFactory;
41 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
42 import org.yaml.snakeyaml.Yaml;
43
44 /**
45  * The Class Apex2YamlEventConverter converts {@link ApexEvent} instances to and from YAML string representations of
46  * Apex events.
47  *
48  * @author Liam Fallon (liam.fallon@ericsson.com)
49  */
50 public class Apex2YamlEventConverter implements ApexEventProtocolConverter {
51     private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2YamlEventConverter.class);
52
53     // The parameters for the YAML event protocol
54     private YamlEventProtocolParameters yamlPars;
55
56     /**
57      * {@inheritDoc}.
58      */
59     @Override
60     public void init(final EventProtocolParameters parameters) {
61         // Check and get the YAML parameters
62         if (!(parameters instanceof YamlEventProtocolParameters)) {
63             final String errorMessage = "specified consumer properties are not applicable to the YAML event protocol";
64             LOGGER.warn(errorMessage);
65             throw new ApexEventRuntimeException(errorMessage);
66         }
67
68         yamlPars = (YamlEventProtocolParameters) parameters;
69     }
70
71     /**
72      * {@inheritDoc}.
73      */
74     @Override
75     public List<ApexEvent> toApexEvent(final String eventName, final Object eventObject) throws ApexEventException {
76         // Check the event eventObject
77         if (eventObject == null) {
78             LOGGER.warn("event processing failed, event is null");
79             throw new ApexEventException("event processing failed, event is null");
80         }
81
82         // Cast the event to a string, if our conversion is correctly configured, this cast should
83         // always work
84         if (!(eventObject instanceof String)) {
85             final String errorMessage = "error converting event \"" + eventObject + "\" to a string";
86             LOGGER.debug(errorMessage);
87             throw new ApexEventException(errorMessage);
88         }
89
90         final String yamlEventString = (String) eventObject;
91
92         // The list of events we will return
93         final List<ApexEvent> eventList = new ArrayList<>();
94
95         // Convert the YAML document string into an object
96         Object yamlObject = new Yaml().load(yamlEventString);
97
98         // If the incoming YAML did not create a map it is a primitive type or a collection so we
99         // convert it into a map for processing
100         Map<?, ?> yamlMap;
101         if (yamlObject instanceof Map) {
102             // We already have a map so just cast the object
103             yamlMap = (Map<?, ?>) yamlObject;
104         } else {
105             // Create a single entry map, new map creation and assignment is to avoid a
106             // type checking warning
107             LinkedHashMap<String, Object> newYamlMap = new LinkedHashMap<>();
108             newYamlMap.put(yamlPars.getYamlFieldName(), yamlObject);
109             yamlMap = newYamlMap;
110         }
111
112         try {
113             eventList.add(yamlMap2ApexEvent(eventName, yamlMap));
114         } catch (final Exception e) {
115             throw new ApexEventException("Failed to unmarshal YAML event, event="
116                 + yamlEventString, e);
117         }
118
119         // Return the list of events we have unmarshalled
120         return eventList;
121     }
122
123     /**
124      * {@inheritDoc}.
125      */
126     @Override
127     public Object fromApexEvent(final ApexEvent apexEvent) throws ApexEventException {
128         // Check the Apex event
129         if (apexEvent == null) {
130             LOGGER.warn("event processing failed, Apex event is null");
131             throw new ApexEventException("event processing failed, Apex event is null");
132         }
133
134         // Get the event definition for the event from the model service
135         final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(apexEvent.getName(),
136                         apexEvent.getVersion());
137
138         // Create a map for output of the APEX event to YAML
139         LinkedHashMap<String, Object> yamlMap = new LinkedHashMap<>();
140
141         yamlMap.put(ApexEvent.NAME_HEADER_FIELD, apexEvent.getName());
142         yamlMap.put(ApexEvent.VERSION_HEADER_FIELD, apexEvent.getVersion());
143         yamlMap.put(ApexEvent.NAMESPACE_HEADER_FIELD, apexEvent.getNameSpace());
144         yamlMap.put(ApexEvent.SOURCE_HEADER_FIELD, apexEvent.getSource());
145         yamlMap.put(ApexEvent.TARGET_HEADER_FIELD, apexEvent.getTarget());
146
147         if (apexEvent.getExceptionMessage() != null) {
148             yamlMap.put(ApexEvent.EXCEPTION_MESSAGE_HEADER_FIELD, apexEvent.getExceptionMessage());
149         }
150
151         for (final AxField eventField : eventDefinition.getFields()) {
152             final String fieldName = eventField.getKey().getLocalName();
153
154             if (!apexEvent.containsKey(fieldName)) {
155                 if (!eventField.getOptional()) {
156                     final String errorMessage = "error parsing " + eventDefinition.getId() + " event to Json. "
157                                     + "Field \"" + fieldName + "\" is missing, but is mandatory. Fields: " + apexEvent;
158                     LOGGER.debug(errorMessage);
159                     throw new ApexEventRuntimeException(errorMessage);
160                 }
161                 continue;
162             }
163
164             yamlMap.put(fieldName, apexEvent.get(fieldName));
165         }
166
167         // Use Snake YAML to convert the APEX event to YAML
168         Yaml yaml = new Yaml();
169         return yaml.dumpAs(yamlMap, null, FlowStyle.BLOCK);
170     }
171
172     /**
173      * This method converts a YAML map into an Apex event.
174      *
175      * @param eventName the name of the event
176      * @param yamlMap the YAML map that holds the event
177      * @return the apex event that we have converted the JSON object into
178      * @throws ApexEventException thrown on unmarshaling exceptions
179      */
180     private ApexEvent yamlMap2ApexEvent(final String eventName, final Map<?, ?> yamlMap) throws ApexEventException {
181         // Process the mandatory Apex header
182         final ApexEvent apexEvent = processApexEventHeader(eventName, yamlMap);
183
184         // Get the event definition for the event from the model service
185         final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(apexEvent.getName(),
186                         apexEvent.getVersion());
187
188         // Iterate over the input fields in the event
189         for (final AxField eventField : eventDefinition.getFields()) {
190             final String fieldName = eventField.getKey().getLocalName();
191             if (!yamlMap.containsKey(fieldName)) {
192                 if (!eventField.getOptional()) {
193                     final String errorMessage = "error parsing " + eventDefinition.getId() + " event from Json. "
194                                     + "Field \"" + fieldName + "\" is missing, but is mandatory.";
195                     LOGGER.debug(errorMessage);
196                     throw new ApexEventException(errorMessage);
197                 }
198                 continue;
199             }
200
201             final Object fieldValue = getYamlField(yamlMap, fieldName, null, !eventField.getOptional());
202
203             if (fieldValue != null) {
204                 // Get the schema helper
205                 final SchemaHelper fieldSchemaHelper = new SchemaHelperFactory().createSchemaHelper(eventField.getKey(),
206                                 eventField.getSchema());
207                 apexEvent.put(fieldName, fieldSchemaHelper.createNewInstance(fieldValue));
208             } else {
209                 apexEvent.put(fieldName, null);
210             }
211         }
212         return apexEvent;
213
214     }
215
216     /**
217      * This method processes the event header of an Apex event.
218      *
219      * @param eventName the name of the event
220      * @param yamlMap the YAML map that holds the event
221      * @return an apex event constructed using the header fields of the event
222      * @throws ApexEventRuntimeException the apex event runtime exception
223      * @throws ApexEventException on invalid events with missing header fields
224      */
225     private ApexEvent processApexEventHeader(final String eventName, final Map<?, ?> yamlMap)
226                     throws ApexEventException {
227         String name = getYamlStringField(yamlMap, ApexEvent.NAME_HEADER_FIELD, yamlPars.getNameAlias(),
228                         ApexEvent.NAME_REGEXP, false);
229
230         // Check that an event name has been specified
231         if (name == null && eventName == null) {
232             throw new ApexEventRuntimeException(
233                             "event received without mandatory parameter \"name\" on configuration or on event");
234         }
235
236         // Check if an event name was specified on the event parameters
237         if (eventName != null) {
238             if (name != null && !eventName.equals(name)) {
239                 LOGGER.warn("The incoming event name \"{}\" does not match the configured event name \"{}\", "
240                                 + "using configured event name", name, eventName);
241             }
242             name = eventName;
243         }
244
245         // Now, find the event definition in the model service. If version is null, the newest event
246         // definition in the model service is used
247         String version = getYamlStringField(yamlMap, ApexEvent.VERSION_HEADER_FIELD, yamlPars.getVersionAlias(),
248                         ApexEvent.VERSION_REGEXP, false);
249         final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(name, version);
250         if (eventDefinition == null) {
251             throw new ApexEventRuntimeException("an event definition for an event named \"" + name
252                             + "\" with version \"" + version + "\" not found in Apex model");
253         }
254
255         // Use the defined event version if no version is specified on the incoming fields
256         if (version == null) {
257             version = eventDefinition.getKey().getVersion();
258         }
259
260         String namespace = getEventHeaderNamespace(yamlMap, name, eventDefinition);
261
262         String source = getEventHeaderSource(yamlMap, eventDefinition);
263
264         String target = getHeaderTarget(yamlMap, eventDefinition);
265
266         return new ApexEvent(name, version, namespace, source, target);
267     }
268
269     /**
270      * Get the event header name space.
271      *
272      * @param yamlMap the YAML map to read from
273      * @param eventDefinition the event definition
274      * @return the event header name space
275      */
276     private String getEventHeaderNamespace(final Map<?, ?> yamlMap, String name, final AxEvent eventDefinition) {
277         // Check the name space is OK if it is defined, if not, use the name space from the model
278         String namespace = getYamlStringField(yamlMap, ApexEvent.NAMESPACE_HEADER_FIELD, yamlPars.getNameSpaceAlias(),
279                         ApexEvent.NAMESPACE_REGEXP, false);
280         if (namespace != null) {
281             if (!namespace.equals(eventDefinition.getNameSpace())) {
282                 throw new ApexEventRuntimeException("namespace \"" + namespace + "\" on event \"" + name
283                                 + "\" does not match namespace \"" + eventDefinition.getNameSpace()
284                                 + "\" for that event in the Apex model");
285             }
286         } else {
287             namespace = eventDefinition.getNameSpace();
288         }
289         return namespace;
290     }
291
292     /**
293      * Get the event header source.
294      *
295      * @param yamlMap the YAML map to read from
296      * @param eventDefinition the event definition
297      * @return the event header source
298      */
299     private String getEventHeaderSource(final Map<?, ?> yamlMap, final AxEvent eventDefinition) {
300         // For source, use the defined source only if the source is not found on the incoming event
301         String source = getYamlStringField(yamlMap, ApexEvent.SOURCE_HEADER_FIELD, yamlPars.getSourceAlias(),
302                         ApexEvent.SOURCE_REGEXP, false);
303         if (source == null) {
304             source = eventDefinition.getSource();
305         }
306         return source;
307     }
308
309     /**
310      * Get the event header target.
311      *
312      * @param yamlMap the YAML map to read from
313      * @param eventDefinition the event definition
314      * @return the event header target
315      */
316     private String getHeaderTarget(final Map<?, ?> yamlMap, final AxEvent eventDefinition) {
317         // For target, use the defined source only if the source is not found on the incoming event
318         String target = getYamlStringField(yamlMap, ApexEvent.TARGET_HEADER_FIELD, yamlPars.getTargetAlias(),
319                         ApexEvent.TARGET_REGEXP, false);
320         if (target == null) {
321             target = eventDefinition.getTarget();
322         }
323         return target;
324     }
325
326     /**
327      * This method gets an event string field from a JSON object.
328      *
329      * @param yamlMap the YAML containing the YAML representation of the incoming event
330      * @param fieldName the field name to find in the event
331      * @param fieldAlias the alias for the field to find in the event, overrides the field name if it is not null
332      * @param fieldRegexp the regular expression to check the field against for validity
333      * @param mandatory true if the field is mandatory
334      * @return the value of the field in the JSON object or null if the field is optional
335      * @throws ApexEventRuntimeException the apex event runtime exception
336      */
337     private String getYamlStringField(final Map<?, ?> yamlMap, final String fieldName, final String fieldAlias,
338                     final String fieldRegexp, final boolean mandatory) {
339         // Get the YAML field for the string field
340         final Object yamlField = getYamlField(yamlMap, fieldName, fieldAlias, mandatory);
341
342         // Null strings are allowed
343         if (yamlField == null) {
344             return null;
345         }
346
347         if (!(yamlField instanceof String)) {
348             // The element is not a string so throw an error
349             throw new ApexEventRuntimeException("field \"" + fieldName + "\" with type \""
350                             + yamlField.getClass().getName() + "\" is not a string value");
351         }
352
353         final String fieldValueString = (String) yamlField;
354
355         // Is regular expression checking required
356         if (fieldRegexp == null) {
357             return fieldValueString;
358         }
359
360         // Check the event field against its regular expression
361         if (!fieldValueString.matches(fieldRegexp)) {
362             throw new ApexEventRuntimeException(
363                             "field \"" + fieldName + "\" with value \"" + fieldValueString + "\" is invalid");
364         }
365
366         return fieldValueString;
367     }
368
369     /**
370      * This method gets an event field from a YAML object.
371      *
372      * @param yamlMap the YAML containing the YAML representation of the incoming event
373      * @param fieldName the field name to find in the event
374      * @param fieldAlias the alias for the field to find in the event, overrides the field name if it is not null
375      * @param mandatory true if the field is mandatory
376      * @return the value of the field in the YAML object or null if the field is optional
377      * @throws ApexEventRuntimeException the apex event runtime exception
378      */
379     private Object getYamlField(final Map<?, ?> yamlMap, final String fieldName, final String fieldAlias,
380                     final boolean mandatory) {
381
382         // Check if we should use the alias for this field
383         String fieldToFind = fieldName;
384         if (fieldAlias != null) {
385             fieldToFind = fieldAlias;
386         }
387
388         // Get the event field
389         final Object eventElement = yamlMap.get(fieldToFind);
390         if (eventElement == null) {
391             if (!mandatory) {
392                 return null;
393             } else {
394                 throw new ApexEventRuntimeException("mandatory field \"" + fieldToFind + "\" is missing");
395             }
396         }
397
398         return eventElement;
399     }
400 }