Example usage for javax.xml.stream XMLEventReader close

List of usage examples for javax.xml.stream XMLEventReader close

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventReader close.

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Frees any resources associated with this Reader.

Usage

From source file:org.eclipse.swordfish.core.configuration.xml.SaxParsingPrototype.java

/**
 * @param args// w  w  w .  ja  v a 2 s  .  co  m
 */
public static void main(String[] args) throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    LinkedList<String> currentElements = new LinkedList<String>();
    InputStream in = SaxParsingPrototype.class.getResource("ComplexPidXmlProperties.xml").openStream();
    XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
    Map<String, List<String>> props = new HashMap<String, List<String>>();
    // Read the XML document
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        if (event.isCharacters() && !event.asCharacters().isWhiteSpace()) {
            putElement(props, getQualifiedName(currentElements), event.asCharacters().getData());

        } else if (event.isStartElement()) {
            System.out.println(event.asStartElement().getName());
            currentElements.add(event.asStartElement().getName().getLocalPart());
            for (Iterator attrIt = event.asStartElement().getAttributes(); attrIt.hasNext();) {
                Attribute attribute = (Attribute) attrIt.next();
                putElement(props, getQualifiedName(currentElements) + "[@" + attribute.getName() + "]",
                        attribute.getValue());

            }
        } else if (event.isAttribute()) {
        } else if (event.isEndElement()) {
            String lastElem = event.asEndElement().getName().getLocalPart();
            if (!currentElements.getLast().equals(lastElem)) {
                throw new UnsupportedOperationException(lastElem + "," + currentElements.getLast());
            }
            currentElements.removeLast();
        }
    }

    eventReader.close();
}

From source file:gdv.xport.satz.xml.FeldXmlTest.java

private static FeldXml createFeldXmlFrom(final String resource) throws XMLStreamException {
    XMLEventReader parser = createXMLEventReader(resource);
    try {/*w  ww.  j a  v a 2 s. co m*/
        return new FeldXml(parser);
    } finally {
        parser.close();
    }
}

From source file:jenkins.plugins.livingdoc.XmlReportReader.java

@SuppressWarnings("PMD.EmptyCatchBlock")
private static void closeQuietly(XMLEventReader reader) {
    if (reader != null) {
        try {//from w  w w . j  ava  2s .co m
            reader.close();
        } catch (XMLStreamException e) {
            // ignore
        }
    }
}

From source file:Main.java

/**
 * Returns the name of the root element of an XML message.
 * //  ww w.jav  a2  s . co  m
 * @param xml     XML message
 * @return the name of the root element
 * @exception Exception if an error occurs
 */
public static String getRootElementName(byte[] xml) throws Exception {

    ByteArrayInputStream is = new ByteArrayInputStream(xml);
    XMLEventReader reader = inputFactory.createXMLEventReader(is);

    while (reader.hasNext()) {
        XMLEvent event = (XMLEvent) reader.next();

        if (event.isStartElement()) {
            StartElement startElement = event.asStartElement();
            return startElement.getName().getLocalPart();
        }
    }

    reader.close();
    return "";
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.tuepp.TueppReader.java

private static void closeQuietly(XMLEventReader aRes) {
    if (aRes != null) {
        try {/*from ww w  .ja  v a 2 s. c om*/
            aRes.close();
        } catch (XMLStreamException e) {
            // Ignore
        }
    }
}

From source file:Main.java

/**
 * Describe <code>getInternalXML</code> method here.
 *
 * @param is an <code>InputStream</code> value
 * @param tagName a <code>String</code> value
 * @param namespace a <code>String</code> value
 * @return a <code>byte[]</code> value
 * @exception Exception if an error occurs
 *//*ww  w . ja  v  a  2  s  . co m*/
public static byte[] getInternalXML(InputStream is, String tagName, String namespace) throws Exception {

    if (namespace == null)
        namespace = "";

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLEventWriter writer = outputFactory.createXMLEventWriter(bos);

    // Loop over XML input stream and process events
    boolean bStartWritingEvents = false;

    XMLEventReader reader = inputFactory.createXMLEventReader(is);

    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (checkNameAndNamespace(event, tagName, namespace) == true) {
            if (event.isStartElement() && !bStartWritingEvents) {
                writer.add(eventFactory.createStartDocument());
                bStartWritingEvents = true;
                continue;
            } else if (event.isEndElement()) {
                writer.add(eventFactory.createEndDocument());
                bStartWritingEvents = false;
                break;
            }
        }

        if (bStartWritingEvents) {
            writer.add(event);
        }
    }

    writer.close();
    reader.close();

    return bos.toByteArray();
}

From source file:eionet.webq.converter.JsonXMLBidirectionalConverter.java

/**
 * Closes quietly reader and writer./*from   ww  w.  j a va 2 s  . c o  m*/
 * @param reader xml event reader
 * @param writer xml event writer
 */
private void closeQuietly(XMLEventReader reader, XMLEventWriter writer) {
    try {
        reader.close();
    } catch (XMLStreamException e) {
        LOGGER.warn("Unable to close XMLEventReader", e);
    }
    try {
        writer.close();
    } catch (XMLStreamException e) {
        LOGGER.warn("Unable to close XMLEventWriter", e);
    }
}

From source file:com.ggvaidya.scinames.model.Project.java

public static Project loadFromFile(File loadFromFile) throws IOException {
    Project project = null;//www  .j  av a  2 s.  c om

    XMLInputFactory factory = XMLInputFactory.newFactory();
    factory.setXMLReporter(new XMLReporter() {
        @Override
        public void report(String message, String errorType, Object relatedInformation, Location location)
                throws XMLStreamException {
            LOGGER.warning(errorType + " while loading project from XML file '" + loadFromFile + "': " + message
                    + " (related info: " + relatedInformation.toString() + ", location: " + location);
        }
    });

    try {
        XMLEventReader reader = factory.createXMLEventReader(
                new XmlStreamReader(new GZIPInputStream(new FileInputStream(loadFromFile))));

        project = ProjectXMLReader.read(reader);
        project.setFile(loadFromFile);
        project.lastModifiedProperty().saved();

        reader.close();

    } catch (XMLStreamException ex) {
        throw new IOException("Could not read project from XML file '" + loadFromFile + "': " + ex, ex);
    }

    return project;

    /*
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            
    // Configure upcoming document builder.
    dbf.setIgnoringComments(true);
    dbf.setIgnoringElementContentWhitespace(true);
            
    Document docProject;
    try {
       DocumentBuilder db = dbf.newDocumentBuilder();
       docProject = db.parse(loadFromFile);
               
    } catch (SAXException ex) {
       throw new IOException("Could not load project XML file: " + ex);
               
    } catch (ParserConfigurationException ex) {
       throw new RuntimeException("Could not load XML parser configuration: " + ex);
            
    }
            
    // Load project.
    Project newProject;
    try {
       newProject = serializeFromDocument(docProject, loadFromFile);
    } catch(SAXException e) {
       throw new IOException("XML file loaded but project could not be read: " + e);
    } catch(IllegalStateException e) {
       throw new IOException("XML file contains errors in content: " + e);
    }
            
    return newProject;
    */
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

public static XmlElement getAtomElement(final InputStream is, final String name, final int minDepth,
        final int maxDepth) throws Exception {
    final XMLEventReader reader = getEventReader(is);
    final XmlElement res = getAtomElement(reader, null, name, null, 0, minDepth, maxDepth, false).getValue();
    reader.close();

    return res;/*w  w w.j  a v a2s.  c  o  m*/
}

From source file:fr.gael.dhus.server.http.webapp.search.controller.SearchController.java

void xmlToJson(InputStream xmlInput, OutputStream jsonOutput) throws XMLStreamException {
    JsonXMLConfig config = new JsonXMLConfigBuilder().autoArray(true).autoPrimitive(false).fieldPrefix("")
            .contentField("content").build();

    XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(xmlInput);
    XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(jsonOutput);

    writer.add(reader);/*from w ww  .j av  a 2  s  . c  o  m*/

    reader.close();
    writer.close();
}