summaryrefslogtreecommitdiffstats
path: root/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriter.java
blob: 977a8e7c6d20dafcc07ae279731b0852e4ab050a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.model.basicmodel.handling;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Set;
import java.util.TreeSet;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.oxm.MediaType;
import org.onap.policy.apex.model.basicmodel.concepts.AxConcept;
import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
import org.onap.policy.apex.model.utilities.Assertions;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
import org.w3c.dom.Document;

/**
 * This class writes an Apex concept to an XML file or JSON file from a Java Apex Concept.
 *
 * @author John Keeney (john.keeney@ericsson.com)
 * @param <C> the type of Apex concept to write, must be a sub class of {@link AxConcept}
 */
public class ApexModelWriter<C extends AxConcept> {
    private static final String CONCEPT_MAY_NOT_BE_NULL = "concept may not be null";
    private static final String CONCEPT_WRITER_MAY_NOT_BE_NULL = "concept writer may not be null";
    private static final String CONCEPT_STREAM_MAY_NOT_BE_NULL = "concept stream may not be null";

    // Get a reference to the logger
    private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelWriter.class);

    // Writing as JSON or XML
    private boolean jsonOutput = false;

    // The list of fields to output as CDATA
    private final Set<String> cdataFieldSet = new TreeSet<>();

    // The Marshaller for the Apex concepts
    private Marshaller marshaller = null;

    // All written concepts are validated before writing if this flag is set
    private boolean validateFlag = true;

    /**
     * Constructor, initiates the writer.
     *
     * @param rootConceptClass the root concept class for concept reading
     * @throws ApexModelException the apex concept writer exception
     */
    public ApexModelWriter(final Class<C> rootConceptClass) throws ApexModelException {
        // Set up Eclipselink for XML and JSON output
        System.setProperty("javax.xml.bind.context.factory", "org.eclipse.persistence.jaxb.JAXBContextFactory");

        try {
            final JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {rootConceptClass}, null);

            // Set up the unmarshaller to carry out validation
            marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
        } catch (final JAXBException e) {
            LOGGER.error("JAXB marshaller creation exception", e);
            throw new ApexModelException("JAXB marshaller creation exception", e);
        }
    }

    /**
     * The set of fields to be output as CDATA.
     *
     * @return the set of fields
     */
    public Set<String> getCDataFieldSet() {
        return cdataFieldSet;
    }

    /**
     * Return true if JSON output enabled, XML output if false.
     *
     * @return true for JSON output
     */
    public boolean isJsonOutput() {
        return jsonOutput;
    }

    /**
     * Set the value of JSON output, true for JSON output, false for XML output.
     *
     * @param jsonOutput true for JSON output
     * @throws ApexModelException on errors setting output type
     */
    public void setJsonOutput(final boolean jsonOutput) throws ApexModelException {
        this.jsonOutput = jsonOutput;

        // Set up output specific parameters
        if (this.jsonOutput) {
            try {
                marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
                marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
            } catch (final Exception e) {
                LOGGER.warn("JAXB error setting marshaller for JSON output", e);
                throw new ApexModelException("JAXB error setting marshaller for JSON output", e);
            }
        } else {
            try {
                marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML);
            } catch (final Exception e) {
                LOGGER.warn("JAXB error setting marshaller for XML output", e);
                throw new ApexModelException("JAXB error setting marshaller for XML output", e);
            }
        }
    }

    /**
     * This method validates the Apex concept then writes it into a stream.
     *
     * @param concept the concept to write
     * @param apexConceptStream the stream to write to
     * @throws ApexModelException on validation or writing exceptions
     */
    public void write(final C concept, final OutputStream apexConceptStream) throws ApexModelException {
        Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL);
        Assertions.argumentNotNull(apexConceptStream, CONCEPT_STREAM_MAY_NOT_BE_NULL);

        this.write(concept, new OutputStreamWriter(apexConceptStream));
    }

    /**
     * This method validates the Apex concept then writes it into a writer.
     *
     * @param concept the concept to write
     * @param apexConceptWriter the writer to write to
     * @throws ApexModelException on validation or writing exceptions
     */
    public void write(final C concept, final Writer apexConceptWriter) throws ApexModelException {
        Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL);
        Assertions.argumentNotNull(apexConceptWriter, CONCEPT_WRITER_MAY_NOT_BE_NULL);

        // Check if we should validate the concept
        if (validateFlag) {
            // Validate the concept first
            final AxValidationResult validationResult = concept.validate(new AxValidationResult());
            LOGGER.debug(validationResult.toString());
            if (!validationResult.isValid()) {
                LOGGER.warn(validationResult.toString());
                throw new ApexModelException("Apex concept xml (" + concept.getKey().getId() + ") validation failed");
            }
        }

        if (jsonOutput) {
            writeJson(concept, apexConceptWriter);
        } else {
            writeXml(concept, apexConceptWriter);
        }
    }

    /**
     * This method writes the Apex concept into a writer in XML format.
     *
     * @param concept the concept to write
     * @param apexConceptWriter the writer to write to
     * @throws ApexModelException on validation or writing exceptions
     */
    private void writeXml(final C concept, final Writer apexConceptWriter) throws ApexModelException {
        Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL);

        LOGGER.debug("writing Apex concept XML . . .");

        try {
            // Write the concept into a DOM document, then transform to add CDATA fields and pretty
            // print, then write out the result
            final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            final Document document = docBuilderFactory.newDocumentBuilder().newDocument();

            // Marshal the concept into the empty document.
            marshaller.marshal(concept, document);

            final Transformer domTransformer = getTransformer();

            // Convert the cDataFieldSet into a space delimited string
            domTransformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS,
                    cdataFieldSet.toString().replaceAll("[\\[\\]\\,]", " "));
            domTransformer.transform(new DOMSource(document), new StreamResult(apexConceptWriter));
        } catch (JAXBException | TransformerException | ParserConfigurationException e) {
            LOGGER.warn("Unable to marshal Apex concept XML", e);
            throw new ApexModelException("Unable to marshal Apex concept XML", e);
        }
        LOGGER.debug("wrote Apex concept XML");
    }


    private Transformer getTransformer() throws TransformerConfigurationException {
        // Transform the DOM to the output stream
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer domTransformer = transformerFactory.newTransformer();

        // Pretty print
        try {
            domTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
            // May fail if not using XALAN XSLT engine. But not in any way vital
            domTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        } catch (final Exception ignore) {
            LOGGER.trace("Unable to set indent property", ignore);
        }
        return domTransformer;
    }

    /**
     * This method writes the Apex concept into a writer in JSON format.
     *
     * @param concept the concept to write
     * @param apexConceptWriter the writer to write to
     * @throws ApexModelException on validation or writing exceptions
     */
    private void writeJson(final C concept, final Writer apexConceptWriter) throws ApexModelException {
        Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL);

        LOGGER.debug("writing Apex concept JSON . . .");

        try {
            marshaller.marshal(concept, apexConceptWriter);
        } catch (final JAXBException e) {
            LOGGER.warn("Unable to marshal Apex concept JSON", e);
            throw new ApexModelException("Unable to marshal Apex concept JSON", e);
        }
        LOGGER.debug("wrote Apex concept JSON");
    }

    /**
     * Gets the validation flag value.
     *
     * @return the validation flag value
     */
    public boolean getValidateFlag() {
        return validateFlag;
    }

    /**
     * Sets the validation flag.
     *
     * @param validateFlag the validation flag value
     */
    public void setValidateFlag(final boolean validateFlag) {
        this.validateFlag = validateFlag;
    }
}