Example usage for javax.xml.stream XMLInputFactory createXMLStreamReader

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

Introduction

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

Prototype

public abstract XMLStreamReader createXMLStreamReader(java.io.InputStream stream) throws XMLStreamException;

Source Link

Document

Create a new XMLStreamReader from a java.io.InputStream

Usage

From source file:com.evolveum.midpoint.common.validator.Validator.java

public void validate(InputStream inputStream, OperationResult validatorResult,
        String objectResultOperationName) {

    XMLStreamReader stream = null;
    try {/*from   w ww. j a  v a 2  s .  c  om*/

        Map<String, String> rootNamespaceDeclarations = new HashMap<String, String>();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        stream = xmlInputFactory.createXMLStreamReader(inputStream);

        int eventType = stream.nextTag();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (!stream.getName().equals(SchemaConstants.C_OBJECTS)) {
                // This has to be an import file with a single objects. Try
                // to process it.
                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);

                EventResult cont = null;
                try {
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations,
                            validatorResult);
                } catch (RuntimeException e) {
                    // Make sure that unexpected error is recorded.
                    objectResult.recordFatalError(e);
                    throw e;
                }

                if (!cont.isCont()) {
                    String message = null;
                    if (cont.getReason() != null) {
                        message = cont.getReason();
                    } else {
                        message = "Object validation failed (no reason given)";
                    }
                    if (objectResult.isUnknown()) {
                        objectResult.recordFatalError(message);
                    }
                    validatorResult.recordFatalError(message);
                    return;
                }
                // return to avoid processing objects in loop
                validatorResult.computeStatus("Validation failed", "Validation warnings");
                return;
            }
            // Extract root namespace declarations
            for (int i = 0; i < stream.getNamespaceCount(); i++) {
                rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i));
            }
        } else {
            throw new SystemException("StAX Malfunction?");
        }

        while (stream.hasNext()) {
            eventType = stream.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {

                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);

                EventResult cont = null;
                try {
                    // Read and validate individual object from the stream
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations,
                            validatorResult);
                } catch (RuntimeException e) {
                    if (objectResult.isUnknown()) {
                        // Make sure that unexpected error is recorded.
                        objectResult.recordFatalError(e);
                    }
                    throw e;
                }

                if (objectResult.isError()) {
                    errors++;
                }

                objectResult.cleanupResult();
                validatorResult.summarize();

                if (cont.isStop()) {
                    if (cont.getReason() != null) {
                        validatorResult.recordFatalError("Processing has been stopped: " + cont.getReason());
                    } else {
                        validatorResult.recordFatalError("Processing has been stopped");
                    }
                    // This means total stop, no other objects will be
                    // processed
                    return;
                }
                if (!cont.isCont()) {
                    if (stopAfterErrors > 0 && errors >= stopAfterErrors) {
                        validatorResult.recordFatalError("Too many errors (" + errors + ")");
                        return;
                    }
                }
            }
        }

    } catch (XMLStreamException ex) {
        // validatorResult.recordFatalError("XML parsing error: " +
        // ex.getMessage()+" on line "+stream.getLocation().getLineNumber(),ex);
        validatorResult.recordFatalError("XML parsing error: " + ex.getMessage(), ex);
        if (handler != null) {
            handler.handleGlobalError(validatorResult);
        }
        return;
    }

    // Error count is sufficient. Detailed messages are in subresults
    validatorResult.computeStatus(errors + " errors, " + (progress - errors) + " passed");

}

From source file:de.uzk.hki.da.cb.CreatePremisAction.java

/**
 * Accepts a premis.xml file and creates a new xml file for each jhove section  
 * //from  w w  w  . j  a v a2 s. c om
 * @author Thomas Kleinke
 * Extract jhove data.
 *
 * @param premisFilePath the premis file path
 * @param outputFolder the output folder
 * @throws XMLStreamException the xML stream exception
 */
public void extractJhoveData(String premisFilePath, String outputFolder) throws XMLStreamException {

    outputFolder += "/premis_output/";

    FileInputStream inputStream = null;

    try {
        inputStream = new FileInputStream(premisFilePath);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Couldn't find file " + premisFilePath, e);
    }

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader streamReader = inputFactory.createXMLStreamReader(inputStream);

    boolean textElement = false;
    boolean jhoveSection = false;
    boolean objectIdentifierValue = false;
    int tab = 0;
    String fileId = "";

    while (streamReader.hasNext()) {
        int event = streamReader.next();

        switch (event) {

        case XMLStreamConstants.START_ELEMENT:

            if (streamReader.getLocalName().equals("jhove")) {
                jhoveSection = true;
                String outputFilePath = outputFolder + fileId.replace('/', '_').replace('.', '_') + ".xml";
                if (!new File(outputFolder).exists())
                    new File(outputFolder).mkdirs();
                writer = startNewDocument(outputFilePath);
            }

            if (streamReader.getLocalName().equals("objectIdentifierValue"))
                objectIdentifierValue = true;

            if (jhoveSection) {
                writer.writeDTD("\n");
                indent(tab);
                tab++;

                String prefix = streamReader.getPrefix();

                if (prefix != null && !prefix.equals("")) {
                    writer.setPrefix(prefix, streamReader.getNamespaceURI());
                    writer.writeStartElement(streamReader.getNamespaceURI(), streamReader.getLocalName());
                } else
                    writer.writeStartElement(streamReader.getLocalName());

                for (int i = 0; i < streamReader.getNamespaceCount(); i++)
                    writer.writeNamespace(streamReader.getNamespacePrefix(i), streamReader.getNamespaceURI(i));

                for (int i = 0; i < streamReader.getAttributeCount(); i++) {
                    QName qname = streamReader.getAttributeName(i);
                    String attributeName = qname.getLocalPart();
                    String attributePrefix = qname.getPrefix();
                    if (attributePrefix != null && !attributePrefix.equals(""))
                        attributeName = attributePrefix + ":" + attributeName;

                    writer.writeAttribute(attributeName, streamReader.getAttributeValue(i));
                }
            }

            break;

        case XMLStreamConstants.CHARACTERS:
            if (objectIdentifierValue) {
                fileId = streamReader.getText();
                objectIdentifierValue = false;
            }

            if (jhoveSection && !streamReader.isWhiteSpace()) {
                writer.writeCharacters(streamReader.getText());
                textElement = true;
            }
            break;

        case XMLStreamConstants.END_ELEMENT:
            if (jhoveSection) {
                tab--;

                if (!textElement) {
                    writer.writeDTD("\n");
                    indent(tab);
                }

                writer.writeEndElement();
                textElement = false;

                if (streamReader.getLocalName().equals("jhove")) {
                    jhoveSection = false;
                    finalizeDocument();
                }
            }
            break;

        case XMLStreamConstants.END_DOCUMENT:
            streamReader.close();
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException("Failed to close input stream", e);
            }
            break;

        default:
            break;
        }
    }
}

From source file:com.hp.alm.ali.rest.client.AliRestClient.java

private List<String> getAttributeValues(InputStream xml, String elemName, String attrName) {
    try {/*from   ww  w.  ja v a 2  s  . co  m*/
        XMLInputFactory factory = XmlUtils.createBasicInputFactory();
        XMLStreamReader parser;
        parser = factory.createXMLStreamReader(xml);
        List<String> result = new LinkedList<String>();
        while (true) {
            int event = parser.next();
            if (event == XMLStreamConstants.END_DOCUMENT) {
                parser.close();
                break;
            }
            if (event == XMLStreamConstants.START_ELEMENT && elemName.equals(parser.getLocalName())) {

                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String localName = parser.getAttributeLocalName(i);
                    if (attrName.equals(localName)) {
                        result.add(parser.getAttributeValue(i));
                        break;
                    }
                }
            }
        }
        return result;
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            xml.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:com.sun.socialsite.pojos.PropDefinition.java

protected void init(PropDefinition profileDef, InputStream input) throws SocialSiteException {
    try {/*w w w. j  av  a2s.  co m*/
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader parser = factory.createXMLStreamReader(input);
        String ns = null; // TODO: namespace for ProfileDef

        // hold the current things we're working on
        Map<String, DisplaySectionDefinition> sdefs = new LinkedHashMap<String, DisplaySectionDefinition>();
        Stack<PropertyDefinitionHolder> propertyHolderStack = new Stack<PropertyDefinitionHolder>();
        List<AllowedValue> allowedValues = null;
        PropertyDefinition pdef = null;

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                log.debug("START ELEMENT -- " + parser.getLocalName());

                if ("display-section".equals(parser.getLocalName())) {
                    propertyHolderStack.push(new DisplaySectionDefinition(parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey")));

                } else if ("property".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    pdef = new PropertyDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey"), parser.getAttributeValue(ns, "type"));

                } else if ("object".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    propertyHolderStack.push(new PropertyObjectDefinition(holder.getBasePath(),
                            parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")));

                } else if ("collection".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    propertyHolderStack.push(new PropertyObjectCollectionDefinition(holder.getBasePath(),
                            parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")));

                } else if ("allowed-values".equals(parser.getLocalName())) {
                    allowedValues = new ArrayList<AllowedValue>();

                } else if ("value".equals(parser.getLocalName())) {
                    AllowedValue allowedValue = new AllowedValue(parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey"));
                    allowedValues.add(allowedValue);

                } else if ("default-value".equals(parser.getLocalName())) {
                    pdef.setDefaultValue(parser.getText());
                }
                break;

            case XMLStreamConstants.END_ELEMENT:
                log.debug("END ELEMENT -- " + parser.getLocalName());

                if ("display-section".equals(parser.getLocalName())) {
                    DisplaySectionDefinition sdef = (DisplaySectionDefinition) propertyHolderStack.pop();
                    sdefs.put(sdef.getName(), sdef);

                } else if ("property".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyDefinitions().add(pdef);
                    propertyDefs.put(pdef.getName(), pdef);
                    pdef = null;

                } else if ("object".equals(parser.getLocalName())) {
                    PropertyObjectDefinition odef = (PropertyObjectDefinition) propertyHolderStack.pop();
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyObjectDefinitions().add(odef);

                    // add to list of all property object defs
                    propertyObjectDefs.put(odef.getName(), odef);
                    odef = null;

                } else if ("collection".equals(parser.getLocalName())) {
                    PropertyObjectCollectionDefinition cdef = (PropertyObjectCollectionDefinition) propertyHolderStack
                            .pop();
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyObjectCollectionDefinitions().add(cdef);

                    // add to list of all property object defs
                    propertyObjectCollectionDefs.put(cdef.getName(), cdef);
                    cdef = null;

                } else if ("allowed-values".equals(parser.getLocalName())) {
                    pdef.setAllowedValues(allowedValues);
                    allowedValues = null;
                }
                break;

            case XMLStreamConstants.CHARACTERS:
                break;

            case XMLStreamConstants.CDATA:
                break;

            } // end switch
        } // end while

        parser.close();

        profileDef.sectionDefs = sdefs;

    } catch (Exception ex) {
        throw new SocialSiteException("ERROR parsing profile definitions", ex);
    }
}

From source file:net.sf.jabref.importer.fileformat.MedlineImporter.java

@Override
public ParserResult importDatabase(BufferedReader reader) throws IOException {
    Objects.requireNonNull(reader);

    List<BibEntry> bibItems = new ArrayList<>();

    try {/*from  w ww  . j a  va2  s . c  om*/
        JAXBContext context = JAXBContext.newInstance("net.sf.jabref.importer.fileformat.medline");
        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader);

        //go to the root element
        while (!xmlStreamReader.isStartElement()) {
            xmlStreamReader.next();
        }

        Unmarshaller unmarshaller = context.createUnmarshaller();
        Object unmarshalledObject = unmarshaller.unmarshal(xmlStreamReader);

        //check whether we have an article set, an article, a book article or a book article set
        if (unmarshalledObject instanceof PubmedArticleSet) {
            PubmedArticleSet articleSet = (PubmedArticleSet) unmarshalledObject;
            for (Object article : articleSet.getPubmedArticleOrPubmedBookArticle()) {
                if (article instanceof PubmedArticle) {
                    PubmedArticle currentArticle = (PubmedArticle) article;
                    parseArticle(currentArticle, bibItems);
                }
                if (article instanceof PubmedBookArticle) {
                    PubmedBookArticle currentArticle = (PubmedBookArticle) article;
                    parseBookArticle(currentArticle, bibItems);
                }
            }
        } else if (unmarshalledObject instanceof PubmedArticle) {
            PubmedArticle article = (PubmedArticle) unmarshalledObject;
            parseArticle(article, bibItems);
        } else if (unmarshalledObject instanceof PubmedBookArticle) {
            PubmedBookArticle currentArticle = (PubmedBookArticle) unmarshalledObject;
            parseBookArticle(currentArticle, bibItems);
        } else {
            PubmedBookArticleSet bookArticleSet = (PubmedBookArticleSet) unmarshalledObject;
            for (PubmedBookArticle bookArticle : bookArticleSet.getPubmedBookArticle()) {
                parseBookArticle(bookArticle, bibItems);
            }
        }
    } catch (JAXBException | XMLStreamException e) {
        LOGGER.debug("could not parse document", e);
        return ParserResult.fromErrorMessage(e.getLocalizedMessage());
    }
    return new ParserResult(bibItems);
}

From source file:net.sf.jabref.logic.importer.fileformat.MedlineImporter.java

@Override
public ParserResult importDatabase(BufferedReader reader) throws IOException {
    Objects.requireNonNull(reader);

    List<BibEntry> bibItems = new ArrayList<>();

    try {//from  w  w  w  .j av a2  s  .  co m
        JAXBContext context = JAXBContext.newInstance("net.sf.jabref.logic.importer.fileformat.medline");
        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader);

        //go to the root element
        while (!xmlStreamReader.isStartElement()) {
            xmlStreamReader.next();
        }

        Unmarshaller unmarshaller = context.createUnmarshaller();
        Object unmarshalledObject = unmarshaller.unmarshal(xmlStreamReader);

        //check whether we have an article set, an article, a book article or a book article set
        if (unmarshalledObject instanceof PubmedArticleSet) {
            PubmedArticleSet articleSet = (PubmedArticleSet) unmarshalledObject;
            for (Object article : articleSet.getPubmedArticleOrPubmedBookArticle()) {
                if (article instanceof PubmedArticle) {
                    PubmedArticle currentArticle = (PubmedArticle) article;
                    parseArticle(currentArticle, bibItems);
                }
                if (article instanceof PubmedBookArticle) {
                    PubmedBookArticle currentArticle = (PubmedBookArticle) article;
                    parseBookArticle(currentArticle, bibItems);
                }
            }
        } else if (unmarshalledObject instanceof PubmedArticle) {
            PubmedArticle article = (PubmedArticle) unmarshalledObject;
            parseArticle(article, bibItems);
        } else if (unmarshalledObject instanceof PubmedBookArticle) {
            PubmedBookArticle currentArticle = (PubmedBookArticle) unmarshalledObject;
            parseBookArticle(currentArticle, bibItems);
        } else {
            PubmedBookArticleSet bookArticleSet = (PubmedBookArticleSet) unmarshalledObject;
            for (PubmedBookArticle bookArticle : bookArticleSet.getPubmedBookArticle()) {
                parseBookArticle(bookArticle, bibItems);
            }
        }
    } catch (JAXBException | XMLStreamException e) {
        LOGGER.debug("could not parse document", e);
        return ParserResult.fromErrorMessage(e.getLocalizedMessage());
    }
    return new ParserResult(bibItems);
}

From source file:com.liferay.portal.util.LocalizationImpl.java

private String _getRootAttribute(String xml, String name, String defaultValue) {

    String value = null;//from   w w  w .  ja v  a2  s.  c o  m

    XMLStreamReader xmlStreamReader = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            value = xmlStreamReader.getAttributeValue(null, name);
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }
    }

    if (Validator.isNull(value)) {
        value = defaultValue;
    }

    return value;
}

From source file:org.castor.jaxb.CastorUnmarshallerTest.java

/**
 * Tests the {@link CastorUnmarshaller#unmarshal(XMLStreamReader, Class)} method when declared type is null. <p/>
 * {@link IllegalArgumentException} is expected.
 *
 * @throws Exception if any error occurs during test
 *///from  w w w . j  a  va2 s  .  co m
@Test(expected = IllegalArgumentException.class)
public void testUnmarshalXMLStreamReaderJAXBElementNull2() throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader xmlStreamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_XML));

    unmarshaller.unmarshal(xmlStreamReader, null);
}

From source file:org.castor.jaxb.CastorUnmarshallerTest.java

/**
 * Tests the {@link CastorUnmarshaller#unmarshal(XMLStreamReader)} method.
 *
 * @throws Exception if any error occurs during test
 *//* www . j  a va2  s  .c o  m*/
@Test
public void testUnmarshalXMLStreamReader() throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader xmlStreamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_XML));

    Entity entity = (Entity) unmarshaller.unmarshal(xmlStreamReader);
    testEntity(entity);
}

From source file:org.castor.jaxb.CastorUnmarshallerTest.java

/**
 * Tests the {@link CastorUnmarshaller#unmarshal(XMLStreamReader, Class)} method.
 *
 * @throws Exception if any error occurs during test
 */// ww  w. j  a  va  2 s  .  co  m
@Test
public void testUnmarshalXMLStreamReaderJAXBElement() throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader xmlStreamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_XML));

    JAXBElement<Entity> entity = unmarshaller.unmarshal(xmlStreamReader, Entity.class);
    testJAXBElement(entity);
}