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.stax.WstxInputFactory;
30  
31  import gov.nist.secauto.metaschema.core.metapath.item.node.IDocumentNodeItem;
32  import gov.nist.secauto.metaschema.core.metapath.item.node.INodeItemFactory;
33  import gov.nist.secauto.metaschema.core.util.AutoCloser;
34  import gov.nist.secauto.metaschema.core.util.ObjectUtils;
35  import gov.nist.secauto.metaschema.databind.io.AbstractDeserializer;
36  import gov.nist.secauto.metaschema.databind.model.IAssemblyClassBinding;
37  
38  import org.codehaus.stax2.XMLEventReader2;
39  import org.codehaus.stax2.XMLInputFactory2;
40  
41  import java.io.IOException;
42  import java.io.Reader;
43  import java.net.URI;
44  
45  import javax.xml.stream.EventFilter;
46  import javax.xml.stream.XMLEventReader;
47  import javax.xml.stream.XMLInputFactory;
48  import javax.xml.stream.XMLStreamException;
49  
50  import edu.umd.cs.findbugs.annotations.NonNull;
51  
52  public class DefaultXmlDeserializer<CLASS>
53      extends AbstractDeserializer<CLASS> {
54    private XMLInputFactory2 xmlInputFactory;
55  
56    @NonNull
57    private final IAssemblyClassBinding rootDefinition;
58  
59    /**
60     * Construct a new Module binding-based deserializer that reads XML-based Module
61     * content.
62     *
63     * @param classBinding
64     *          the assembly class binding describing the Java objects this
65     *          deserializer parses data into
66     */
67    public DefaultXmlDeserializer(@NonNull IAssemblyClassBinding classBinding) {
68      super(classBinding);
69      if (!classBinding.isRoot()) {
70        throw new UnsupportedOperationException(
71            String.format("The assembly '%s' is not a root assembly.", classBinding.getBoundClass().getName()));
72      }
73      this.rootDefinition = classBinding;
74    }
75  
76    /**
77     * Get the XML input factory instance used to create XML parser instances.
78     * <p>
79     * Uses a built-in default if a user specified factory is not provided.
80     *
81     * @return the factory instance
82     * @see #setXMLInputFactory(XMLInputFactory2)
83     */
84    @NonNull
85    private XMLInputFactory2 getXMLInputFactory() {
86      synchronized (this) {
87        if (xmlInputFactory == null) {
88          xmlInputFactory = (XMLInputFactory2) XMLInputFactory.newInstance();
89          assert xmlInputFactory instanceof WstxInputFactory;
90          xmlInputFactory.configureForXmlConformance();
91          xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, false);
92          // xmlInputFactory.configureForSpeed();
93        }
94        return ObjectUtils.notNull(xmlInputFactory);
95      }
96    }
97  
98    /**
99     * Provide a XML input factory instance that will be used to create XML parser
100    * instances.
101    *
102    * @param factory
103    *          the factory instance
104    */
105   protected void setXMLInputFactory(@NonNull XMLInputFactory2 factory) {
106     synchronized (this) {
107       this.xmlInputFactory = factory;
108     }
109   }
110 
111   @NonNull
112   private XMLEventReader2 newXMLEventReader2(@NonNull Reader reader) throws XMLStreamException {
113     XMLEventReader eventReader = getXMLInputFactory().createXMLEventReader(reader);
114     EventFilter filter = new CommentFilter();
115     return ObjectUtils.notNull((XMLEventReader2) getXMLInputFactory().createFilteredReader(eventReader, filter));
116   }
117 
118   @Override
119   protected final IDocumentNodeItem deserializeToNodeItemInternal(Reader reader, URI documentUri) throws IOException {
120     Object value = deserializeToValue(reader, documentUri);
121     return INodeItemFactory.instance().newDocumentNodeItem(rootDefinition, documentUri, value);
122   }
123 
124   @Override
125   public final CLASS deserializeToValue(Reader reader, URI documentUri) throws IOException {
126     // doesn't auto close the underlying reader
127     try (AutoCloser<XMLEventReader2, XMLStreamException> closer = new AutoCloser<>(
128         newXMLEventReader2(reader), event -> event.close())) {
129       return parseXmlInternal(closer.getResource());
130     } catch (XMLStreamException ex) {
131       throw new IOException("Unable to create a new XMLEventReader2 instance.", ex);
132     }
133   }
134 
135   @NonNull
136   private CLASS parseXmlInternal(@NonNull XMLEventReader2 reader)
137       throws IOException {
138 
139     MetaschemaXmlReader parser = new MetaschemaXmlReader(reader, new DefaultXmlProblemHandler());
140 
141     try {
142       return parser.read(rootDefinition);
143     } catch (IOException | XMLStreamException | AssertionError ex) {
144       throw new IOException(
145           String.format("An unexpected error occured during parsing: %s", ex.getMessage()),
146           ex);
147     }
148   }
149 }