76bae68337a9fa89afc9d2fae7364096f9ba53df
[policy/apex-pdp.git] /
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
30 import javax.xml.XMLConstants;
31 import javax.xml.bind.JAXBContext;
32 import javax.xml.bind.JAXBElement;
33 import javax.xml.bind.JAXBException;
34 import javax.xml.bind.Marshaller;
35 import javax.xml.bind.Unmarshaller;
36 import javax.xml.transform.stream.StreamSource;
37 import javax.xml.validation.Schema;
38 import javax.xml.validation.SchemaFactory;
39
40 import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.ObjectFactory;
41 import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEvent;
42 import org.onap.policy.apex.plugins.event.protocol.xml.jaxb.XMLApexEventData;
43 import org.onap.policy.apex.service.engine.event.ApexEvent;
44 import org.onap.policy.apex.service.engine.event.ApexEventException;
45 import org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter;
46 import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
47 import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters;
48 import org.onap.policy.common.utils.resources.ResourceUtils;
49 import org.slf4j.ext.XLogger;
50 import org.slf4j.ext.XLoggerFactory;
51 import org.xml.sax.SAXException;
52
53 /**
54  * The Class Apex2XMLEventConverter converts {@link ApexEvent} instances into string instances of {@link XMLApexEvent}
55  * that are XML representations of Apex events defined in JAXB.
56  *
57  * @author Liam Fallon (liam.fallon@ericsson.com)
58  */
59 public final class Apex2XMLEventConverter implements ApexEventProtocolConverter {
60     private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2XMLEventConverter.class);
61
62     private static final String MODEL_SCHEMA_NAME = "xml/apex-event.xsd";
63
64     // XML Unmarshaller and marshaller and object factory for events
65     private Unmarshaller unmarshaller;
66     private Marshaller marshaller;
67     private ObjectFactory objectFactory = new ObjectFactory();
68
69     /**
70      * Constructor to create the Apex to XML converter.
71      *
72      * @throws ApexEventException the apex event exception
73      */
74     public Apex2XMLEventConverter() throws ApexEventException {
75         try {
76             final URL schemaURL = ResourceUtils.getUrlResource(MODEL_SCHEMA_NAME);
77             final Schema apexEventSchema =
78                     SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaURL);
79
80             final JAXBContext jaxbContext = JAXBContext.newInstance(XMLApexEvent.class);
81
82             // Set up the unmarshaller to carry out validation
83             unmarshaller = jaxbContext.createUnmarshaller();
84             unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
85             unmarshaller.setSchema(apexEventSchema);
86
87             // Set up the marshaller
88             marshaller = jaxbContext.createMarshaller();
89             marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
90             marshaller.setSchema(apexEventSchema);
91         } catch (JAXBException | SAXException e) {
92             LOGGER.error("Unable to set up marshalling and unmarshalling for XML events", e);
93             throw new ApexEventException("Unable to set up marshalling and unmarshalling for XML events", e);
94         }
95     }
96
97     /*
98      * (non-Javadoc)
99      *
100      * @see org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter#init(org.onap.policy.apex.service.
101      * parameters. eventprotocol.EventProtocolParameters)
102      */
103     @Override
104     public void init(final EventProtocolParameters parameters) {}
105
106     /*
107      * (non-Javadoc)
108      *
109      * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#toApexEvent(java.lang.String, java.lang.Object)
110      */
111     @Override
112     public List<ApexEvent> toApexEvent(final String eventName, final Object eventObject) throws ApexEventException {
113         // Check the XML event
114         if (eventObject == null) {
115             LOGGER.warn("event processing failed, XML event is null");
116             throw new ApexEventException("event processing failed, XML event is null");
117         }
118
119         // Cast the event to a string, if our conversion is correctly configured, this cast should always work
120         String xmlEventString = null;
121         try {
122             xmlEventString = (String) eventObject;
123         } catch (final Exception e) {
124             final String errorMessage = "error converting event \"" + eventObject + "\" to a string";
125             LOGGER.debug(errorMessage, e);
126             throw new ApexEventRuntimeException(errorMessage, e);
127         }
128
129         // The XML event
130         XMLApexEvent xmlApexEvent = null;
131
132         // Use JAXB to read and verify the event from the XML string
133         try {
134             final StreamSource source = new StreamSource(new ByteArrayInputStream(xmlEventString.getBytes()));
135             final JAXBElement<XMLApexEvent> rootElement = unmarshaller.unmarshal(source, XMLApexEvent.class);
136             xmlApexEvent = rootElement.getValue();
137         } catch (final JAXBException e) {
138             LOGGER.warn("Unable to unmarshal Apex XML event\n" + xmlEventString, e);
139             throw new ApexEventException("Unable to unmarshal Apex XML event\n" + xmlEventString, e);
140         }
141
142         // Create the Apex event
143         final ApexEvent apexEvent = new ApexEvent(xmlApexEvent.getName(), xmlApexEvent.getVersion(),
144                 xmlApexEvent.getNameSpace(), xmlApexEvent.getSource(), xmlApexEvent.getTarget());
145
146         // Set the data on the apex event
147         for (final XMLApexEventData xmlData : xmlApexEvent.getData()) {
148             apexEvent.put(xmlData.getKey(), xmlData.getValue());
149         }
150
151         // Return the event in a single element
152         final ArrayList<ApexEvent> eventList = new ArrayList<ApexEvent>();
153         eventList.add(apexEvent);
154         return eventList;
155     }
156
157     /*
158      * (non-Javadoc)
159      *
160      * @see
161      * org.onap.policy.apex.service.engine.event.ApexEventConverter#fromApexEvent(org.onap.policy.apex.service.engine.
162      * event. ApexEvent)
163      */
164     @Override
165     public String fromApexEvent(final ApexEvent apexEvent) throws ApexEventException {
166         // Check the Apex event
167         if (apexEvent == null) {
168             LOGGER.warn("event processing failed, Apex event is null");
169             throw new ApexEventException("event processing failed, Apex event is null");
170         }
171
172         // Get the Apex event data
173         final List<XMLApexEventData> xmlDataList = new ArrayList<XMLApexEventData>();
174
175         try {
176             for (final Entry<String, Object> apexDataEntry : apexEvent.entrySet()) {
177                 // Add an XML event data item
178                 if (apexDataEntry.getValue() != null) {
179                     xmlDataList.add(new XMLApexEventData(apexDataEntry.getKey(), apexDataEntry.getValue().toString()));
180                 } else {
181                     xmlDataList.add(new XMLApexEventData(apexDataEntry.getKey(), ""));
182                 }
183             }
184         } catch (final Exception e) {
185             LOGGER.warn("Unable to transfer Apex event data to XML\n" + apexEvent, e);
186             throw new ApexEventException("Unable to transfer Apex event data to XML\n" + apexEvent, e);
187         }
188
189         // Create the XML event
190         final XMLApexEvent xmlApexEvent = new XMLApexEvent(apexEvent.getName(), apexEvent.getVersion(),
191                 apexEvent.getNameSpace(), apexEvent.getSource(), apexEvent.getTarget(), xmlDataList);
192
193         // Write the event into a DOM document
194         try {
195             // Marshal the event into XML
196             final StringWriter writer = new StringWriter();
197             marshaller.marshal(objectFactory.createXmlApexEvent(xmlApexEvent), writer);
198
199             // Return the event as XML in a string
200             return writer.toString();
201         } catch (final JAXBException e) {
202             LOGGER.warn("Unable to unmarshal Apex event to XML\n" + apexEvent, e);
203             throw new ApexEventException("Unable to unmarshal Apex event to XML\n" + apexEvent, e);
204         }
205     }
206 }