View Javadoc
1   /*
2    * Portions of this software was developed by employees of the National Institute
3    * of Standards and Technology (NIST), an agency of the Federal Government and is
4    * being made available as a public service. Pursuant to title 17 United States
5    * Code Section 105, works of NIST employees are not subject to copyright
6    * protection in the United States. This software may be subject to foreign
7    * copyright. Permission in the United States and in foreign countries, to the
8    * extent that NIST may hold copyright, to use, copy, modify, create derivative
9    * works, and distribute this software and its documentation without fee is hereby
10   * granted on a non-exclusive basis, provided that this notice and disclaimer
11   * of warranty appears in all copies.
12   *
13   * THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER
14   * EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY
15   * THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF
16   * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND FREEDOM FROM
17   * INFRINGEMENT, AND ANY WARRANTY THAT THE DOCUMENTATION WILL CONFORM TO THE
18   * SOFTWARE, OR ANY WARRANTY THAT THE SOFTWARE WILL BE ERROR FREE.  IN NO EVENT
19   * SHALL NIST BE LIABLE FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT,
20   * INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM,
21   * OR IN ANY WAY CONNECTED WITH THIS SOFTWARE, WHETHER OR NOT BASED UPON WARRANTY,
22   * CONTRACT, TORT, OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED BY PERSONS OR
23   * PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED FROM, OR AROSE OUT
24   * OF THE RESULTS OF, OR USE OF, THE SOFTWARE OR SERVICES PROVIDED HEREUNDER.
25   */
26  
27  package gov.nist.secauto.metaschema.databind.io.xml;
28  
29  import com.ctc.wstx.api.WstxOutputProperties;
30  import com.ctc.wstx.stax.WstxOutputFactory;
31  
32  import gov.nist.secauto.metaschema.core.util.ObjectUtils;
33  import gov.nist.secauto.metaschema.databind.io.AbstractSerializer;
34  import gov.nist.secauto.metaschema.databind.model.IAssemblyClassBinding;
35  
36  import org.codehaus.stax2.XMLOutputFactory2;
37  import org.codehaus.stax2.XMLStreamWriter2;
38  
39  import java.io.IOException;
40  import java.io.Writer;
41  
42  import javax.xml.stream.XMLOutputFactory;
43  import javax.xml.stream.XMLStreamException;
44  
45  import edu.umd.cs.findbugs.annotations.NonNull;
46  
47  public class DefaultXmlSerializer<CLASS>
48      extends AbstractSerializer<CLASS> {
49    private XMLOutputFactory2 xmlOutputFactory;
50  
51    /**
52     * Construct a new XML serializer based on the top-level assembly indicated by
53     * the provided {@code classBinding}.
54     *
55     * @param classBinding
56     *          the bound Module assembly definition that describes the data to
57     *          serialize
58     */
59    public DefaultXmlSerializer(@NonNull IAssemblyClassBinding classBinding) {
60      super(classBinding);
61    }
62  
63    /**
64     * Get the configured XML output factory used to create {@link XMLStreamWriter2}
65     * instances.
66     *
67     * @return the factory
68     */
69    @NonNull
70    protected final XMLOutputFactory2 getXMLOutputFactory() {
71      synchronized (this) {
72        if (xmlOutputFactory == null) {
73          xmlOutputFactory = (XMLOutputFactory2) XMLOutputFactory.newInstance();
74          assert xmlOutputFactory instanceof WstxOutputFactory;
75          xmlOutputFactory.configureForSpeed();
76          xmlOutputFactory.setProperty(WstxOutputProperties.P_USE_DOUBLE_QUOTES_IN_XML_DECL, true);
77          xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
78        }
79        assert xmlOutputFactory != null;
80        return xmlOutputFactory;
81      }
82    }
83  
84    /**
85     * Override the default {@link XMLOutputFactory2} instance with a custom
86     * factory.
87     *
88     * @param xmlOutputFactory
89     *          the new factory
90     */
91    protected void setXMLOutputFactory(@NonNull XMLOutputFactory2 xmlOutputFactory) {
92      synchronized (this) {
93        this.xmlOutputFactory = xmlOutputFactory;
94      }
95    }
96  
97    /**
98     * Create a new stream writer using the provided writer.
99     *
100    * @param writer
101    *          the writer to use for output
102    * @return the stream writer created by the output factory
103    * @throws IOException
104    *           if an error occurred while creating the writer
105    */
106   @NonNull
107   protected final XMLStreamWriter2 newXMLStreamWriter(@NonNull Writer writer) throws IOException {
108     try {
109       return ObjectUtils.notNull((XMLStreamWriter2) getXMLOutputFactory().createXMLStreamWriter(writer));
110     } catch (XMLStreamException ex) {
111       throw new IOException(ex);
112     }
113   }
114 
115   @Override
116   public void serialize(CLASS data, Writer writer) throws IOException {
117     XMLStreamWriter2 streamWriter = newXMLStreamWriter(writer);
118     IOException caughtException = null;
119     IAssemblyClassBinding classBinding = getClassBinding();
120 
121     MetaschemaXmlWriter xmlGenerator = new MetaschemaXmlWriter(streamWriter);
122 
123     try {
124       xmlGenerator.write(classBinding, data);
125       streamWriter.flush();
126     } catch (XMLStreamException ex) {
127       caughtException = new IOException(ex);
128       throw caughtException;
129     } finally { // NOPMD - exception handling is needed
130       try {
131         streamWriter.close();
132       } catch (XMLStreamException ex) {
133         if (caughtException == null) {
134           throw new IOException(ex);
135         }
136         caughtException.addSuppressed(ex);
137         throw caughtException; // NOPMD - intentional
138       }
139     }
140   }
141 }