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