001/*
002 * Portions of this software was developed by employees of the National Institute
003 * of Standards and Technology (NIST), an agency of the Federal Government and is
004 * being made available as a public service. Pursuant to title 17 United States
005 * Code Section 105, works of NIST employees are not subject to copyright
006 * protection in the United States. This software may be subject to foreign
007 * copyright. Permission in the United States and in foreign countries, to the
008 * extent that NIST may hold copyright, to use, copy, modify, create derivative
009 * works, and distribute this software and its documentation without fee is hereby
010 * granted on a non-exclusive basis, provided that this notice and disclaimer
011 * of warranty appears in all copies.
012 *
013 * THE SOFTWARE IS PROVIDED 'AS IS' WITHOUT ANY WARRANTY OF ANY KIND, EITHER
014 * EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY
015 * THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF
016 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND FREEDOM FROM
017 * INFRINGEMENT, AND ANY WARRANTY THAT THE DOCUMENTATION WILL CONFORM TO THE
018 * SOFTWARE, OR ANY WARRANTY THAT THE SOFTWARE WILL BE ERROR FREE.  IN NO EVENT
019 * SHALL NIST BE LIABLE FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO, DIRECT,
020 * INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM,
021 * OR IN ANY WAY CONNECTED WITH THIS SOFTWARE, WHETHER OR NOT BASED UPON WARRANTY,
022 * CONTRACT, TORT, OR OTHERWISE, WHETHER OR NOT INJURY WAS SUSTAINED BY PERSONS OR
023 * PROPERTY OR OTHERWISE, AND WHETHER OR NOT LOSS WAS SUSTAINED FROM, OR AROSE OUT
024 * OF THE RESULTS OF, OR USE OF, THE SOFTWARE OR SERVICES PROVIDED HEREUNDER.
025 */
026
027package gov.nist.secauto.metaschema.databind.io.xml;
028
029import com.ctc.wstx.stax.WstxInputFactory;
030
031import gov.nist.secauto.metaschema.core.metapath.item.node.IDocumentNodeItem;
032import gov.nist.secauto.metaschema.core.metapath.item.node.INodeItemFactory;
033import gov.nist.secauto.metaschema.core.util.AutoCloser;
034import gov.nist.secauto.metaschema.core.util.ObjectUtils;
035import gov.nist.secauto.metaschema.databind.io.AbstractDeserializer;
036import gov.nist.secauto.metaschema.databind.model.IAssemblyClassBinding;
037
038import org.codehaus.stax2.XMLEventReader2;
039import org.codehaus.stax2.XMLInputFactory2;
040
041import java.io.IOException;
042import java.io.Reader;
043import java.net.URI;
044
045import javax.xml.stream.EventFilter;
046import javax.xml.stream.XMLEventReader;
047import javax.xml.stream.XMLInputFactory;
048import javax.xml.stream.XMLStreamException;
049
050import edu.umd.cs.findbugs.annotations.NonNull;
051
052public class DefaultXmlDeserializer<CLASS>
053    extends AbstractDeserializer<CLASS> {
054  private XMLInputFactory2 xmlInputFactory;
055
056  @NonNull
057  private final IAssemblyClassBinding rootDefinition;
058
059  /**
060   * Construct a new Module binding-based deserializer that reads XML-based Module
061   * content.
062   *
063   * @param classBinding
064   *          the assembly class binding describing the Java objects this
065   *          deserializer parses data into
066   */
067  public DefaultXmlDeserializer(@NonNull IAssemblyClassBinding classBinding) {
068    super(classBinding);
069    if (!classBinding.isRoot()) {
070      throw new UnsupportedOperationException(
071          String.format("The assembly '%s' is not a root assembly.", classBinding.getBoundClass().getName()));
072    }
073    this.rootDefinition = classBinding;
074  }
075
076  /**
077   * Get the XML input factory instance used to create XML parser instances.
078   * <p>
079   * Uses a built-in default if a user specified factory is not provided.
080   *
081   * @return the factory instance
082   * @see #setXMLInputFactory(XMLInputFactory2)
083   */
084  @NonNull
085  private XMLInputFactory2 getXMLInputFactory() {
086    synchronized (this) {
087      if (xmlInputFactory == null) {
088        xmlInputFactory = (XMLInputFactory2) XMLInputFactory.newInstance();
089        assert xmlInputFactory instanceof WstxInputFactory;
090        xmlInputFactory.configureForXmlConformance();
091        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, false);
092        // xmlInputFactory.configureForSpeed();
093      }
094      return ObjectUtils.notNull(xmlInputFactory);
095    }
096  }
097
098  /**
099   * 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}