Changes for checkstyle 8.32
[policy/apex-pdp.git] / plugins / plugins-event / plugins-event-protocol / plugins-event-protocol-xml / src / main / java / org / onap / policy / apex / plugins / event / protocol / xml / Apex2XmlEventConverter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.plugins.event.protocol.xml;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.StringWriter;
25 import java.net.URL;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Map.Entry;
29 import javax.xml.XMLConstants;
30 import javax.xml.bind.JAXBContext;
31 import javax.xml.bind.JAXBElement;
32 import javax.xml.bind.JAXBException;
33 import javax.xml.bind.Marshaller;
34 import javax.xml.bind.Unmarshaller;
35 import javax.xml.transform.stream.StreamSource;
36 import javax.xml.validation.Schema;
37 import javax.xml.validation.SchemaFactory;
38 import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.ObjectFactory;
39 import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEvent;
40 import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEventData;
41 import org.onap.policy.apex.service.engine.event.ApexEvent;
42 import org.onap.policy.apex.service.engine.event.ApexEventException;
43 import org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter;
44 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
45 import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters;
46 import org.onap.policy.common.utils.resources.ResourceUtils;
47 import org.slf4j.ext.XLogger;
48 import org.slf4j.ext.XLoggerFactory;
49 import org.xml.sax.SAXException;
50
51 /**
52  * The Class Apex2XMLEventConverter converts {@link ApexEvent} instances into string instances of {@link XMLApexEvent}
53  * that are XML representations of Apex events defined in JAXB.
54  *
55  * @author Liam Fallon (liam.fallon@ericsson.com)
56  */
57 public final class Apex2XmlEventConverter implements ApexEventProtocolConverter {
58     private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2XmlEventConverter.class);
59
60     private static final String MODEL_SCHEMA_NAME = "xml/apex-event.xsd";
61
62     // XML Unmarshaller and marshaller and object factory for events
63     private Unmarshaller unmarshaller;
64     private Marshaller marshaller;
65     private ObjectFactory objectFactory = new ObjectFactory();
66
67     /**
68      * Constructor to create the Apex to XML converter.
69      *
70      * @throws ApexEventException the apex event exception
71      */
72     public Apex2XmlEventConverter() throws ApexEventException {
73         try {
74             final URL schemaUrl = ResourceUtils.getUrlResource(MODEL_SCHEMA_NAME);
75             final Schema apexEventSchema =
76                     SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaUrl);
77
78             final JAXBContext jaxbContext = JAXBContext.newInstance(XMLApexEvent.class);
79
80             // Set up the unmarshaller to carry out validation
81             unmarshaller = jaxbContext.createUnmarshaller();
82             unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
83             unmarshaller.setSchema(apexEventSchema);
84
85             // Set up the marshaller
86             marshaller = jaxbContext.createMarshaller();
87             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
88             marshaller.setSchema(apexEventSchema);
89         } catch (JAXBException | SAXException e) {
90             LOGGER.error("Unable to set up marshalling and unmarshalling for XML events", e);
91             throw new ApexEventException("Unable to set up marshalling and unmarshalling for XML events", e);
92         }
93     }
94
95     /**
96      * {@inheritDoc}.
97      */
98     @Override
99     public void init(final EventProtocolParameters parameters) {
100         // No initialization necessary on this class
101     }
102
103     /**
104      * {@inheritDoc}.
105      */
106     @Override
107     public List<ApexEvent> toApexEvent(final String eventName, final Object eventObject) throws ApexEventException {
108         // Check the XML event
109         if (eventObject == null) {
110             LOGGER.warn("event processing failed, XML event is null");
111             throw new ApexEventException("event processing failed, XML event is null");
112         }
113
114         // Cast the event to a string, if our conversion is correctly configured, this cast should always work
115         String xmlEventString = null;
116         try {
117             xmlEventString = (String) eventObject;
118         } catch (final Exception e) {
119             final String errorMessage = "error converting event \"" + eventObject + "\" to a string";
120             LOGGER.debug(errorMessage, e);
121             throw new ApexEventRuntimeException(errorMessage, e);
122         }
123
124         // The XML event
125         XMLApexEvent xmlApexEvent = null;
126
127         // Use JAXB to read and verify the event from the XML string
128         try {
129             final StreamSource source = new StreamSource(new ByteArrayInputStream(xmlEventString.getBytes()));
130             final JAXBElement<XMLApexEvent> rootElement = unmarshaller.unmarshal(source, XMLApexEvent.class);
131             xmlApexEvent = rootElement.getValue();
132         } catch (final JAXBException e) {
133             LOGGER.warn("Unable to unmarshal Apex XML event\n" + xmlEventString, e);
134             throw new ApexEventException("Unable to unmarshal Apex XML event\n" + xmlEventString, e);
135         }
136
137         // Create the Apex event
138         final ApexEvent apexEvent = new ApexEvent(xmlApexEvent.getName(), xmlApexEvent.getVersion(),
139                 xmlApexEvent.getNameSpace(), xmlApexEvent.getSource(), xmlApexEvent.getTarget());
140
141         // Set the data on the apex event
142         for (final XMLApexEventData xmlData : xmlApexEvent.getData()) {
143             apexEvent.put(xmlData.getKey(), xmlData.getValue());
144         }
145
146         // Return the event in a single element
147         final ArrayList<ApexEvent> eventList = new ArrayList<>();
148         eventList.add(apexEvent);
149         return eventList;
150     }
151
152     /**
153      * {@inheritDoc}.
154      */
155     @Override
156     public String fromApexEvent(final ApexEvent apexEvent) throws ApexEventException {
157         // Check the Apex event
158         if (apexEvent == null) {
159             LOGGER.warn("event processing failed, Apex event is null");
160             throw new ApexEventException("event processing failed, Apex event is null");
161         }
162
163         // Get the Apex event data
164         final List<XMLApexEventData> xmlDataList = new ArrayList<>();
165
166         try {
167             for (final Entry<String, Object> apexDataEntry : apexEvent.entrySet()) {
168                 // Add an XML event data item
169                 if (apexDataEntry.getValue() != null) {
170                     xmlDataList.add(new XMLApexEventData(apexDataEntry.getKey(), apexDataEntry.getValue().toString()));
171                 } else {
172                     xmlDataList.add(new XMLApexEventData(apexDataEntry.getKey(), ""));
173                 }
174             }
175         } catch (final Exception e) {
176             LOGGER.warn("Unable to transfer Apex event data to XML\n" + apexEvent, e);
177             throw new ApexEventException("Unable to transfer Apex event data to XML\n" + apexEvent, e);
178         }
179
180         // Create the XML event
181         final XMLApexEvent xmlApexEvent = new XMLApexEvent(apexEvent.getName(), apexEvent.getVersion(),
182                 apexEvent.getNameSpace(), apexEvent.getSource(), apexEvent.getTarget(), xmlDataList);
183
184         // Write the event into a DOM document
185         try {
186             // Marshal the event into XML
187             final StringWriter writer = new StringWriter();
188             marshaller.marshal(objectFactory.createXmlApexEvent(xmlApexEvent), writer);
189
190             // Return the event as XML in a string
191             return writer.toString();
192         } catch (final JAXBException e) {
193             LOGGER.warn("Unable to unmarshal Apex event to XML\n" + apexEvent, e);
194             throw new ApexEventException("Unable to unmarshal Apex event to XML\n" + apexEvent, e);
195         }
196     }
197 }