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:jodtemplate.pptx.io.xml.SlideXmlRelsReader.java

@Override
public Slide read(final String path, final Resources resources, final XMLInputFactory xmlInputFactory,
        final Slide slide) throws XMLStreamException, IOException {
    final Resource slideXmlRelsRes = resources.getResource(Utils.removePrefixSeparator(path));
    try (final InputStream is = slideXmlRelsRes.getInputStream()) {
        final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);
        int event = xmlStreamReader.next();
        while (event != XMLStreamConstants.END_DOCUMENT) {
            if (xmlStreamReader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                final String elementNS = xmlStreamReader.getName().getNamespaceURI();
                final String elementName = xmlStreamReader.getName().getLocalPart();
                if (OOXMLDocument.RELATIONSHIP_ELEMENT.equals(elementName)
                        && OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE.equals(elementNS)) {
                    final Relationship relationship = createRelationshipElement(xmlStreamReader);
                    slide.addOtherRelationship(relationship);
                }/*w  w  w .j  a  v  a2 s .  c  om*/
            }
            event = xmlStreamReader.next();
        }
    }

    return slide;
}

From source file:jodtemplate.io.xml.ContentTypesReader.java

@Override
public ContentTypes read(final String path, final Resources resources, final XMLInputFactory xmlInputFactory,
        final ContentTypes contentTypes) throws XMLStreamException, IOException {
    final Resource contentTypesRes = resources.getResource(Utils.removePrefixSeparator(path));
    try (final InputStream is = contentTypesRes.getInputStream()) {
        final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);
        int event = xmlStreamReader.next();
        while (event != XMLStreamConstants.END_DOCUMENT) {
            if (xmlStreamReader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                final String elementNS = xmlStreamReader.getName().getNamespaceURI();
                final String elementName = xmlStreamReader.getName().getLocalPart();
                if (OOXMLDocument.DEFAULT_ELEMENT.equals(elementName)
                        && OOXMLDocument.CONTENT_TYPES_NAMESPACE.equals(elementNS)) {
                    contentTypes.addDefaultElement(createDefaultElement(xmlStreamReader));
                }/* ww w. j a  va 2  s. c o  m*/
                if (OOXMLDocument.OVERRIDE_ELEMENT.equals(elementName)
                        && OOXMLDocument.CONTENT_TYPES_NAMESPACE.equals(elementNS)) {
                    contentTypes.addOverrideElement(createOverrideElement(xmlStreamReader));
                }
            }
            event = xmlStreamReader.next();
        }
    }

    return contentTypes;
}

From source file:org.openvpms.tools.data.loader.DataLoaderTestCase.java

/**
 * Loads a file.// w  ww. j a  va  2s . c  o  m
 *
 * @param loader the loader
 * @param file   the file to load
 * @throws Exception for any error
 */
private void load(DataLoader loader, String file) throws Exception {
    InputStream stream = getClass().getResourceAsStream(file);
    assertNotNull(stream);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = factory.createXMLStreamReader(stream);
    loader.load(reader, file);
}

From source file:jodtemplate.pptx.io.xml.PresentationXmlRelsReader.java

@Override
public Presentation read(final String path, final Resources resources, final XMLInputFactory xmlInputFactory,
        final Presentation presentation) throws XMLStreamException, IOException {
    final Resource presentationXmlRelsRes = resources.getResource(Utils.removePrefixSeparator(path));
    try (final InputStream is = presentationXmlRelsRes.getInputStream()) {
        final XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);
        int event = xmlStreamReader.next();
        while (event != XMLStreamConstants.END_DOCUMENT) {
            if (xmlStreamReader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                final String elementNS = xmlStreamReader.getName().getNamespaceURI();
                final String elementName = xmlStreamReader.getName().getLocalPart();
                if (OOXMLDocument.RELATIONSHIP_ELEMENT.equals(elementName)
                        && OOXMLDocument.RELATIONSHIPS_RELS_NAMESPACE.equals(elementNS)) {
                    final Relationship relationship = createRelationshipElement(xmlStreamReader);
                    if (Relationship.SLIDE_TYPE.equals(relationship.getType())) {
                        final Slide slide = new Slide();
                        slide.setRelationship(relationship);
                        slide.setPresentation(presentation);
                        presentation.addSlide(slide);
                    } else {
                        presentation.addOtherRelationship(relationship);
                    }/*from  w w  w . j av  a  2 s. co  m*/
                }
            }
            event = xmlStreamReader.next();
        }
    }

    return presentation;
}

From source file:com.pocketsoap.salesforce.soap.ChatterClient.java

private <T> T makeSoapRequest(String serverUrl, RequestEntity req, ResponseParser<T> respParser)
        throws XMLStreamException, IOException {
    PostMethod post = new PostMethod(serverUrl);
    post.addRequestHeader("SOAPAction", "\"\"");
    post.setRequestEntity(req);//from   w w w.  jav  a 2 s . co  m

    HttpClient http = new HttpClient();
    int sc = http.executeMethod(post);
    if (sc != 200 && sc != 500)
        throw new IOException("request to " + serverUrl + " returned unexpected HTTP status code of " + sc
                + ", check configuration.");

    XMLInputFactory f = XMLInputFactory.newInstance();
    f.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);

    XMLStreamReader rdr = f.createXMLStreamReader(post.getResponseBodyAsStream());
    rdr.require(XMLStreamReader.START_DOCUMENT, null, null);
    rdr.nextTag();
    rdr.require(XMLStreamReader.START_ELEMENT, SOAP_NS, "Envelope");
    rdr.nextTag();
    // TODO, should handle a Header appearing in the response.
    rdr.require(XMLStreamReader.START_ELEMENT, SOAP_NS, "Body");
    rdr.nextTag();
    if (rdr.getLocalName().equals("Fault")) {
        throw handleSoapFault(rdr);
    }
    try {
        T response = respParser.parse(rdr);
        while (rdr.hasNext())
            rdr.next();
        return response;
    } finally {
        try {
            rdr.close();
        } finally {
            post.releaseConnection();
        }
    }
}

From source file:com.hp.mqm.clt.XmlProcessorTest.java

private void assertXml(List<TestResult> expectedTestResults, Set<XmlElement> expectedElements, File xmlFile)
        throws FileNotFoundException, XMLStreamException {
    FileInputStream fis = new FileInputStream(xmlFile);
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    xmlInputFactory.setProperty("javax.xml.stream.isCoalescing", true);
    XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(fis);

    boolean isFirstEvent = true;
    while (xmlStreamReader.hasNext()) {
        if (!isFirstEvent) {
            xmlStreamReader.next();/*from  w ww  .  ja  v a  2s. com*/
        } else {
            isFirstEvent = false;
        }

        if (xmlStreamReader.getEventType() == XMLStreamReader.START_ELEMENT) {
            String localName = xmlStreamReader.getLocalName();
            if ("taxonomy".equals(localName)) {
                assertElement(localName, false, xmlStreamReader, expectedElements);
            } else if ("test_field".equals(localName)) {
                assertElement(localName, false, xmlStreamReader, expectedElements);
            } else if ("product_area_ref".equals(localName)) {
                assertElement(localName, true, xmlStreamReader, expectedElements);
            } else if ("backlog_item_ref".equals(localName)) {
                assertElement(localName, true, xmlStreamReader, expectedElements);
            } else if ("release_ref".equals(localName)) {
                assertElement(localName, true, xmlStreamReader, expectedElements);
            } else if ("test_run".equals(localName)) {
                assertXmlTest(xmlStreamReader, expectedTestResults);
            }
        }
    }
    xmlStreamReader.close();
    IOUtils.closeQuietly(fis);
    Assert.assertTrue(expectedElements.isEmpty());
    Assert.assertTrue(expectedTestResults.isEmpty());
}

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

public ParserResult importEntries(String text) {
    // URLencode the string for transmission
    String urlencodedCitation = null;
    try {/* w w w.ja  v  a  2 s  .c  om*/
        urlencodedCitation = URLEncoder.encode(text, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Unsupported encoding", e);
    }

    // Send the request
    URL url;
    URLConnection conn;
    try {
        url = new URL("http://freecite.library.brown.edu/citations/create");
        conn = url.openConnection();
    } catch (MalformedURLException e) {
        LOGGER.warn("Bad URL", e);
        return new ParserResult();
    } catch (IOException e) {
        LOGGER.warn("Could not download", e);
        return new ParserResult();
    }
    try {
        conn.setRequestProperty("accept", "text/xml");
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        String data = "citation=" + urlencodedCitation;
        // write parameters
        writer.write(data);
        writer.flush();
    } catch (IllegalStateException e) {
        LOGGER.warn("Already connected.", e);
    } catch (IOException e) {
        LOGGER.warn("Unable to connect to FreeCite online service.", e);
        return ParserResult
                .fromErrorMessage(Localization.lang("Unable to connect to FreeCite online service."));
    }
    // output is in conn.getInputStream();
    // new InputStreamReader(conn.getInputStream())
    List<BibEntry> res = new ArrayList<>();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        XMLStreamReader parser = factory.createXMLStreamReader(conn.getInputStream());
        while (parser.hasNext()) {
            if ((parser.getEventType() == XMLStreamConstants.START_ELEMENT)
                    && "citation".equals(parser.getLocalName())) {
                parser.nextTag();

                StringBuilder noteSB = new StringBuilder();

                BibEntry e = new BibEntry();
                // fallback type
                EntryType type = BibtexEntryTypes.INPROCEEDINGS;

                while (!((parser.getEventType() == XMLStreamConstants.END_ELEMENT)
                        && "citation".equals(parser.getLocalName()))) {
                    if (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                        String ln = parser.getLocalName();
                        if ("authors".equals(ln)) {
                            StringBuilder sb = new StringBuilder();
                            parser.nextTag();

                            while (parser.getEventType() == XMLStreamConstants.START_ELEMENT) {
                                // author is directly nested below authors
                                assert "author".equals(parser.getLocalName());

                                String author = parser.getElementText();
                                if (sb.length() == 0) {
                                    // first author
                                    sb.append(author);
                                } else {
                                    sb.append(" and ");
                                    sb.append(author);
                                }
                                assert parser.getEventType() == XMLStreamConstants.END_ELEMENT;
                                assert "author".equals(parser.getLocalName());
                                parser.nextTag();
                                // current tag is either begin:author or
                                // end:authors
                            }
                            e.setField(FieldName.AUTHOR, sb.toString());
                        } else if (FieldName.JOURNAL.equals(ln)) {
                            // we guess that the entry is a journal
                            // the alternative way is to parse
                            // ctx:context-objects / ctx:context-object / ctx:referent / ctx:metadata-by-val / ctx:metadata / journal / rft:genre
                            // the drawback is that ctx:context-objects is NOT nested in citation, but a separate element
                            // we would have to change the whole parser to parse that format.
                            type = BibtexEntryTypes.ARTICLE;
                            e.setField(ln, parser.getElementText());
                        } else if ("tech".equals(ln)) {
                            type = BibtexEntryTypes.TECHREPORT;
                            // the content of the "tech" field seems to contain the number of the technical report
                            e.setField(FieldName.NUMBER, parser.getElementText());
                        } else if (FieldName.DOI.equals(ln) || "institution".equals(ln) || "location".equals(ln)
                                || FieldName.NUMBER.equals(ln) || "note".equals(ln)
                                || FieldName.TITLE.equals(ln) || FieldName.PAGES.equals(ln)
                                || FieldName.PUBLISHER.equals(ln) || FieldName.VOLUME.equals(ln)
                                || FieldName.YEAR.equals(ln)) {
                            e.setField(ln, parser.getElementText());
                        } else if ("booktitle".equals(ln)) {
                            String booktitle = parser.getElementText();
                            if (booktitle.startsWith("In ")) {
                                // special treatment for parsing of
                                // "In proceedings of..." references
                                booktitle = booktitle.substring(3);
                            }
                            e.setField("booktitle", booktitle);
                        } else if ("raw_string".equals(ln)) {
                            // raw input string is ignored
                        } else {
                            // all other tags are stored as note
                            noteSB.append(ln);
                            noteSB.append(':');
                            noteSB.append(parser.getElementText());
                            noteSB.append(Globals.NEWLINE);
                        }
                    }
                    parser.next();
                }

                if (noteSB.length() > 0) {
                    String note;
                    if (e.hasField("note")) {
                        // "note" could have been set during the parsing as FreeCite also returns "note"
                        note = e.getFieldOptional("note").get().concat(Globals.NEWLINE)
                                .concat(noteSB.toString());
                    } else {
                        note = noteSB.toString();
                    }
                    e.setField("note", note);
                }

                // type has been derived from "genre"
                // has to be done before label generation as label generation is dependent on entry type
                e.setType(type);

                // autogenerate label (BibTeX key)
                LabelPatternUtil.makeLabel(
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getBibDatabaseContext().getMetaData(),
                        JabRefGUI.getMainFrame().getCurrentBasePanel().getDatabase(), e, Globals.prefs);

                res.add(e);
            }
            parser.next();
        }
        parser.close();
    } catch (IOException | XMLStreamException ex) {
        LOGGER.warn("Could not parse", ex);
        return new ParserResult();
    }

    return new ParserResult(res);
}

From source file:org.activiti.app.rest.editor.AbstractModelsResource.java

public ModelRepresentation importProcessModel(HttpServletRequest request, MultipartFile file) {

    String fileName = file.getOriginalFilename();
    if (fileName != null && (fileName.endsWith(".bpmn") || fileName.endsWith(".bpmn20.xml"))) {
        try {//from   w  ww  .jav a 2s  .  com
            XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
            InputStreamReader xmlIn = new InputStreamReader(file.getInputStream(), "UTF-8");
            XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn);
            BpmnModel bpmnModel = bpmnXmlConverter.convertToBpmnModel(xtr);
            if (CollectionUtils.isEmpty(bpmnModel.getProcesses())) {
                throw new BadRequestException("No process found in definition " + fileName);
            }

            if (bpmnModel.getLocationMap().size() == 0) {
                BpmnAutoLayout bpmnLayout = new BpmnAutoLayout(bpmnModel);
                bpmnLayout.execute();
            }

            ObjectNode modelNode = bpmnJsonConverter.convertToJson(bpmnModel);

            org.activiti.bpmn.model.Process process = bpmnModel.getMainProcess();
            String name = process.getId();
            if (StringUtils.isNotEmpty(process.getName())) {
                name = process.getName();
            }
            String description = process.getDocumentation();

            ModelRepresentation model = new ModelRepresentation();
            model.setKey(process.getId());
            model.setName(name);
            model.setDescription(description);
            model.setModelType(AbstractModel.MODEL_TYPE_BPMN);
            Model newModel = modelService.createModel(model, modelNode.toString(),
                    SecurityUtils.getCurrentUserObject());
            return new ModelRepresentation(newModel);

        } catch (BadRequestException e) {
            throw e;

        } catch (Exception e) {
            logger.error("Import failed for " + fileName, e);
            throw new BadRequestException(
                    "Import failed for " + fileName + ", error message " + e.getMessage());
        }
    } else {
        throw new BadRequestException(
                "Invalid file name, only .bpmn and .bpmn20.xml files are supported not " + fileName);
    }
}

From source file:com.norconex.collector.http.sitemap.impl.StandardSitemapResolver.java

private void parseLocation(InputStream is, HttpClient httpClient, SitemapURLAdder sitemapURLAdder,
        Set<String> resolvedLocations, String location) throws XMLStreamException {

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
    XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is);
    ParseState parseState = new ParseState();

    String locationDir = StringUtils.substringBeforeLast(location, "/");
    int event = xmlReader.getEventType();
    while (true) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            String tag = xmlReader.getLocalName();
            parseStartElement(parseState, tag);
            break;
        case XMLStreamConstants.CHARACTERS:
            String value = xmlReader.getText();
            if (parseState.sitemapIndex && parseState.loc) {
                resolveLocation(value, httpClient, sitemapURLAdder, resolvedLocations);
                parseState.loc = false;//from   www .  j  a  v a  2s  . c  om
            } else if (parseState.baseURL != null) {
                parseCharacters(parseState, value);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            tag = xmlReader.getLocalName();
            parseEndElement(sitemapURLAdder, parseState, locationDir, tag);
            break;
        }
        if (!xmlReader.hasNext()) {
            break;
        }
        event = xmlReader.next();
    }
}