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:org.jabref.logic.importer.fileformat.MedlineImporter.java

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

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

    try {//from  ww w.j av  a 2 s.  c o m
        JAXBContext context = JAXBContext.newInstance("org.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.fromError(e);
    }
    return new ParserResult(bibItems);
}

From source file:org.jahia.utils.migration.Migrators.java

private <T> T unmarshal(Class<T> docClass, InputStream inputStream) throws JAXBException, XMLStreamException {
    JAXBContext jc = JAXBContext.newInstance(docClass);
    Unmarshaller u = jc.createUnmarshaller();

    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(inputStream);

    T doc = (T) u.unmarshal(xmlStreamReader);
    return doc;/*from  ww  w.  ja  v  a2 s.  co  m*/
}

From source file:org.jasig.schedassist.impl.caldav.xml.ReportResponseHandlerImpl.java

/**
 * Extracts a {@link List} of {@link Calendar}s from the {@link InputStream}, if present.
 * //from ww  w  . ja v  a  2  s.  c  om
 * @param inputStream
 * @return a never null, but possibly empty {@link List} of {@link Calendar}s from the {@link InputStream}
 * @throws XmlParsingException in the event the stream could not be properly parsed
 */
public List<CalendarWithURI> extractCalendars(InputStream inputStream) {
    List<CalendarWithURI> results = new ArrayList<CalendarWithURI>();
    ByteArrayOutputStream capturedContent = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        InputStream localReference = inputStream;
        if (log.isDebugEnabled()) {
            capturedContent = new ByteArrayOutputStream();
            localReference = new TeeInputStream(inputStream, capturedContent);
        }
        BufferedInputStream buffered = new BufferedInputStream(localReference);
        buffered.mark(1);
        int firstbyte = buffered.read();
        if (-1 == firstbyte) {
            // short circuit on empty stream
            return results;
        }
        buffered.reset();
        XMLStreamReader parser = factory.createXMLStreamReader(buffered);

        String currentUri = null;
        String currentEtag = null;
        for (int eventType = parser.next(); eventType != XMLStreamConstants.END_DOCUMENT; eventType = parser
                .next()) {
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                QName name = parser.getName();
                if (isWebdavHrefElement(name)) {
                    currentUri = parser.getElementText();
                } else if (isWebdavEtagElement(name)) {
                    currentEtag = parser.getElementText();
                } else if (isCalendarDataElement(name)) {
                    Calendar cal = extractCalendar(parser.getElementText());
                    if (cal != null) {
                        CalendarWithURI withUri = new CalendarWithURI(cal, currentUri, currentEtag);
                        results.add(withUri);
                    } else if (log.isDebugEnabled()) {
                        log.debug("extractCalendar returned null for " + currentUri + ", skipping");
                    }
                }
                break;
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("extracted " + results.size() + " calendar from " + capturedContent.toString());
        }

    } catch (XMLStreamException e) {
        if (capturedContent != null) {
            log.error("caught XMLStreamException in extractCalendars, captured content: "
                    + capturedContent.toString(), e);
        } else {
            log.error("caught XMLStreamException in extractCalendars, no captured content available", e);
        }
        throw new XmlParsingException("caught XMLStreamException in extractCalendars", e);
    } catch (IOException e) {
        log.error("caught IOException in extractCalendars", e);
        throw new XmlParsingException("caught IOException in extractCalendars", e);
    }

    return results;
}

From source file:org.jboss.loom.migrators.logging.LoggingMigrator.java

@Override
public void loadSourceServerConfig(MigrationContext ctx) throws LoadMigrationException {
    try {/*from   ww  w. ja  va 2  s. c o m*/
        File log4jConfFile = Utils.createPath(
                //super.getGlobalConfig().getAS5Config().getDir(),  "server",
                //super.getGlobalConfig().getAS5Config().getProfileName(),
                //"conf", "jboss-log4j.xml");
                super.getGlobalConfig().getAS5Config().getConfDir(), "jboss-log4j.xml");

        XMLInputFactory xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(log4jConfFile));

        //if( ! log4jConfFile.canRead())
        //    throw new LoadMigrationException("Cannot find/open file: " + log4jConfFile.getAbsolutePath());

        Unmarshaller unmarshaller = JAXBContext.newInstance(LoggingAS5Bean.class).createUnmarshaller();
        LoggingAS5Bean loggingAS5 = (LoggingAS5Bean) unmarshaller.unmarshal(xsr);

        MigratorData mData = new MigratorData();

        if (loggingAS5.getCategories() != null) {
            mData.getConfigFragments().addAll(loggingAS5.getCategories());
        }

        if (loggingAS5.getLoggers() != null) {
            mData.getConfigFragments().addAll(loggingAS5.getLoggers());
        }

        mData.getConfigFragments().addAll(loggingAS5.getAppenders());
        mData.getConfigFragments().add(loggingAS5.getRootLoggerAS5());

        ctx.getMigrationData().put(LoggingMigrator.class, mData);
    } catch (JAXBException | XMLStreamException e) {
        throw new LoadMigrationException(e);
    }
}

From source file:org.miloss.fgsms.presentation.Helper.java

public static ServicePolicy ImportServicePolicy(String pol, PolicyType pt) {
        try {//  w  ww.j av a 2 s  .c  o  m
            JAXBContext jc = Utility.getSerializationContext();

            Unmarshaller u = jc.createUnmarshaller();

            ByteArrayInputStream bss = new ByteArrayInputStream(pol.getBytes(Constants.CHARSET));
            //1 = reader
            //2 = writer
            XMLInputFactory xf = XMLInputFactory.newInstance();
            XMLStreamReader r = xf.createXMLStreamReader(bss);

            //        com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl r = new com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl(bss, new com.sun.org.apache.xerces.internal.impl.PropertyManager(1));

            switch (pt) {
            case MACHINE:
                JAXBElement<MachinePolicy> foo = (JAXBElement<MachinePolicy>) u.unmarshal(r, MachinePolicy.class);
                bss.close();
                if (foo != null && foo.getValue() != null) {
                    return foo.getValue();
                }
                break;
            case PROCESS:
                JAXBElement<ProcessPolicy> foo2 = (JAXBElement<ProcessPolicy>) u.unmarshal(r, ProcessPolicy.class);
                bss.close();
                if (foo2 != null && foo2.getValue() != null) {
                    return foo2.getValue();
                }
                break;
            case STATISTICAL:
                JAXBElement<StatisticalServicePolicy> foo3 = (JAXBElement<StatisticalServicePolicy>) u.unmarshal(r,
                        StatisticalServicePolicy.class);
                bss.close();
                if (foo3 != null && foo3.getValue() != null) {
                    return foo3.getValue();
                }
                break;
            case STATUS:
                JAXBElement<StatusServicePolicy> foo4 = (JAXBElement<StatusServicePolicy>) u.unmarshal(r,
                        StatusServicePolicy.class);
                bss.close();
                if (foo4 != null && foo4.getValue() != null) {
                    return foo4.getValue();
                }
                break;
            case TRANSACTIONAL:
                JAXBElement<TransactionalWebServicePolicy> foo5 = (JAXBElement<TransactionalWebServicePolicy>) u
                        .unmarshal(r, TransactionalWebServicePolicy.class);
                bss.close();
                if (foo5 != null && foo5.getValue() != null) {
                    return foo5.getValue();
                }
                break;
            }
            bss.close();
            Logger.getLogger(Helper.class).log(Level.WARN, "ServicePolicy is unexpectedly null or empty");
            return null;
        } catch (Exception ex) {
            Logger.getLogger(Helper.class).log(Level.ERROR, null, ex);
        }
        return null;

    }

From source file:org.modeldriven.fuml.xmi.stream.StreamReader.java

@SuppressWarnings("unchecked")
public Collection read(InputStream stream) {
    List<Object> results = new ArrayList<Object>();
    InputStream source = stream;/*w w  w  .j  a v  a  2  s .  co  m*/
    StreamContext context = null;

    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();

        factory.setXMLResolver(new XMLResolver() {

            @Override
            public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace)
                    throws XMLStreamException {
                // TODO Auto-generated method stub
                return null;
            }

        });

        /*
        XStream xstream = new XStream(new StaxDriver() {
           protected XMLStreamReader createParser(Reader xml) throws
           XMLStreamException {
           return getInputFactory().createXMLStreamReader(xml);
           }
           protected XMLStreamReader createParser(InputStream xml) throws
           XMLStreamException {
           return getInputFactory().createXMLStreamReader(xml);
           }
           });
        */

        //factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,Boolean.FALSE);
        //factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,Boolean.TRUE);
        //set the IS_COALESCING property to true , if application desires to
        //get whole text data as one event.            
        //factory.setProperty(XMLInputFactory.IS_COALESCING , Boolean.TRUE);

        factory.setEventAllocator(new EventAllocator());

        allocator = factory.getEventAllocator();
        XMLStreamReader streamReader = factory.createXMLStreamReader(stream);

        int eventType = streamReader.getEventType();
        StreamNode node = null;
        StreamNode parent = null;
        int level = 0;
        int ignoredNodeLevel = -1;

        while (streamReader.hasNext()) {
            eventType = streamReader.next();
            //if (log.isDebugEnabled())
            //    log.debug(this.getEventTypeString(eventType));

            switch (eventType) {
            case XMLEvent.START_ELEMENT:
                level++;
                if (ignoredNodeLevel >= 0)
                    break;

                XMLEvent event = allocateXMLEvent(streamReader);
                if (level == 1) {
                    if (context != null)
                        throw new XmiException("existing context unexpected");
                    context = new StreamContext(event);
                }

                // debugging
                if (event.toString().contains("plasma:PlasmaType")) {
                    int foo = 1;
                    foo++;
                }

                node = new StreamNode(event, context);
                if (node.isIgnored()) {
                    if (log.isDebugEnabled()) {
                        Location loc = event.getLocation();
                        String msg = "start ignoring elements - level:  " + String.valueOf(level)
                                + " - line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber() + "] - ";
                        log.debug(msg);
                    }
                    ignoredNodeLevel = level;
                    break;
                }

                logEventInfo(event);
                parent = null;
                if (nodes.size() > 0) {
                    parent = nodes.peek();
                    parent.add(node);
                    node.setParent(parent);
                    if (isRootNode(node, context))
                        results.add(node);
                } else {
                    if (isRootNode(node, context))
                        results.add(node);
                }

                nodes.push(node);
                fireStreamNodeCreated(node, parent);
                break;
            case XMLEvent.END_ELEMENT:
                if (ignoredNodeLevel >= 0) {
                    if (ignoredNodeLevel == level) {
                        if (log.isDebugEnabled()) {
                            event = allocateXMLEvent(streamReader);
                            Location loc = event.getLocation();
                            String msg = "end ignoring elements - level:  " + String.valueOf(level)
                                    + " - line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber()
                                    + "] - ";
                            log.debug(msg);
                        }
                        ignoredNodeLevel = -1;
                    }
                    level--;
                    break;
                }

                level--;
                node = nodes.pop();
                parent = null;
                if (nodes.size() > 0)
                    parent = nodes.peek();
                fireStreamNodeCompleted(node, parent);
                break;
            case XMLEvent.CHARACTERS:
                if (ignoredNodeLevel >= 0)
                    break;
                node = nodes.peek();
                event = allocateXMLEvent(streamReader);
                String data = event.asCharacters().getData();
                if (data != null) {
                    data = data.trim();
                    if (data.length() > 0) {
                        if (log.isDebugEnabled())
                            log.debug("CHARACTERS: '" + data + "'");
                        if (data.length() > 0) {
                            node = nodes.peek();
                            node.addCharactersEvent(event);
                        }
                    }
                }
                break;
            default:
                if (log.isDebugEnabled()) {
                    event = allocateXMLEvent(streamReader);
                    logEventInfo(event);
                }
                break;
            }
        }
        if (results.size() > 1)
            throw new XmiException("found multiple root nodes (" + results.size() + ")");
    } catch (XMLStreamException e) {
        throw new XmiException(e);
    } finally {
        try {
            source.close();
        } catch (IOException e) {
        }
    }

    return results;
}

From source file:org.mule.module.xml.util.XMLUtils.java

/**
 * Returns an XMLStreamReader for an object of unknown type if possible.
 * @return null if no XMLStreamReader can be created for the object type
 * @throws XMLStreamException/*from ww w . j  a  va 2s .c  o  m*/
 */
public static javax.xml.stream.XMLStreamReader toXMLStreamReader(javax.xml.stream.XMLInputFactory factory,
        Object obj) throws XMLStreamException {
    if (obj instanceof javax.xml.stream.XMLStreamReader) {
        return (javax.xml.stream.XMLStreamReader) obj;
    } else if (obj instanceof org.mule.module.xml.stax.StaxSource) {
        return ((org.mule.module.xml.stax.StaxSource) obj).getXMLStreamReader();
    } else if (obj instanceof javax.xml.transform.Source) {
        return factory.createXMLStreamReader((javax.xml.transform.Source) obj);
    } else if (obj instanceof org.xml.sax.InputSource) {
        return factory.createXMLStreamReader(((org.xml.sax.InputSource) obj).getByteStream());
    } else if (obj instanceof org.w3c.dom.Document) {
        return factory.createXMLStreamReader(new javax.xml.transform.dom.DOMSource((org.w3c.dom.Document) obj));
    } else if (obj instanceof org.dom4j.Document) {
        return factory.createXMLStreamReader(new org.dom4j.io.DocumentSource((org.dom4j.Document) obj));
    } else if (obj instanceof java.io.InputStream) {
        final InputStream is = (java.io.InputStream) obj;

        XMLStreamReader xsr = factory.createXMLStreamReader(is);
        return new DelegateXMLStreamReader(xsr) {
            @Override
            public void close() throws XMLStreamException {
                super.close();

                try {
                    is.close();
                } catch (IOException e) {
                    throw new XMLStreamException(e);
                }
            }

        };
    } else if (obj instanceof String) {
        return factory.createXMLStreamReader(new StringReader((String) obj));
    } else if (obj instanceof byte[]) {
        // TODO Handle encoding/charset?
        return factory.createXMLStreamReader(new ByteArrayInputStream((byte[]) obj));
    } else {
        return null;
    }
}

From source file:org.mule.module.xml.util.XMLUtils.java

/**
 * Convert our object to a Source type efficiently.
 *//*from www. ja v a 2  s .co m*/
public static javax.xml.transform.Source toXmlSource(javax.xml.stream.XMLInputFactory xmlInputFactory,
        boolean useStaxSource, Object src) throws Exception {
    if (src instanceof javax.xml.transform.Source) {
        return (Source) src;
    } else if (src instanceof byte[]) {
        ByteArrayInputStream stream = new ByteArrayInputStream((byte[]) src);
        return toStreamSource(xmlInputFactory, useStaxSource, stream);
    } else if (src instanceof InputStream) {
        return toStreamSource(xmlInputFactory, useStaxSource, (InputStream) src);
    } else if (src instanceof String) {
        if (useStaxSource) {
            return new StaxSource(xmlInputFactory.createXMLStreamReader(new StringReader((String) src)));
        } else {
            return new StreamSource(new StringReader((String) src));
        }
    } else if (src instanceof org.dom4j.Document) {
        return new DocumentSource((org.dom4j.Document) src);
    } else if (src instanceof org.xml.sax.InputSource) {
        return new SAXSource((InputSource) src);
    }
    // TODO MULE-3555
    else if (src instanceof XMLStreamReader) {
        XMLStreamReader xsr = (XMLStreamReader) src;

        // StaxSource requires that we advance to a start element/document event
        if (!xsr.isStartElement() && xsr.getEventType() != XMLStreamConstants.START_DOCUMENT) {
            xsr.nextTag();
        }

        return new StaxSource((XMLStreamReader) src);
    } else if (src instanceof org.w3c.dom.Document || src instanceof org.w3c.dom.Element) {
        return new DOMSource((org.w3c.dom.Node) src);
    } else if (src instanceof DelayedResult) {
        DelayedResult result = ((DelayedResult) src);
        DOMResult domResult = new DOMResult();
        result.write(domResult);
        return new DOMSource(domResult.getNode());
    } else if (src instanceof OutputHandler) {
        OutputHandler handler = ((OutputHandler) src);
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        handler.write(RequestContext.getEvent(), output);

        return toStreamSource(xmlInputFactory, useStaxSource, new ByteArrayInputStream(output.toByteArray()));
    } else {
        return null;
    }
}

From source file:org.mule.module.xml.util.XMLUtils.java

public static javax.xml.transform.Source toStreamSource(javax.xml.stream.XMLInputFactory xmlInputFactory,
        boolean useStaxSource, InputStream stream) throws XMLStreamException {
    if (useStaxSource) {
        return new org.mule.module.xml.stax.StaxSource(xmlInputFactory.createXMLStreamReader(stream));
    } else {/* w  w  w  . jav  a 2  s  . c o  m*/
        return new javax.xml.transform.stream.StreamSource(stream);
    }
}

From source file:org.mule.transport.sap.transformer.XmlToJcoFunctionTransformer.java

public JCoFunction transform(InputStream stream, String encoding) throws XMLStreamException {

    XMLStreamReader reader = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    String functionName = null;//from   w  w w  .j  a v  a2  s  .co  m
    String tableName = null;
    String structureName = null;
    String rowId = null;
    String fieldName = null;
    String value = null;

    JCoFunction function = null;

    try {
        reader = factory.createXMLStreamReader(stream);
        String localName = null;
        while (reader.hasNext()) {
            int eventType = reader.next();

            if (eventType == XMLStreamReader.START_DOCUMENT) {
                // find START_DOCUMENT

            } else if (eventType == XMLStreamReader.START_ELEMENT) {
                // find START_ELEMENT
                localName = reader.getLocalName();

                logger.debug("START ELEMENT IS FOUND");
                logger.debug("start localName = " + localName);

                if (localName.equals(MessageConstants.JCO)) {
                    functionName = getAttributeValue(MessageConstants.JCO_ATTR_NAME, reader);

                    try {
                        function = this.connector.getAdapter().getFunction(functionName);
                    } catch (JCoException e) {
                        throw new XMLStreamException(e);
                    }
                    logger.debug("function name:" + functionName);

                } else if (functionName != null) {
                    if (localName.equals(MessageConstants.IMPORT)) {
                        //recordType = IMPORT;

                        push(function.getImportParameterList());
                    } else if (localName.equals(MessageConstants.EXPORT)) {
                        //recordType = EXPORT;

                        push(function.getExportParameterList());
                    } else if (localName.equals(MessageConstants.TABLES)) {
                        //recordType = TABLES;
                        tableName = null;
                        push(function.getTableParameterList());

                    } else if (localName.equals(MessageConstants.TABLE)) {
                        if (tableName != null) {
                            pop();
                        }
                        tableName = getAttributeValue(MessageConstants.TABLE_ATTR_NAME, reader);

                        logger.debug("tableName = " + tableName);
                        push(this.record.getTable(tableName));
                    } else if (localName.equals(MessageConstants.STRUCTURE)) {
                        structureName = getAttributeValue(MessageConstants.STRUCTURE_ATTR_NAME, reader);
                        push(this.record.getStructure(structureName));
                    } else if (localName.equals(MessageConstants.ROW)) {
                        rowId = getAttributeValue(MessageConstants.ROW_ATTR_ID, reader);
                        logger.debug("rowId = " + rowId);
                        if (this.record instanceof JCoTable) {
                            ((JCoTable) this.record).appendRow();
                        }
                    } else if (localName.equals(MessageConstants.FIELD)) {
                        fieldName = getAttributeValue(MessageConstants.STRUCTURE_ATTR_NAME, reader);
                        value = reader.getElementText().trim(); // get an element value
                        logger.debug("FieldName = " + fieldName);
                        logger.debug("value = " + value);

                        this.record.setValue(fieldName, value);

                    }
                }

            } else if (eventType == XMLStreamReader.END_DOCUMENT) {

                // find END_DOCUMENT
                logger.debug("END DOCUMENT IS FOUND");
            } else if (eventType == XMLStreamReader.END_ELEMENT) {
                logger.debug("END ELEMENT IS FOUND");
                logger.debug("end localName = " + localName);
                // find END_ELEMENT
                if (localName.equals(MessageConstants.IMPORT) || localName.equals(MessageConstants.EXPORT)
                        || localName.equals(MessageConstants.TABLES) || localName.equals(MessageConstants.TABLE)
                        || localName.equals(MessageConstants.STRUCTURE)) {
                    pop();
                }
            }
        }
    } catch (Exception e) {
        logger.fatal(e);
        throw new TransformerException(this, e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (XMLStreamException ex) {
            }
        }
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException ex) {
            }
        }
        logger.debug("\n" + function.getImportParameterList().toXML());
        logger.debug("\n" + function.getExportParameterList().toXML());
        logger.debug("\n" + function.getTableParameterList().toXML());

        return function;
    }
}