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