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.sakaiproject.tags.impl.job.MeshTagsSyncJob.java

public synchronized void syncAllTags() {

    long start = System.currentTimeMillis();

    if (log.isInfoEnabled()) {
        log.info("Starting MESH Tag Collection synchronization");
    }/*w  w  w  . j a  v  a2 s. c o m*/
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader xsr = factory.createXMLStreamReader(getTagsXmlInputStream());
        xsr.next();
        xsr.nextTag();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();

        while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
            DOMResult result = new DOMResult();
            t.transform(new StAXSource(xsr), result);

            Node nNode = result.getNode();
            Element element = ((Document) nNode).getDocumentElement();
            String tagLabel = "undefined";
            counterTotal++;

            try {
                Element descriptorName = (Element) element.getElementsByTagName("DescriptorName").item(0);
                tagLabel = getString("String", descriptorName);
                String externalId = getString("DescriptorUI", element);
                String description = getString("Annotation", element);
                long externalCreationDate = xmlDateToMs(element.getElementsByTagName("DateCreated").item(0),
                        externalId);
                long lastUpdateDateInExternalSystem = xmlDateToMs(
                        element.getElementsByTagName("DateRevised").item(0), externalId);
                String externalHierarchyCode = xmlTreeToString(
                        element.getElementsByTagName("TreeNumberList").item(0), externalId);
                String externalType = element.getAttribute("DescriptorClass");
                String alternativeLabels = xmlToAlternativeLabels(
                        element.getElementsByTagName("ConceptList").item(0), externalId);
                updateOrCreateTagWithExternalSourceName(externalId, "MESH", tagLabel, description,
                        alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, null,
                        externalHierarchyCode, externalType, null);
                counterSuccess++;
                lastSuccessfulLabel = tagLabel;
            } catch (Exception e) {
                log.warn("Mesh XML can't be processed for this Label: " + tagLabel
                        + ". If the value is undefined, then, the previous successful label was: "
                        + lastSuccessfulLabel, e);
                sendStatusMail(2, e.getMessage());
            }
            if (counterTotal % 1000 == 0) {
                log.info(counterSuccess + "/" + counterTotal
                        + " labels processed correctly... and still processing. "
                        + (counterTotal - counterSuccess) + " errors by the moment");
            }

        } // end while
        xsr.close();
        updateTagCollectionSynchronization("MESH", 0L);
        deleteTagsOlderThanDateFromCollection("MESH", start);
        sendStatusMail(1, "Imported from MESH finished. Num of labels processed successfully " + counterSuccess
                + "of" + counterTotal);
    } catch (XMLStreamException ex) {
        log.warn("Mesh XML can't be processed", ex);
    } catch (Exception e) {
        log.warn("Mesh XML can't be processed", e);
        sendStatusMail(2, e.getMessage());
    }

    if (log.isInfoEnabled()) {
        log.info("Finished Mesh Tags synchronization in " + (System.currentTimeMillis() - start) + " ms");
    }
    counterTotal = 0;
    counterSuccess = 0;
    lastSuccessfulLabel = "";
}

From source file:org.sakaiproject.tags.impl.job.TagsExportedXMLSyncJob.java

public synchronized void syncAllTags() {

    long start = System.currentTimeMillis();

    if (log.isInfoEnabled()) {
        log.info("Starting Full XML Tag Collection synchronization");
    }//from ww  w . j  a v a 2s  .  c  om
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader xsr = factory.createXMLStreamReader(getTagsXmlInputStream());
        xsr.next();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();

        while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
            DOMResult result = new DOMResult();
            t.transform(new StAXSource(xsr), result);

            Node nNode = result.getNode();
            Element element = ((Document) nNode).getDocumentElement();

            String tagLabel = getString("tagLabel", element);
            String tagId = getString("tagId", element);
            String externalId = getString("externalId", element);
            String description = getString("description", element);
            long externalCreationDate = stringToLong(getString("externalCreationDate", element), 0L);
            long lastUpdateDateInExternalSystem = stringToLong(
                    getString("lastUpdateDateInExternalSystem", element), 0L);
            String externalHierarchyCode = getString("externalHierarchyCode", element);
            String externalType = getString("externalType", element);
            String alternativeLabels = getString("alternativeLabels", element);
            String tagCollectionId = getString("tagCollectionId", element);

            if (collectionToUpdate != null && !collectionToUpdateMoreThanOne) {
                if (!(collectionToUpdate.equals(tagCollectionId))) {
                    collectionToUpdateMoreThanOne = true;
                }
            } else {
                collectionToUpdate = tagCollectionId;
            }
            String data = getString("data", element);
            String parentId = getString("parentId", element);

            if (tagId != null && tagId.length() == VALID_ID_LENGTH) {
                if (tagWithIdIsPresent(tagId)) {
                    updateLabelWithId(tagId, externalId, tagCollectionId, tagLabel, description,
                            alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, parentId,
                            externalHierarchyCode, externalType, data);
                } else {
                    updateOrCreateTagWithCollectionId(externalId, tagCollectionId, tagLabel, description,
                            alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, parentId,
                            externalHierarchyCode, externalType, data);
                }
            } else {
                updateOrCreateTagWithCollectionId(externalId, tagCollectionId, tagLabel, description,
                        alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, parentId,
                        externalHierarchyCode, externalType, data);
            }
        }

        updateTagCollectionSynchronizationWithCollectionId(collectionToUpdate, 0L);
        //We will delete the old ones when there is only one collectionID in the file.
        if (collectionToUpdate != null && !collectionToUpdateMoreThanOne) {
            deleteTagsOlderThanDateFromCollectionWithCollectionId(collectionToUpdate, start);
        }
        sendStatusMail(1, "");
    } catch (Exception e) {
        log.warn("Full Tags XML can't be processed", e);
        sendStatusMail(2, e.getMessage());
    }

    String collectionToUpdate = null;
    Boolean collectionToUpdateMoreThanOne = false;
    if (log.isInfoEnabled()) {
        log.info("Finished Full XML Tags synchronization in " + (System.currentTimeMillis() - start) + " ms");
    }
}

From source file:org.sakaiproject.tags.impl.job.TagsSyncJob.java

public synchronized void syncAllTags() {

    long start = System.currentTimeMillis();

    if (log.isInfoEnabled()) {
        log.info("Starting Tag Collection synchronization");
    }//  w  w  w  . j  a va 2s .  c o m

    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader xsr = factory.createXMLStreamReader(getTagCollectionssXmlInputStream());
        xsr.next();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();

        while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
            DOMResult result = new DOMResult();
            t.transform(new StAXSource(xsr), result);

            Node nNode = result.getNode();
            Element element = ((Document) nNode).getDocumentElement();

            String name = getString("Name", element);
            log.debug("Found name: " + name);
            String description = getString("Description", element);
            log.debug("Found description : " + description);
            String externalSourceName = getString("ExternalSourceName", element);
            log.debug("externalSourceName: " + externalSourceName);
            String externalSourceDescription = getString("ExternalSourceDescription", element);
            log.debug("externalSourceDescription: " + externalSourceDescription);
            long lastUpdateDateInExternalSystem = xmlDateToMs(
                    element.getElementsByTagName("DateRevised").item(0), name);
            log.debug("lastUpdateDateInExternalSystem: " + lastUpdateDateInExternalSystem);

            updateOrCreateTagCollection(name, description, externalSourceName, externalSourceDescription,
                    lastUpdateDateInExternalSystem);
        }

        sendStatusMail(1, "");
    } catch (Exception e) {
        log.warn("Error Synchronizing the Tags from an xml file:", e);
        sendStatusMail(2, e.getMessage());
    }

    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader xsr = factory.createXMLStreamReader(getTagsXmlInputStream());
        xsr.next();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();

        while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
            DOMResult result = new DOMResult();
            t.transform(new StAXSource(xsr), result);

            Node nNode = result.getNode();
            Element element = ((Document) nNode).getDocumentElement();
            String action = element.getAttribute("Action");
            String tagLabel = getString("TagLabel", element);
            log.debug("Found tagLabel: " + tagLabel);
            String externalId = getString("ExternalId", element);
            log.debug("Found externalId: " + externalId);
            String description = getString("Description", element);
            log.debug("Found description : " + description);
            long externalCreationDate = xmlDateToMs(element.getElementsByTagName("DateCreated").item(0),
                    tagLabel);
            log.debug("externalCreationDate: " + externalCreationDate);
            long lastUpdateDateInExternalSystem = xmlDateToMs(
                    element.getElementsByTagName("DateRevised").item(0), tagLabel);
            log.debug("lastUpdateDateInExternalSystem: " + lastUpdateDateInExternalSystem);
            String externalHierarchyCode = getString("HierarchyCode", element);
            log.debug("externalHierarchyCode: " + externalHierarchyCode);
            String externalType = getString("Type", element);
            log.debug("externalType: " + externalType);
            String alternativeLabels = getString("AlternativeLabels", element);
            log.debug("alternativeLabels: " + alternativeLabels);
            String externalSourceName = getString("ExternalSourceName", element);
            log.debug("externalSourceName: " + externalSourceName);
            String data = getString("Data", element);
            log.debug("data: " + data);
            String parentId = getString("ParentId", element);
            log.debug("parentId: " + parentId);

            if (Objects.equals(action, "delete")) {
                deleteTagFromExternalCollection(externalId, externalSourceName);
            } else {
                updateOrCreateTagWithExternalSourceName(externalId, externalSourceName, tagLabel, description,
                        alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, parentId,
                        externalHierarchyCode, externalType, data);
            }

            updateTagCollectionSynchronization(externalSourceName, 0L);
        }
        sendStatusMail(1, "");
    } catch (Exception e) {
        log.warn("Error Synchronizing the Tags from an xml file:", e);
        sendStatusMail(2, e.getMessage());
    }
    if (log.isInfoEnabled()) {
        log.info("Finished Tags synchronization in " + (System.currentTimeMillis() - start) + " ms");
    }

}

From source file:org.silverpeas.core.admin.component.PersonalComponentRegistry.java

private static PersonalComponent loadComponent(File descriptor) {
    try {/*from   w ww .j a v  a2  s.co  m*/
        JAXBContext context = JAXBContext.newInstance("org.silverpeas.core.admin.component.model");
        Unmarshaller unmarshaller = context.createUnmarshaller();
        try (InputStream in = new FileInputStream(descriptor)) {
            XMLInputFactory factory = XMLInputFactory.newFactory();
            return (unmarshaller.unmarshal(factory.createXMLStreamReader(in), PersonalComponent.class))
                    .getValue();
        }
    } catch (IOException | JAXBException | XMLStreamException e) {
        throw new SilverpeasRuntimeException(e.getMessage(), e);
    }
}

From source file:org.silverpeas.core.admin.component.WAComponentRegistry.java

private static WAComponent loadComponent(File descriptor) {
    try {/*w ww.  j  a  v  a2 s  .  c o m*/
        JAXBContext context = JAXBContext.newInstance("org.silverpeas.core.admin.component.model");
        Unmarshaller unmarshaller = context.createUnmarshaller();
        try (InputStream in = new FileInputStream(descriptor)) {
            XMLInputFactory factory = XMLInputFactory.newFactory();
            return (unmarshaller.unmarshal(factory.createXMLStreamReader(in), WAComponent.class)).getValue();
        }
    } catch (IOException | JAXBException | XMLStreamException e) {
        throw new SilverpeasRuntimeException(e.getMessage(), e);
    }
}

From source file:org.slc.sli.api.resources.config.StAXMsgBodyReader.java

/**
 * Deserializer for XML => EntityBody
 * @param body xml as an input stream//from   w ww .  java2 s. c  o  m
 * @return a EntityBody object that corresponds to the xml
 * @throws XMLStreamException
 */
public EntityBody deserialize(final InputStream body) throws XMLStreamException {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    final XMLStreamReader reader = factory.createXMLStreamReader(body);
    try {
        return readDocument(reader);
    } finally {
        reader.close();
    }
}

From source file:org.slc.sli.modeling.wadl.reader.WadlReader.java

/**
 * Reads XMI from an {@link InputStream}.
 *
 * @param stream//from  w w w.j  a  v a  2 s.  com
 *            The {@link InputStream}.
 * @return The parsed {@link Model}.
 */
public static final Application readApplication(final InputStream stream) {
    if (stream == null) {
        throw new IllegalArgumentException("stream");
    }
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        final XMLStreamReader reader = factory.createXMLStreamReader(stream);
        try {
            return readDocument(reader);
        } finally {
            reader.close();
        }
    } catch (final XMLStreamException e) {
        throw new WadlRuntimeException(e);
    }
}

From source file:org.slc.sli.modeling.xmi.comp.XmiMappingReader.java

/**
 * Reads XMI from an {@link InputStream}.
 * //from  ww  w.  j  a v  a2  s  .c  o m
 * @param stream
 *            The {@link InputStream}.
 * @return The parsed {@link Model}.
 */
public static final XmiComparison readDocument(final InputStream stream) {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        final XMLStreamReader reader = factory.createXMLStreamReader(stream);
        try {
            return readDocument(reader);
        } finally {
            reader.close();
        }
    } catch (final XMLStreamException e) {
        throw new XmiCompRuntimeException(e);
    }
}

From source file:org.slc.sli.modeling.xmi.reader.XmiReader.java

/**
 * Reads XMI from an {@link InputStream}.
 *
 * @param stream//from   ww  w. j  av  a  2s .com
 *            The {@link InputStream}.
 * @return The parsed {@link Model}.
 */
public static final Model readModel(final InputStream stream) {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        final XMLStreamReader reader = factory.createXMLStreamReader(stream);
        try {
            return readDocument(reader);
        } finally {
            reader.close();
        }
    } catch (final XMLStreamException e) {
        throw new XmiRuntimeException(e);
    }
}

From source file:org.socraticgrid.workbench.ontomodel.service.SyntacticalOntoModelServiceImpl.java

/**
 * Extracts all the Fact Types used in a process definition.
 * Each Fact Type is declared as://from   w w w. j a v  a 2  s.  c om
 * 
 *   <bpmn2:textAnnotation id="_92807518-95EC-447B-A292-D46C9D5958E9">
 *       <bpmn2:text>KMRCustom--Diagnosis--code--49320</bpmn2:text>
 *   </bpmn2:textAnnotation>
 * 
 * In the previous example, Diagnosis is the Fact Type
 * 
 * @param processXml
 * @return
 * @throws XMLStreamException 
 */
private Set<String> getProcessFactTypesFromXml(String processXml) throws XMLStreamException {

    Set<String> facts = new HashSet<String>();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = factory.createXMLStreamReader(new ByteArrayInputStream(processXml.getBytes()));

    boolean parsingTextAnnotation = false;

    //<bpmn2:text>KMRCustom--Diagnosis--code--49320</bpmn2:text>
    while (reader.hasNext()) {
        switch (reader.next()) {
        case XMLStreamReader.START_ELEMENT:
            if ("bpmn2".equals(reader.getName().getPrefix())
                    && "textAnnotation".equals(reader.getName().getLocalPart())) {
                parsingTextAnnotation = true;
            }
            if (parsingTextAnnotation && "bpmn2".equals(reader.getName().getPrefix())
                    && "text".equals(reader.getName().getLocalPart())) {
                String text = reader.getElementText();
                if (text.startsWith("KMRCustom--")) {
                    String[] parts = text.split("--");
                    facts.add(parts[1]);
                }
            }
            break;
        case XMLStreamReader.END_ELEMENT:
            if ("bpmn2".equals(reader.getName().getPrefix())
                    && "textAnnotation".equals(reader.getName().getLocalPart())) {
                parsingTextAnnotation = false;
            }
        }
    }

    return facts;
}