Example usage for javax.xml.stream XMLStreamReader close

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

Introduction

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

Prototype

public void close() throws XMLStreamException;

Source Link

Document

Frees any resources associated with this Reader.

Usage

From source file:net.solarnetwork.util.JavaBeanXmlSerializer.java

private void endParse(XMLStreamReader reader) {
    try {/*from ww w  .  j a  v  a 2s. c o m*/
        reader.close();
    } catch (XMLStreamException e) {
        // ignore this
    }
}

From source file:au.org.ala.bhl.DocumentPaginator.java

private void paginateImpl(XMLStreamReader parser, PageHandler handler) throws Exception {

    if (parser == null) {
        return;//from  w w  w. j a  va  2s . co m
    }

    StringBuilder buffer = new StringBuilder();

    String currentPage = null;

    while (true) {
        int event = parser.next();
        if (event == XMLStreamConstants.END_DOCUMENT) {
            parser.close();
            break;
        }

        if (event == XMLStreamConstants.START_ELEMENT) {
            if (parser.getLocalName().equals("PARAM")) {
                String attrName = parser.getAttributeValue("", "name");
                if (attrName.equals("PAGE")) {

                    if (!StringUtils.isEmpty(currentPage)) {
                        if (handler != null) {
                            handler.handlePage(currentPage, buffer.toString());
                        }
                    }

                    buffer = new StringBuilder();
                    currentPage = parser.getAttributeValue("", "value");
                }
            }
        }

        if (event == XMLStreamConstants.CHARACTERS) {
            String value = StringUtils.trim(parser.getText());
            if (!StringUtils.isEmpty(value)) {
                buffer.append(value).append(" ");
            }
        }
    }

}

From source file:com.microsoft.tfs.core.ws.runtime.types.StaxAnyContentType.java

@Override
public void writeAsElement(final XMLStreamWriter writer, final String name) throws XMLStreamException {
    final Iterator i = getElementIterator();

    /*/*ww w . jav a  2  s. c  o m*/
     * Use the regular public iterator for reader access.
     */
    for (; i.hasNext();) {
        final XMLStreamReader reader = (XMLStreamReader) i.next();

        /*
         * Advance one event, beyond the start document, to get the first
         * element.
         */
        reader.next();

        StaxUtils.copyCurrentElement(reader, writer);

        reader.close();
    }

    if (i instanceof Closable) {
        ((Closable) i).close();
    }
}

From source file:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Parses the operation response as an entity. Reads entity data from the specified
 * <code>XMLStreamReader</code> using the specified class type and optionally projects the entity result with the
 * specified resolver into a {@link TableResult} object.
 * //from   w ww  .  jav a  2 s.c  om
 * @param xmlr
 *            The <code>XMLStreamReader</code> to read the data to parse from.
 * @param httpStatusCode
 *            The HTTP status code returned with the operation response.
 * @param clazzType
 *            The class type <code>T</code> implementing {@link TableEntity} for the entity returned. Set to
 *            <code>null</code> to ignore the returned entity and copy only response properties into the
 *            {@link TableResult} object.
 * @param resolver
 *            An {@link EntityResolver} instance to project the entity into an instance of type <code>R</code>. Set
 *            to <code>null</code> to return the entitys as instance of the class type <code>T</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         A {@link TableResult} object with the parsed operation response.
 * 
 * @throws XMLStreamException
 *             if an error occurs while accessing the stream.
 * @throws ParseException
 *             if an error occurs while parsing the stream.
 * @throws InstantiationException
 *             if an error occurs while constructing the result.
 * @throws IllegalAccessException
 *             if an error occurs in reflection while parsing the result.
 * @throws StorageException
 *             if a storage service error occurs.
 */
private static <T extends TableEntity, R> TableResult parseSingleOpAtomResponse(final InputStream inStream,
        final int httpStatusCode, final Class<T> clazzType, final EntityResolver<R> resolver,
        final OperationContext opContext) throws XMLStreamException, ParseException, InstantiationException,
        IllegalAccessException, StorageException {
    XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(inStream);

    try {
        xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null);
        xmlr.next();

        final TableResult res = parseAtomEntity(xmlr, clazzType, resolver, opContext);
        res.setHttpStatusCode(httpStatusCode);
        return res;
    } finally {
        xmlr.close();
    }
}

From source file:at.lame.hellonzb.parser.NzbParser.java

/**
 * This is the constructor of the class.
 * It parses the given XML file./*from w  ww  . ja v a 2s. c  o  m*/
 *
 * @param mainApp The main application object
 * @param file The file name of the nzb file to parse
 * @throws XMLStreamException 
 * @throws IOException 
 */
public NzbParser(HelloNzbCradle mainApp, String file) throws XMLStreamException, IOException, ParseException {
    this.mainApp = mainApp;

    DownloadFile currentFile = null;
    DownloadFileSegment currentSegment = null;
    boolean groupFlag = false;
    boolean segmentFlag = false;

    this.name = file.trim();
    this.name = file.substring(0, file.length() - 4);
    this.downloadFiles = new Vector<DownloadFile>();

    this.origTotalSize = 0;
    this.downloadedBytes = 0;

    // create XML parser
    String string = reformatInputStream(file);
    InputStream in = new ByteArrayInputStream(string.getBytes());
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(in);

    // parse nzb file with a Java XML parser
    while (parser.hasNext()) {
        switch (parser.getEventType()) {
        // parser has reached the end of the xml file
        case XMLStreamConstants.END_DOCUMENT:
            parser.close();
            break;

        // parser has found a new element
        case XMLStreamConstants.START_ELEMENT:
            String elemName = parser.getLocalName().toLowerCase();
            if (elemName.equals("file")) {
                currentFile = newDownloadFile(parser);
                boolean found = false;
                for (DownloadFile dlf : downloadFiles)
                    if (dlf.getFilename().equals(currentFile.getFilename())) {
                        found = true;
                        break;
                    }

                if (!found)
                    downloadFiles.add(currentFile);
            } else if (elemName.equals("group"))
                groupFlag = true;
            else if (elemName.equals("segment")) {
                currentSegment = newDownloadFileSegment(parser, currentFile);
                currentFile.addSegment(currentSegment);
                segmentFlag = true;
            }
            break;

        // end of element
        case XMLStreamConstants.END_ELEMENT:
            groupFlag = false;
            segmentFlag = false;
            break;

        // get the elements value(s)
        case XMLStreamConstants.CHARACTERS:
            if (!parser.isWhiteSpace()) {
                if (groupFlag && (currentFile != null))
                    currentFile.addGroup(parser.getText());
                else if (segmentFlag && (currentSegment != null))
                    currentSegment.setArticleId(parser.getText());
            }
            break;

        // any other parser event?
        default:
            break;
        }

        parser.next();
    }

    checkFileSegments();
    this.origTotalSize = getCurrTotalSize();
}

From source file:com.hp.alm.ali.rest.client.AliRestClient.java

private List<String> getAttributeValues(InputStream xml, String elemName, String attrName) {
    try {//from  ww  w .j  a  v a 2s.com
        XMLInputFactory factory = XmlUtils.createBasicInputFactory();
        XMLStreamReader parser;
        parser = factory.createXMLStreamReader(xml);
        List<String> result = new LinkedList<String>();
        while (true) {
            int event = parser.next();
            if (event == XMLStreamConstants.END_DOCUMENT) {
                parser.close();
                break;
            }
            if (event == XMLStreamConstants.START_ELEMENT && elemName.equals(parser.getLocalName())) {

                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String localName = parser.getAttributeLocalName(i);
                    if (attrName.equals(localName)) {
                        result.add(parser.getAttributeValue(i));
                        break;
                    }
                }
            }
        }
        return result;
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            xml.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:com.microsoft.tfs.core.clients.workitem.internal.metadata.Metadata.java

@Override
public long updateMetadata(final AnyContentType metadata, final String newDbStamp) {
    final long startTime = System.currentTimeMillis();
    final boolean[] fullUpdateHolder = new boolean[1];
    fullUpdateHolder[0] = false;/* w w  w  .j av  a 2 s .  c o  m*/
    final Set<String> tableNames = new HashSet<String>();

    connectionPool.executeWithPooledConnection(new DBTask() {
        @Override
        public void performTask(final DBConnection connection) {
            if (newDbStamp != null) {
                /*
                 * A DBStamp was returned along with metadata updates. We
                 * need to check it and see which of three states we're in:
                 *
                 * 1) If the current dbstamp is null, this is the first
                 * metadata update. Set the dbstamp to the passed value and
                 * proceed with the update.
                 *
                 * 2) If the current dbstamp is not null and doesn't match
                 * the passed dbstamp, then our cache has been invalidated.
                 * Ignore the metadata update and do a complete refresh.
                 *
                 * 3) If the current dbstamp is not null and matches the
                 * passed dbstamp, proceed with the update.
                 */

                final String oldDbStamp = getDBStamp(connection);

                if (oldDbStamp == null || oldDbStamp.length() == 0) {
                    setDBStamp(connection, newDbStamp);
                } else if (!oldDbStamp.equals(newDbStamp)) {
                    log.info(MessageFormat.format(
                            "current dbstamp [{0}] does not match [{1}] - invalidating cache", //$NON-NLS-1$
                            oldDbStamp, newDbStamp));
                    dropMetadataTables(connection);
                    createMaxCountTable(connection);
                    setDBStamp(connection, ""); //$NON-NLS-1$
                    fullUpdateHolder[0] = true;
                    return;
                }
            }

            /*
             * Normal update.
             */

            final Iterator i = metadata.getElementIterator();
            final RowSetParser parser = new RowSetParser();

            while (i.hasNext()) {
                final DBRowSetHandler handler = new DBRowSetHandler(connection, verbose);

                if (metadata instanceof DOMAnyContentType) {
                    parser.parse((Element) i.next(), handler);
                } else if (metadata instanceof StaxAnyContentType) {
                    final XMLStreamReader reader = (XMLStreamReader) i.next();
                    try {
                        parser.parse(reader, handler);
                    } finally {
                        try {
                            reader.close();
                        } catch (final XMLStreamException e) {
                            throw new TECoreException(e);
                        }
                    }
                } else {
                    throw new WorkItemException(MessageFormat.format(
                            "Can''t update metadata from unknown AnyContentType implementation {0}", //$NON-NLS-1$
                            metadata.getClass().getName()));
                }

                if (alwaysSendUpdateNotifications || handler.getInsertCount() > 0
                        || handler.getDeleteCount() > 0) {
                    tableNames.add(handler.getTableName());
                }
            }

            if (i instanceof Closable) {
                ((Closable) i).close();
            }
        }
    });

    if (fullUpdateHolder[0]) {
        update();
    } else {
        if (tableNames.size() > 0) {
            /*
             * reset internal caches
             */
            synchronized (this) {
                if (tableNames.contains(MetadataTableNames.CONSTANT_SETS)) {
                    distinctConstantSetIds = null;
                }
            }

            final Set<String> unmodifiableTableNameSet = Collections.unmodifiableSet(tableNames);

            /*
             * Fire any listeners for metadata updates
             */
            synchronized (metadataUpdateListeners) {
                for (final Iterator<IMetadataChangeListener> it = metadataUpdateListeners.iterator(); it
                        .hasNext();) {
                    it.next().metadataChanged(unmodifiableTableNameSet);
                }
            }
        }
    }

    return System.currentTimeMillis() - startTime;
}

From source file:de.tuebingen.uni.sfs.germanet.api.IliLoader.java

/**
 * Loads <code>IliRecords</code> from the specified file into this
 * <code>IliLoader</code>'s <code>GermaNet</code> object.
 * @param iliFile the file containing <code>IliRecords</code> data
 * @throws java.io.FileNotFoundException
 * @throws javax.xml.stream.XMLStreamException
 *///from   w w w  .j  a va2  s.  c  o m
protected void loadILI(File iliFile) throws FileNotFoundException, XMLStreamException {
    InputStream in = new FileInputStream(iliFile);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(in);
    int event;
    String nodeName;
    logger.debug("Loading " + iliFile.getName() + "...");

    //Parse entire file, looking for ili record start elements
    while (parser.hasNext()) {
        event = parser.next();
        switch (event) {
        case XMLStreamConstants.START_DOCUMENT:
            namespace = parser.getNamespaceURI();
            break;
        case XMLStreamConstants.START_ELEMENT:
            nodeName = parser.getLocalName();
            if (nodeName.equals(GermaNet.XML_ILI_RECORD)) {
                IliRecord ili = processIliRecord(parser);
                germaNet.addIliRecord(ili);
            }
            break;
        }
    }
    parser.close();
    logger.debug("Done.");
}

From source file:de.tuebingen.uni.sfs.germanet.api.IliLoader.java

/**
 * Loads <code>IliRecords</code> from the specified stream into this
 * <code>IliLoader</code>'s <code>GermaNet</code> object.
 * @param inputStream the stream containing <code>IliRecords</code> data
 * @throws javax.xml.stream.XMLStreamException
 *//*w ww  . j a  v  a2s  . com*/
protected void loadILI(InputStream inputStream) throws XMLStreamException {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(inputStream);
    int event;
    String nodeName;
    logger.debug("Loading input stream interLingualIndex_DE-EN.xml...");

    //Parse entire file, looking for ili record start elements
    while (parser.hasNext()) {
        event = parser.next();
        switch (event) {
        case XMLStreamConstants.START_DOCUMENT:
            namespace = parser.getNamespaceURI();
            break;
        case XMLStreamConstants.START_ELEMENT:
            nodeName = parser.getLocalName();
            if (nodeName.equals(GermaNet.XML_ILI_RECORD)) {
                IliRecord ili = processIliRecord(parser);
                germaNet.addIliRecord(ili);
            }
            break;
        }
    }
    parser.close();
    logger.debug("Done.");
}

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

/**
 * Extracts {@code @xsi:noNamespaceSchemaLocation} or {@code @xsi:schemaLocation} attribute value from xml root element.
 *
 * @param source source to be searched.// w  w w  .  j a  v  a  2s .  co  m
 * @return {@code @xsi:noNamespaceSchemaLocation} or {@code @xsi:schemaLocation} attribute value, default {@code null}
 */
public String extractXmlSchema(byte[] source) {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    ByteArrayInputStream bais = new ByteArrayInputStream(source);
    XMLStreamReader xmlStreamReader = null;
    try {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(bais);
        while (xmlStreamReader.hasNext()) {
            if (xmlStreamReader.next() == START_ELEMENT) {
                return StringUtils.defaultString(
                        parseNoNamespaceSchemaLocation(xmlStreamReader.getAttributeValue(XSI_NAMESPACE_URI,
                                "noNamespaceSchemaLocation")),
                        parseSchemaLocation(
                                xmlStreamReader.getAttributeValue(XSI_NAMESPACE_URI, "schemaLocation")));
            }
        }
    } catch (Exception e) {
        LOGGER.warn("exception thrown during extracting xml schema", e);
    } finally {
        IOUtils.closeQuietly(bais);
        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (XMLStreamException e) {
                LOGGER.warn("unable to close xml stream", e);
            }
        }
    }
    return null;
}