Example usage for javax.xml.stream XMLInputFactory newInstance

List of usage examples for javax.xml.stream XMLInputFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.stream XMLInputFactory newInstance.

Prototype

public static XMLInputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:com.joliciel.frenchTreebank.upload.TreebankXmlReader.java

void getNextEventReader() {
    if (eventReader == null && currentFileIndex < files.size()) {
        File file = files.get(currentFileIndex++);
        try {/*from   w w  w.j  av  a2  s  .  co m*/
            LOG.info("Reading file: " + file.getName());
            InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            XMLInputFactory factory = XMLInputFactory.newInstance();
            eventReader = factory.createXMLEventReader(inputStream);
        } catch (FileNotFoundException e) {
            LogUtils.logError(LOG, e);
            throw new RuntimeException(e);
        } catch (XMLStreamException e) {
            LogUtils.logError(LOG, e);
            throw new RuntimeException(e);
        }
        treebankFile = this.treebankService.newTreebankFile(file.getName());
    }
}

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final Vaadlets unmarshal(final Reader aReader, final Resource theSchemaResource) {
    try {//from  ww w .  j  a  v  a2  s.  c o m
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            unmarshaller.setSchema(schema);
        }
        return unmarshaller
                .unmarshal(XMLInputFactory.newInstance().createXMLStreamReader(aReader), Vaadlets.class)
                .getValue();
    } catch (final JAXBException | SAXException | XMLStreamException | FactoryConfigurationError
            | IOException e) {
        throw new RuntimeException("Can't unmarschal", e);
    }
}

From source file:com.act.lcms.MzMLParser.java

public Iterator<S> getIterator(String inputFile)
        throws ParserConfigurationException, IOException, XMLStreamException {
    DocumentBuilderFactory docFactory = mkDocBuilderFactory();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();

    return new Iterator<S>() {
        boolean inEntry = false;

        XMLEventReader xr = xmlInputFactory.createXMLEventReader(new FileInputStream(inputFile), "utf-8");
        // TODO: is the use of the XML version/encoding tag definitely necessary?
        StringWriter w = new StringWriter().append(XML_PREAMBLE).append("\n");
        XMLEventWriter xw = xmlOutputFactory.createXMLEventWriter(w);

        S next = null;/*www . j  a  va2 s.c o  m*/

        /* Because we're handling the XML as a stream, we can only determine whether we have another Spectrum to return
         * by attempting to parse the next one.  `this.next()` reads
         */
        private S getNextSpectrum() {
            S spectrum = null;
            if (xr == null || !xr.hasNext()) {
                return null;
            }

            try {
                while (xr.hasNext()) {
                    XMLEvent e = xr.nextEvent();
                    if (!inEntry && e.isStartElement()
                            && e.asStartElement().getName().getLocalPart().equals((SPECTRUM_OBJECT_TAG))) {
                        xw.add(e);
                        inEntry = true;
                    } else if (e.isEndElement()
                            && e.asEndElement().getName().getLocalPart().equals(SPECTRUM_OBJECT_TAG)) {
                        xw.add(e);
                        xw.flush();
                        /* TODO: the XMLOutputFactory docs don't make it clear if/how events can be written directly into a new
                         * document structure, so we incur the cost of extracting each spectrum entry, serializing it, and
                         * re-reading it into its own document so it can be handled by XPath.  Master this strange corner of the
                         * Java ecosystem and get rid of <></>his doc -> string -> doc conversion. */
                        Document doc = docBuilder.parse(new ReaderInputStream(new StringReader(w.toString())));
                        spectrum = handleSpectrumEntry(doc);
                        xw.close();
                        /* Note: this can also be accomplished with `w.getBuffer().setLength(0);`, but using a new event writer
                         * seems safer. */
                        w = new StringWriter();
                        w.append(XML_PREAMBLE).append("\n");
                        xw = xmlOutputFactory.createXMLEventWriter(w);
                        inEntry = false;
                        // Don't stop parsing if handleSpectrumEntry didn't like this spectrum document.
                        if (spectrum != null) {
                            break;
                        }
                    } else if (inEntry) {
                        // Add this element if we're in an entry
                        xw.add(e);
                    }
                }

                // We've reached the end of the document; close the reader to show that we're done.
                if (!xr.hasNext()) {
                    xr.close();
                    xr = null;
                }
            } catch (Exception e) {
                // TODO: do better.  We seem to run into this sort of thing with Iterators a lot...
                throw new RuntimeException(e);
            }

            return spectrum;
        }

        private S tryParseNext() {
            // Fail the attempt if the reader is closed.
            if (xr == null || !xr.hasNext()) {
                return null;
            }

            // No checks on whether we already have a spectrum stored: we expect the callers to do that.
            return getNextSpectrum();
        }

        @Override
        public boolean hasNext() {
            // Prime the pump if the iterator doesn't have a value stored yet.
            if (this.next == null) {
                this.next = tryParseNext();
            }

            // If we have an entry waiting, return true; otherwise read the next entry and return true if successful.
            return this.next != null;
        }

        @Override
        public S next() {
            // Prime the pump like we do in hasNext().
            if (this.next == null) {
                this.next = tryParseNext();
            }

            // Take available spectrum and return it.
            S res = this.next;
            /* Advance to the next element immediately, making next() do the heavy lifting most of the time.  Otherwise,
             * the parsing will resume on hasNext(), which seems like it ought to be a light-weight operation. */
            this.next = tryParseNext();

            return res;
        }

    };
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.tuepp.TueppReader.java

@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
    super.initialize(aContext);

    posMappingProvider = MappingProviderFactory.createPosMappingProvider(mappingPosLocation, posTagset,
            getLanguage());//w w  w .  j  ava 2 s  .c o m

    // Set up XML deserialization 
    try {
        context = JAXBContext.newInstance(TueppToken.class);
        unmarshaller = context.createUnmarshaller();
        xmlInputFactory = XMLInputFactory.newInstance();
    } catch (JAXBException e) {
        throw new ResourceInitializationException(e);
    }

    // Seek first article
    try {
        step();
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.MathMLCanonicalizer.java

/**
 * Loads configuration from XML file, overriding the properties.
 *//*from   www.j a  v a2 s.  co  m*/
private void loadXMLConfiguration(InputStream xmlConfigurationStream)
        throws ConfigException, XMLStreamException {
    assert xmlConfigurationStream != null;
    final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    final XMLStreamReader reader = inputFactory.createXMLStreamReader(xmlConfigurationStream);

    boolean config = false;
    Module module = null;
    while (reader.hasNext()) {
        final int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT: {
            String name = reader.getLocalName();
            if (name.equals("config")) {
                config = true;
                break;
            }

            if (config && name.equals("module")) {
                if (reader.getAttributeCount() == 1) {
                    final String attributeName = reader.getAttributeLocalName(0);
                    final String attributeValue = reader.getAttributeValue(0);

                    if (attributeName.equals("name") && attributeValue != null) {
                        String fullyQualified = Settings.class.getPackage().getName() + ".modules."
                                + attributeValue;
                        try {
                            Class<?> moduleClass = Class.forName(fullyQualified);
                            module = (Module) moduleClass.newInstance();
                        } catch (InstantiationException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot instantiate module " + attributeValue, ex);
                        } catch (IllegalAccessException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot access module " + attributeValue, ex);
                        } catch (ClassNotFoundException ex) {
                            LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
                            throw new ConfigException("cannot load module " + attributeValue, ex);
                        }
                    }
                }
            }

            if (config && name.equals("property")) {
                if (reader.getAttributeCount() == 1) {
                    final String attributeName = reader.getAttributeLocalName(0);
                    final String attributeValue = reader.getAttributeValue(0);

                    if (attributeName.equals("name") && attributeValue != null) {
                        if (module == null) {
                            if (Settings.isProperty(attributeValue)) {
                                Settings.setProperty(attributeValue, reader.getElementText());
                            } else {
                                throw new ConfigException("configuration not valid\n"
                                        + "Tried to override non-existing global property " + attributeValue);
                            }
                        } else {
                            if (module.isProperty(attributeValue)) {
                                module.setProperty(attributeValue, reader.getElementText());
                            } else {
                                throw new ConfigException("configuration not valid\n"
                                        + "configuration tried to override non-existing property "
                                        + attributeValue);
                            }
                        }
                    }
                }
            }

            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            if (config && reader.getLocalName().equals("module")) {
                addModule(module);

                module = null;
            }

            if (config && reader.getLocalName().equals("config")) {
                config = false;
            }
        }
        }
    }
}

From source file:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterImpl.java

private Map<String, CtClass> createClasses(final Map<String, Class<?>> existingClasses,
        final InputStream stream) throws XMLStreamException {
    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
    Map<String, CtClass> ctClasses = new HashMap<String, CtClass>();

    while (reader.hasNext() && reader.next() > 0) {
        if (isTagStarted(reader, TAG_MODEL)) {
            String pluginIdentifier = getPluginIdentifier(reader);
            String modelName = getStringAttribute(reader, L_NAME);
            String className = ClassNameUtils.getFullyQualifiedClassName(pluginIdentifier, modelName);

            if (existingClasses.containsKey(className)) {
                LOG.info("Class " + className + " already exists, skipping");
            } else {
                LOG.info("Creating class " + className);
                ctClasses.put(className, classPool.makeClass(className));
            }/*from  w  w  w  . j  av a  2  s. c  o m*/

            break;
        }
    }

    reader.close();

    return ctClasses;
}

From source file:demo.SourceHttpMessageConverter.java

private Source readStAXSource(InputStream body) {
    try {//from w  w w. j av  a2  s .c o  m
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, isSupportDtd());
        inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, isProcessExternalEntities());
        if (!isProcessExternalEntities()) {
            inputFactory.setXMLResolver(NO_OP_XML_RESOLVER);
        }
        XMLStreamReader streamReader = inputFactory.createXMLStreamReader(body);
        return new StAXSource(streamReader);
    } catch (XMLStreamException ex) {
        throw new HttpMessageNotReadableException("Could not parse document: " + ex.getMessage(), ex);
    }
}

From source file:com.norconex.collector.http.sitemap.impl.DefaultSitemapResolver.java

private void parseLocation(InputStream is, DefaultHttpClient httpClient, SitemapURLStore sitemapURLStore,
        Set<String> resolvedLocations, String location) throws XMLStreamException {

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
    XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is);
    ParseState parseState = new ParseState();

    String locationDir = StringUtils.substringBeforeLast(location, "/");
    int event = xmlReader.getEventType();
    while (true) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            String tag = xmlReader.getLocalName();
            parseStartElement(parseState, tag);
            break;
        case XMLStreamConstants.CHARACTERS:
            String value = xmlReader.getText();
            if (parseState.sitemapIndex && parseState.loc) {
                resolveLocation(value, httpClient, sitemapURLStore, resolvedLocations);
                parseState.loc = false;//  w w  w . ja  v  a 2s  . co  m
            } else if (parseState.baseURL != null) {
                parseCharacters(parseState, value);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            tag = xmlReader.getLocalName();
            parseEndElement(sitemapURLStore, parseState, locationDir, tag);
            break;
        }
        if (!xmlReader.hasNext()) {
            break;
        }
        event = xmlReader.next();
    }
}

From source file:com.hp.mqm.clt.XmlProcessorTest.java

private void assertXml(List<TestResult> expectedTestResults, Set<XmlElement> expectedElements, File xmlFile)
        throws FileNotFoundException, XMLStreamException {
    FileInputStream fis = new FileInputStream(xmlFile);
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    xmlInputFactory.setProperty("javax.xml.stream.isCoalescing", true);
    XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(fis);

    boolean isFirstEvent = true;
    while (xmlStreamReader.hasNext()) {
        if (!isFirstEvent) {
            xmlStreamReader.next();//from  ww w  .  j  a  va  2 s  . com
        } else {
            isFirstEvent = false;
        }

        if (xmlStreamReader.getEventType() == XMLStreamReader.START_ELEMENT) {
            String localName = xmlStreamReader.getLocalName();
            if ("taxonomy".equals(localName)) {
                assertElement(localName, false, xmlStreamReader, expectedElements);
            } else if ("test_field".equals(localName)) {
                assertElement(localName, false, xmlStreamReader, expectedElements);
            } else if ("product_area_ref".equals(localName)) {
                assertElement(localName, true, xmlStreamReader, expectedElements);
            } else if ("backlog_item_ref".equals(localName)) {
                assertElement(localName, true, xmlStreamReader, expectedElements);
            } else if ("release_ref".equals(localName)) {
                assertElement(localName, true, xmlStreamReader, expectedElements);
            } else if ("test_run".equals(localName)) {
                assertXmlTest(xmlStreamReader, expectedTestResults);
            }
        }
    }
    xmlStreamReader.close();
    IOUtils.closeQuietly(fis);
    Assert.assertTrue(expectedElements.isEmpty());
    Assert.assertTrue(expectedTestResults.isEmpty());
}

From source file:net.landora.video.info.file.FileInfoManager.java

private synchronized Map<String, FileInfo> parseCacheFile(File file) {
    InputStream is = null;/*from  w w  w  . j a v a  2 s. c o m*/
    try {
        is = new BufferedInputStream(new FileInputStream(file));
        if (COMPRESS_INFO_FILE) {
            is = new GZIPInputStream(is);
        }

        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(is);

        reader.nextTag();
        reader.require(XMLStreamReader.START_ELEMENT, null, "files");

        Map<String, FileInfo> files = new HashMap<String, FileInfo>();

        while (reader.nextTag() != XMLStreamReader.END_ELEMENT) {
            reader.require(XMLStreamReader.START_ELEMENT, null, "file");

            FileInfo info = new FileInfo();
            String filename = reader.getAttributeValue(null, "filename");
            info.setFilename(filename);
            info.setE2dkHash(reader.getAttributeValue(null, "ed2k"));
            info.setFileSize(Long.parseLong(reader.getAttributeValue(null, "length")));
            info.setLastModified(Long.parseLong(reader.getAttributeValue(null, "lastmodified")));
            info.setMetadataSource(reader.getAttributeValue(null, "metadatasource"));
            info.setMetadataId(reader.getAttributeValue(null, "metadataid"));
            info.setVideoId(reader.getAttributeValue(null, "videoid"));

            files.put(filename, info);

            XMLUtilities.ignoreTag(reader);

        }
        reader.close();

        return files;

    } catch (Exception e) {
        log.error("Error parsing file cache.", e);
        return new HashMap<String, FileInfo>();
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }
    }
}