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:org.sakaiproject.tags.impl.job.TagsSyncJob.java

public synchronized void syncAllTags() {

    long start = System.currentTimeMillis();

    if (log.isInfoEnabled()) {
        log.info("Starting Tag Collection synchronization");
    }//from  w  w w.  ja  va2  s  .c om

    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.sciflex.plugins.synapse.esper.mediators.AbstractTestCase.java

protected OMElement createOMElement(String xml) {
    try {/*from  w  w  w  .  j  ava 2s.c om*/

        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(xml));
        StAXOMBuilder builder = new StAXOMBuilder(reader);
        OMElement omElement = builder.getDocumentElement();
        return omElement;

    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.sciflex.plugins.synapse.esper.mediators.XMLMediator.java

/**
 * Invokes the mediator passing the current message for mediation.
 * @param mc Message Context of the current message.
 * @return returns true if mediation should continue, or false if further 
 * mediation should be aborted.//from  w ww  . j ava  2  s  .  c  o m
 */
public boolean mediate(MessageContext mc) {
    if (activityMonitor != null && !activityMonitor.getIsMediatorActive()) {
        log.warn("Cannot mediate. Mediator is inactive");
        return true;
    }
    long activityStamp = System.currentTimeMillis();
    log.trace("Beginning Mediation");
    // There is no providerLock in place at this point, to enable maximum
    // concurrent use of the mediate method. However, if someone is to
    // acquire a providerLock, that person must ensure that the mediate
    // method is not called.
    EPServiceProvider provider = getProvider();
    if (provider == null) {

        // There should be an error if we couldn't obtain the provider.
        // Therefore, stop mediation

        return false;
    }
    if (componentStore != null) {
        componentStore.invoke(mc);
    }
    eplStatementHelper.invoke(mc);
    // It takes this long to make the request.
    // You will have to setup all the required resources
    // to proceed with the servicing of the request.
    if (statMonitor != null) {
        long ts = System.currentTimeMillis();
        statMonitor.handleRequest(ts - activityStamp);
        activityStamp = ts;
    }
    OMElement bodyElement = null;
    try {
        bodyElement = mc.getEnvelope().getBody().getFirstElement();
    } catch (OMException e) {
        log.warn("An error occured while reading message " + e.getMessage());
        // We don't mind an error while reading a message.
        return true;
    }
    if (bodyElement == null) {
        // FIXME Figure out proper response for null element.
        return true;
    }
    bodyElement.build();

    try {
        String buffer = bodyElement.toStringWithConsume();
        XMLStreamReader xsr = XMLInputFactory.newInstance()
                .createXMLStreamReader(new ByteArrayInputStream(buffer.getBytes()));
        StAXOMBuilder builder = new StAXOMBuilder(DOOMAbstractFactory.getOMFactory(), xsr);
        OMElement docElement = builder.getDocumentElement();
        if (docElement != null) {
            Node node = (Node) docElement.getParent();
            provider.getEPRuntime().sendEvent(node);
            log.trace("Ending Mediation");
        } else
            log.error("Mediation failed");
    } catch (Exception e) {
        log.error("An error occured while sending Event " + e.getMessage());
    }
    // You have to get here to say the mediator responded.
    // All other returns are failures rather.
    if (statMonitor != null) {
        long ts = System.currentTimeMillis();
        statMonitor.handleResponse(ts - activityStamp);
    }
    return true;
}

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

/**
 * Deserializer for XML => EntityBody
 * @param body xml as an input stream/* w ww . j  a v a  2  s  . c  om*/
 * @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  2s. c  o  m*/
 *            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}.
 * // w w w.  j av 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/*w w w .  j a v  a  2  s  .  c  om*/
 *            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 www  . j  a v  a 2 s . c  o m*/
 * 
 *   <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;
}

From source file:org.sonar.api.profiles.XMLProfileParser.java

private SMInputFactory initStax() {
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
    // just so it won't try to load DTD in if there's DOCTYPE
    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
    return new SMInputFactory(xmlFactory);
}

From source file:org.sonar.api.rules.XMLRuleParser.java

public List<Rule> parse(Reader reader) {
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
    // just so it won't try to load DTD in if there's DOCTYPE
    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
    SMInputFactory inputFactory = new SMInputFactory(xmlFactory);
    try {/*from w w w .  j  ava2s .c  o m*/
        SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
        rootC.advance(); // <rules>
        List<Rule> rules = new ArrayList<Rule>();

        SMInputCursor rulesC = rootC.childElementCursor("rule");
        while (rulesC.getNext() != null) {
            // <rule>
            Rule rule = Rule.create();
            rules.add(rule);

            processRule(rule, rulesC);
        }
        return rules;

    } catch (XMLStreamException e) {
        throw new SonarException("XML is not valid", e);
    }
}