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:pl.hycom.pip.messanger.pipeline.PipelineManager.java

@Override
public void afterPropertiesSet() throws Exception {
    XMLInputFactory xif = XMLInputFactory.newFactory();
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    XMLStreamReader xsr = xif
            .createXMLStreamReader(new StreamSource(getClass().getResourceAsStream(pipelineFileURL)));

    pipeline = (Pipeline) JAXBContext.newInstance(Pipeline.class).createUnmarshaller().unmarshal(xsr);
}

From source file:pl.orange.labs.mundo.plugins.wms.dao.WmsWebDaoImpl.java

@Override
@Cacheable("mundoCache")
public WmsCapabilities getCapabilities(final String url) throws WmsException {
    try {/*from  w w  w  . ja v  a 2s.com*/

        LocalDefaultHttpClient httpClient = new LocalDefaultHttpClient();
        ResponseEntity<InputStream> response = httpClient.getHttpResponseInputStream(url,
                config.getIntValueForConfigVariable(ConfigService.HTTP_DEFAULT_CONNECT_TIMEOUT_KEY),
                config.getIntValueForConfigVariable(ConfigService.HTTP_DEFAULT_READ_TIMEOUT_KEY), 200);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("HTTP resppnse receivied " + response.getStatusCode());

        InputStream io = response.getBody();
        InputStreamEntity entity = new InputStreamEntity(io);

        String s = EntityUtils.toString(entity, "UTF-8");
        StringReader sr = new StringReader(s);

        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader xsr = xif.createXMLStreamReader(sr);

        JAXBContext jaxcontext = JAXBContext.newInstance(WmsCapabilities.class);
        Object objRsp = jaxcontext.createUnmarshaller().unmarshal(xsr);

        if (objRsp instanceof WmsCapabilities) {
            WmsCapabilities apiResp = (WmsCapabilities) objRsp;
            return apiResp;
        } else {
            LOGGER.error("ERROR - not possible to parse response WmsCapabilities from API resource");
            throw new WmsException("Bad response type!");
        }

    } catch (RestClientException ex) {
        LOGGER.error(ex);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("WMS: RestClientException", ex);
        throw new WmsException("Wms Capabilities error: " + ex.getMessage());
    }

    catch (JAXBException ex) {
        LOGGER.error(ex);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("WMS: JAXBException", ex);
        throw new WmsException("Wms Capabilities error: " + ex.getMessage());
    } catch (XMLStreamException ex) {
        LOGGER.error(ex);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("WMS: XMLStreamException", ex);
        throw new WmsException("Wms Capabilities error: " + ex.getMessage());
    } catch (IOException e) {
        LOGGER.error(e);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("WMS: IOException", e);
        throw new WmsException("Wms Capabilities error: " + e.getMessage());
    } catch (ConfigException e) {
        LOGGER.error(e);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("WMS: ConfigException", e);
        throw new WmsException("Wms Capabilities error: " + e.getMessage());
    }
}

From source file:source.YahooAnswersStreamParser.java

public YahooAnswersStreamParser(String fileName, boolean bDoCleanUp) throws IOException, XMLStreamException {
    mFile = new File(fileName);
    mDoCleanUp = bDoCleanUp;/*from  ww w .  ja  v a2 s .  com*/

    final XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.IS_COALESCING, true);
    InputStream is = CompressUtils.createInputStream(fileName);
    mReader = factory.createXMLStreamReader(new InvalidXmlCharFilter(new InputStreamReader(is, "UTF-8")));
    mNextDoc = fetchNext();
}

From source file:tkwatch.Utilities.java

/**
 * Finds the value of the named element, if any, in an XML string. Adapted
 * from Vohra and Vohra, <i>Pro XML Development with Java Technology</i>, p.
 * 47.// w  w w . j a  v a2  s.  co  m
 * 
 * @param desiredElementName
 *            The name of the element to search for in the XML string.
 * @param xmlString
 *            The XML string to search for an account number.
 * 
 * @return Returns the element value(s) as formatted in the incoming string
 *         (if found) as a <code>Vector<String></code>, <code>null</code>
 *         otherwise.
 */
public static final Vector<String> getValueFromXml(final String desiredElementName, final String xmlString) {
    Vector<String> elementValue = new Vector<String>();
    String elementValueText = null;
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    try {
        String elementName = "";
        StringReader stringReader = new StringReader(xmlString);
        XMLStreamReader reader = inputFactory.createXMLStreamReader(stringReader);
        while (reader.hasNext()) {
            int eventType = reader.getEventType();
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    elementValueText = reader.getAttributeValue(0);
                    System.out.println("START_ELEMENT case, element name is " + elementName
                            + ", element value is " + elementValueText);
                }
                break;
            case XMLStreamConstants.ATTRIBUTE:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    elementValueText = reader.getElementText();
                    System.out.println("ATTRIBUTE case, element name is " + elementName + ", element value is "
                            + elementValueText);
                    elementValue.add(elementValueText);
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                elementName = reader.getLocalName();
                if (elementName.equals(desiredElementName)) {
                    System.out.println("END_ELEMENT case, element name is " + elementName
                            + ", element value is " + elementValueText);
                }
                break;
            default:
                elementName = reader.getLocalName();
                if (elementName != null) {
                    if (elementName.equals(desiredElementName)) {
                        System.out.println("default case, element name is " + elementName);
                    }
                }
                break;
            }
            reader.next();
        }
    } catch (XMLStreamException e) {
        TradekingException.handleException(e);
    }
    return (elementValue.isEmpty() ? null : elementValue);
}

From source file:tpt.dbweb.cat.io.TaggedTextXMLReader.java

private Iterator<TaggedText> getIterator(InputStream is, String errorMessageInfo) {

    XMLStreamReader tmpxsr = null;
    try {/*from   w  w w  . j a v a  2  s  .  c  o  m*/
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
        xif.setProperty(XMLInputFactory.IS_VALIDATING, false);
        tmpxsr = xif.createXMLStreamReader(is);
    } catch (XMLStreamException | FactoryConfigurationError e) {
        e.printStackTrace();
        return null;
    }

    final XMLStreamReader xsr = tmpxsr;
    return new PeekIterator<TaggedText>() {

        @Override
        protected TaggedText internalNext() {
            ArrayList<TextSpan> openMarks = new ArrayList<>();
            StringBuilder pureTextSB = new StringBuilder();
            ArrayList<TextSpan> marks = new ArrayList<>();
            marks.add(new TextSpan(null, 0, 0));
            TaggedText tt = null;

            try {
                loop: while (xsr.hasNext()) {
                    xsr.next();
                    int event = xsr.getEventType();
                    switch (event) {
                    case XMLStreamConstants.START_ELEMENT:
                        if ("articles".equals(xsr.getLocalName())) {
                        } else if ("article".equals(xsr.getLocalName())) {
                            tt = new TaggedText();
                            for (int i = 0; i < xsr.getAttributeCount(); i++) {
                                if ("id".equals(xsr.getAttributeLocalName(i))) {
                                    tt.id = xsr.getAttributeValue(i);
                                }
                                tt.info().put(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
                            }

                        } else if ("mark".equals(xsr.getLocalName())) {
                            TextSpan tr = new TextSpan(null, pureTextSB.length(), pureTextSB.length());
                            for (int i = 0; i < xsr.getAttributeCount(); i++) {
                                tr.info().put(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
                            }

                            openMarks.add(tr);
                        } else if ("br".equals(xsr.getLocalName())) {
                            // TODO: how to propagate tags from the input to the output?
                        } else {
                            log.warn("ignore tag " + xsr.getLocalName());
                        }
                        break;
                    case XMLStreamConstants.END_ELEMENT:
                        if ("mark".equals(xsr.getLocalName())) {

                            // search corresponding <mark ...>
                            TextSpan tr = openMarks.remove(openMarks.size() - 1);
                            if (tr == null) {
                                log.warn("markend at " + xsr.getLocation().getCharacterOffset()
                                        + " has no corresponding mark tag");
                                break;
                            }

                            tr.end = pureTextSB.length();
                            marks.add(tr);

                        } else if ("article".equals(xsr.getLocalName())) {
                            tt.text = StringUtils.stripEnd(pureTextSB.toString().trim(), " \t\n");
                            pureTextSB = new StringBuilder();

                            tt.mentions = new ArrayList<>();
                            for (TextSpan mark : marks) {

                                String entity = mark.info().get("entity");
                                if (entity == null) {
                                    entity = mark.info().get("annotation");
                                }
                                if (entity != null) {
                                    EntityMention e = new EntityMention(tt.text, mark.start, mark.end, entity);
                                    String minMention = mark.info().get("min");
                                    String mention = e.getMention();
                                    if (minMention != null && !"".equals(minMention)) {
                                        Pattern p = Pattern.compile(Pattern.quote(minMention));
                                        Matcher m = p.matcher(mention);
                                        if (m.find()) {
                                            TextSpan min = new TextSpan(e.text, e.start + m.start(),
                                                    e.start + m.end());
                                            e.min = min;
                                            if (m.find()) {
                                                log.warn("found " + minMention + " two times in \"" + mention
                                                        + "\"");
                                            }
                                        } else {
                                            String prefix = Utility.findLongestPrefix(mention, minMention);
                                            log.warn("didn't find min mention '" + minMention + "' in text '"
                                                    + mention + "', longest prefix found: '" + prefix
                                                    + "' in article " + tt.id);
                                        }
                                    }

                                    mark.info().remove("min");
                                    mark.info().remove("entity");
                                    if (mark.info().size() > 0) {
                                        e.info().putAll(mark.info());
                                    }
                                    tt.mentions.add(e);
                                }
                            }
                            openMarks.clear();
                            marks.clear();
                            break loop;
                        }
                        break;
                    case XMLStreamConstants.CHARACTERS:
                        String toadd = xsr.getText();
                        if (pureTextSB.length() == 0) {
                            toadd = StringUtils.stripStart(toadd, " \t\n");
                        }
                        if (toadd.contains("thanks")) {
                            log.info("test");
                        }
                        pureTextSB.append(toadd);
                        break;
                    }

                }
            } catch (XMLStreamException e) {
                log.error("{}", errorMessageInfo);
                throw new RuntimeException(e);
            }
            if (tt != null && tt.mentions != null) {
                tt.mentions.sort(null);
            }
            return tt;
        }
    };
}

From source file:uap.workflow.engine.cfg.ProcessEngineConfigurationImpl.java

public void initExtensionConfig() {
    String configPath = "uap/workflow/engine/cfg/BizImpl.cfg.xml";
    Reader reader = null;//from w  ww .  j av a  2 s.c  o m
    try {
        URL url = Thread.currentThread().getContextClassLoader().getResource(configPath);
        String filePath = url.getPath();
        File f = new File(filePath);
        if (!f.exists())
            return;
        String xmlText = FileUtils.readFileToString(new File(filePath), "UTF-8");
        reader = new StringReader(xmlText);

        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance(ExtensionConfig.class);
            Unmarshaller us = jc.createUnmarshaller();
            // xmlinput
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            // XMLStreamReader
            XMLStreamReader streamReader = inputFactory.createXMLStreamReader(reader);
            // 
            extensionconfig = (ExtensionConfig) us.unmarshal(streamReader);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ParseConfigException(e.getMessage());
        }
    } catch (IOException e) {

    } finally {
        try {
            if (reader != null) {
                reader.close();
                reader = null;
            }
        } catch (IOException e) {
        }
    }
    return;

}