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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.plugins.event.protocol.yaml;
24 import java.util.ArrayList;
25 import java.util.LinkedHashMap;
26 import java.util.List;
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;
45 * The Class Apex2YamlEventConverter converts {@link ApexEvent} instances to and from YAML string representations of
48 * @author Liam Fallon (liam.fallon@ericsson.com)
50 public class Apex2YamlEventConverter implements ApexEventProtocolConverter {
51 private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2YamlEventConverter.class);
53 // The parameters for the YAML event protocol
54 private YamlEventProtocolParameters yamlPars;
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);
68 yamlPars = (YamlEventProtocolParameters) parameters;
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");
82 // Cast the event to a string, if our conversion is correctly configured, this cast should
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);
90 final String yamlEventString = (String) eventObject;
92 // The list of events we will return
93 final List<ApexEvent> eventList = new ArrayList<>();
95 // Convert the YAML document string into an object
96 Object yamlObject = new Yaml().load(yamlEventString);
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
101 if (yamlObject instanceof Map) {
102 // We already have a map so just cast the object
103 yamlMap = (Map<?, ?>) yamlObject;
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;
113 eventList.add(yamlMap2ApexEvent(eventName, yamlMap));
114 } catch (final Exception e) {
115 throw new ApexEventException("Failed to unmarshal YAML event, event="
116 + yamlEventString, e);
119 // Return the list of events we have unmarshalled
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");
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());
138 // Create a map for output of the APEX event to YAML
139 LinkedHashMap<String, Object> yamlMap = new LinkedHashMap<>();
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());
147 if (apexEvent.getExceptionMessage() != null) {
148 yamlMap.put(ApexEvent.EXCEPTION_MESSAGE_HEADER_FIELD, apexEvent.getExceptionMessage());
151 for (final AxField eventField : eventDefinition.getFields()) {
152 final String fieldName = eventField.getKey().getLocalName();
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);
164 yamlMap.put(fieldName, apexEvent.get(fieldName));
167 // Use Snake YAML to convert the APEX event to YAML
168 Yaml yaml = new Yaml();
169 return yaml.dumpAs(yamlMap, null, FlowStyle.BLOCK);
173 * This method converts a YAML map into an Apex event.
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
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);
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());
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);
201 final Object fieldValue = getYamlField(yamlMap, fieldName, null, !eventField.getOptional());
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));
209 apexEvent.put(fieldName, null);
217 * This method processes the event header of an Apex event.
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
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);
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");
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);
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");
255 // Use the defined event version if no version is specified on the incoming fields
256 if (version == null) {
257 version = eventDefinition.getKey().getVersion();
260 String namespace = getEventHeaderNamespace(yamlMap, name, eventDefinition);
262 String source = getEventHeaderSource(yamlMap, eventDefinition);
264 String target = getHeaderTarget(yamlMap, eventDefinition);
266 return new ApexEvent(name, version, namespace, source, target);
270 * Get the event header name space.
272 * @param yamlMap the YAML map to read from
273 * @param eventDefinition the event definition
274 * @return the event header name space
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");
287 namespace = eventDefinition.getNameSpace();
293 * Get the event header source.
295 * @param yamlMap the YAML map to read from
296 * @param eventDefinition the event definition
297 * @return the event header source
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();
310 * Get the event header target.
312 * @param yamlMap the YAML map to read from
313 * @param eventDefinition the event definition
314 * @return the event header target
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();
327 * This method gets an event string field from a JSON object.
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
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);
342 // Null strings are allowed
343 if (yamlField == null) {
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");
353 final String fieldValueString = (String) yamlField;
355 // Is regular expression checking required
356 if (fieldRegexp == null) {
357 return fieldValueString;
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");
366 return fieldValueString;
370 * This method gets an event field from a YAML object.
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
379 private Object getYamlField(final Map<?, ?> yamlMap, final String fieldName, final String fieldAlias,
380 final boolean mandatory) {
382 // Check if we should use the alias for this field
383 String fieldToFind = fieldName;
384 if (fieldAlias != null) {
385 fieldToFind = fieldAlias;
388 // Get the event field
389 final Object eventElement = yamlMap.get(fieldToFind);
390 if (eventElement == null) {
394 throw new ApexEventRuntimeException("mandatory field \"" + fieldToFind + "\" is missing");