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: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 .ja  v a2s.c om*/

    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:gate.corpora.FastInfosetDocumentFormat.java

/**
 * Unpacks markup in the GATE-specific standoff XML markup format.
 * /* w  w w.  ja va2s .  co  m*/
 * @param doc
 *          the document to process
 * @param statusListener
 *          optional status listener to receive status messages
 * @throws DocumentFormatException
 *           if a fatal error occurs during parsing
 */
private void unpackGateFormatMarkup(Document doc, StatusListener statusListener)
        throws DocumentFormatException {
    boolean docHasContentButNoValidURL = hasContentButNoValidUrl(doc);

    try {
        Reader inputReader = null;
        InputStream inputStream = null;
        XMLStreamReader xsr = null;
        String encoding = ((TextualDocument) doc).getEncoding();
        if (docHasContentButNoValidURL) {
            xsr = new StAXDocumentParser(IOUtils.toInputStream(doc.getContent().toString(), encoding),
                    getStAXManager());
        } else {
            inputStream = doc.getSourceUrl().openStream();
            xsr = new StAXDocumentParser(inputStream, getStAXManager());
        }

        // find the opening GateDocument tag
        xsr.nextTag();

        // parse the document
        try {
            DocumentStaxUtils.readGateXmlDocument(xsr, doc, statusListener);
        } finally {
            xsr.close();
            if (inputStream != null) {
                inputStream.close();
            }
            if (inputReader != null) {
                inputReader.close();
            }
        }
    } catch (XMLStreamException e) {
        doc.getFeatures().put("parsingError", Boolean.TRUE);

        Boolean bThrow = (Boolean) doc.getFeatures().get(GateConstants.THROWEX_FORMAT_PROPERTY_NAME);

        if (bThrow != null && bThrow.booleanValue()) {
            // the next line is commented to avoid Document creation fail on
            // error
            throw new DocumentFormatException(e);
        } else {
            Out.println("Warning: Document remains unparsed. \n" + "\n  Stack Dump: ");
            e.printStackTrace(Out.getPrintWriter());
        } // if
    } catch (IOException ioe) {
        throw new DocumentFormatException("I/O exception for " + doc.getSourceUrl().toString(), ioe);
    }
}

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

/**
 * Loads <code>WiktionaryParaphrases</code> from the specified file into this
 * <code>WiktionaryLoader</code>'s <code>GermaNet</code> object.
 * @param wiktionaryFile the file containing <code>WiktionaryParaphrases</code> data
 * @throws java.io.FileNotFoundException
 * @throws javax.xml.stream.XMLStreamException
 *//*  ww w. j ava  2 s. c  om*/
protected void loadWiktionary(File wiktionaryFile) throws FileNotFoundException, XMLStreamException {
    wikiDir = wiktionaryFile;
    FilenameFilter filter = new WikiFilter(); //get only wiktionary files
    File[] wikiFiles = wikiDir.listFiles(filter);

    if (wikiFiles == null || wikiFiles.length == 0) {
        throw new FileNotFoundException(
                "Unable to load Wiktionary Paraphrases from \"" + this.wikiDir.getPath() + "\"");
    }

    for (File wikiFile : wikiFiles) {
        logger.debug("Loading " + wikiFile.getName() + "...");
        InputStream in = new FileInputStream(wikiFile);
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader parser = factory.createXMLStreamReader(in);
        int event;
        String nodeName;

        //Parse entire file, looking for Wiktionary paraphrase 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_WIKTIONARY_PARAPHRASE)) {
                    WiktionaryParaphrase wiki = processWiktionaryParaphrase(parser);
                    germaNet.addWiktionaryParaphrase(wiki);
                }
                break;
            }
        }
        parser.close();
    }

    logger.debug("Done.");

}

From source file:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterImpl.java

private void defineClasses(final Map<String, CtClass> ctClasses, final InputStream stream)
        throws XMLStreamException, ModelXmlCompilingException, NotFoundException {
    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);

    while (reader.hasNext() && reader.next() > 0) {
        if (isTagStarted(reader, TAG_MODEL)) {
            String pluginIdentifier = getPluginIdentifier(reader);
            String modelName = getStringAttribute(reader, L_NAME);
            String className = ClassNameUtils.getFullyQualifiedClassName(pluginIdentifier, modelName);

            if (ctClasses.containsKey(className)) {
                parse(reader, ctClasses.get(className), pluginIdentifier);
            }/*from   www  .j  a va2 s  .  c  om*/
        }
    }

    reader.close();
}

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

/**
 * Loads <code>WiktionaryParaphrases</code> from the given streams into this
 * <code>WiktionaryLoader</code>'s <code>GermaNet</code> object.
 * @param inputStreams the list of streams containing <code>WiktionaryParaphrases</code> data
 * @param xmlNames the names of the streams
 * @throws javax.xml.stream.XMLStreamException
 *//*w w  w.j a  v a2s .  c o m*/
protected void loadWiktionary(List<InputStream> inputStreams, List<String> xmlNames) throws XMLStreamException {

    for (int i = 0; i < inputStreams.size(); i++) {
        if (xmlNames.get(i).startsWith("wiktionary")) {
            logger.debug("Loading input stream " + xmlNames.get(i) + "...");
            XMLInputFactory factory = XMLInputFactory.newInstance();
            XMLStreamReader parser = factory.createXMLStreamReader(inputStreams.get(i));
            int event;
            String nodeName;

            //Parse entire file, looking for Wiktionary paraphrase 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_WIKTIONARY_PARAPHRASE)) {
                        WiktionaryParaphrase wiki = processWiktionaryParaphrase(parser);
                        germaNet.addWiktionaryParaphrase(wiki);
                    }
                    break;
                }
            }
            parser.close();
        }
    }

    logger.debug("Done.");

}

From source file:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterImpl.java

private Map<String, CtClass> createClasses(final Map<String, Class<?>> existingClasses,
        final InputStream stream) throws XMLStreamException {
    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
    Map<String, CtClass> ctClasses = new HashMap<String, CtClass>();

    while (reader.hasNext() && reader.next() > 0) {
        if (isTagStarted(reader, TAG_MODEL)) {
            String pluginIdentifier = getPluginIdentifier(reader);
            String modelName = getStringAttribute(reader, L_NAME);
            String className = ClassNameUtils.getFullyQualifiedClassName(pluginIdentifier, modelName);

            if (existingClasses.containsKey(className)) {
                LOG.info("Class " + className + " already exists, skipping");
            } else {
                LOG.info("Creating class " + className);
                ctClasses.put(className, classPool.makeClass(className));
            }// ww  w .j  av a  2  s.  c o  m

            break;
        }
    }

    reader.close();

    return ctClasses;
}

From source file:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterImpl.java

private Map<String, Class<?>> findExistingClasses(final InputStream stream) throws XMLStreamException {
    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
    Map<String, Class<?>> existingClasses = new HashMap<String, Class<?>>();

    while (reader.hasNext() && reader.next() > 0) {
        if (isTagStarted(reader, TAG_MODEL)) {
            String pluginIdentifier = getPluginIdentifier(reader);
            String modelName = getStringAttribute(reader, L_NAME);
            String className = ClassNameUtils.getFullyQualifiedClassName(pluginIdentifier, modelName);

            try {
                existingClasses.put(className, classLoader.loadClass(className));
                LOG.info("Class " + className + " already exists, skipping");
            } catch (ClassNotFoundException e) {
                LOG.info("Class " + className + " not found, will be generated");
            }//www.  j ava 2s .c o m

            break;
        }
    }

    reader.close();

    return existingClasses;
}

From source file:com.autonomy.aci.client.services.impl.AbstractStAXProcessor.java

/**
 * This method firstly checks that the content type of the response is text based and can be parsed. If so, it
 * converts the <tt>AciResponseInputStream</tt> into a StAX <tt>XMLStreamReader</tt> and calls the the {@link
 * #process(javax.xml.stream.XMLStreamReader)} method that should be implemented in a subclass to do all the work.
 * @param aciResponseInputStream The ACI response to process
 * @return An object of type <tt>T</tt>
 * @throws AciErrorException  If the ACI response was an error response
 * @throws ProcessorException If an error occurred during the processing of the IDOL response
 *//*  w  w  w.  ja  v  a2  s.c om*/
public T process(final AciResponseInputStream aciResponseInputStream) {
    LOGGER.trace("process() called...");

    if (!"text/xml".equalsIgnoreCase(aciResponseInputStream.getContentType())) {
        throw new ProcessorException(
                "This processor is unable to process non-text ACI responses. The content type for this response is "
                        + aciResponseInputStream.getContentType());
    }

    // Define this here so we can make sure it's closed when the processor is finished...
    XMLStreamReader xmlStreamReader = null;

    try {
        // Update the factory with the various properties as they might have changed since the last run...
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, namespaceAware);
        xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, validating);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, coalescing);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, replacingEntityReferences);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,
                supportingExternalEntities);
        xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, supportDtd);

        // Convert the input stream..
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(aciResponseInputStream);
        return process(xmlStreamReader);
    } catch (final XMLStreamException xmlse) {
        throw new ProcessorException("Unable to convert the InputStream to a XMLStreamReader", xmlse);
    } finally {
        if (xmlStreamReader != null) {
            try {
                // This does NOT close the underlying AciResponseInputStream
                xmlStreamReader.close();
            } catch (final XMLStreamException xmlse) {
                LOGGER.error("Unable to close the XMLStreamReader.", xmlse);
            }
        }
    }
}

From source file:net.landora.video.info.file.FileInfoManager.java

private synchronized Map<String, FileInfo> parseCacheFile(File file) {
    InputStream is = null;/* ww w. jav a 2 s  .  c o  m*/
    try {
        is = new BufferedInputStream(new FileInputStream(file));
        if (COMPRESS_INFO_FILE) {
            is = new GZIPInputStream(is);
        }

        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(is);

        reader.nextTag();
        reader.require(XMLStreamReader.START_ELEMENT, null, "files");

        Map<String, FileInfo> files = new HashMap<String, FileInfo>();

        while (reader.nextTag() != XMLStreamReader.END_ELEMENT) {
            reader.require(XMLStreamReader.START_ELEMENT, null, "file");

            FileInfo info = new FileInfo();
            String filename = reader.getAttributeValue(null, "filename");
            info.setFilename(filename);
            info.setE2dkHash(reader.getAttributeValue(null, "ed2k"));
            info.setFileSize(Long.parseLong(reader.getAttributeValue(null, "length")));
            info.setLastModified(Long.parseLong(reader.getAttributeValue(null, "lastmodified")));
            info.setMetadataSource(reader.getAttributeValue(null, "metadatasource"));
            info.setMetadataId(reader.getAttributeValue(null, "metadataid"));
            info.setVideoId(reader.getAttributeValue(null, "videoid"));

            files.put(filename, info);

            XMLUtilities.ignoreTag(reader);

        }
        reader.close();

        return files;

    } catch (Exception e) {
        log.error("Error parsing file cache.", e);
        return new HashMap<String, FileInfo>();
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }
    }
}

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. j  av a 2  s.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());
}