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:org.codice.ddf.opensearch.source.OpenSearchSource.java

private InputTransformer getInputTransformer(InputStream inputStream) throws UnsupportedQueryException {
    XMLStreamReader xmlStreamReader = null;
    try {//from   w ww .  ja  va2s  .c o m
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(inputStream);
        while (xmlStreamReader.hasNext()) {
            int next = xmlStreamReader.next();
            if (next == XMLStreamConstants.START_ELEMENT) {
                String namespaceUri = xmlStreamReader.getNamespaceURI();
                InputTransformer transformerReference = lookupTransformerReference(namespaceUri);
                if (transformerReference != null) {
                    return transformerReference;
                }
            }
        }
    } catch (XMLStreamException | InvalidSyntaxException e) {
        LOGGER.debug("Failed to parse transformer namespace", e);
    } finally {
        try {
            if (xmlStreamReader != null) {
                xmlStreamReader.close();
            }
        } catch (XMLStreamException e) {
            LOGGER.debug("Failed to close namespace reader", e);
        }
    }

    throw new UnsupportedQueryException(
            "Unable to find applicable InputTransformer for metacard content from Atom feed.");
}

From source file:org.commonjava.maven.ext.manip.util.PomPeek.java

private void parseCoordElements(final File pom) {
    Reader reader = null;//from ww  w  .j a va  2s.  com
    XMLStreamReader xml = null;
    try {
        reader = new FileReader(pom);
        xml = XMLInputFactory.newFactory().createXMLStreamReader(reader);

        final Stack<String> path = new Stack<String>();
        while (xml.hasNext()) {
            final int evt = xml.next();
            switch (evt) {
            case START_ELEMENT: {
                final String elem = xml.getLocalName();
                path.push(elem);
                if (captureValue(elem, path, xml)) {
                    // seems like xml.getElementText() traverses the END_ELEMENT event...
                    path.pop();
                }
                break;
            }
            case END_ELEMENT: {
                final String elem = xml.getLocalName();
                if (MODULES_ELEM.equals(elem)) {
                    modulesDone = true;
                }

                path.pop();
                break;
            }
            default: {
            }
            }

            if (foundAll()) {
                return;
            }
        }
    } catch (final IOException e) {
        logger.warn("Failed to peek at POM coordinate for: " + pom + " Reason: " + e.getMessage()
                + "\nThis POM will NOT be available as an ancestor to other models during effective-model building.",
                e);
    } catch (final XMLStreamException e) {
        logger.warn("Failed to peek at POM coordinate for: " + pom + " Reason: " + e.getMessage()
                + "\nThis POM will NOT be available as an ancestor to other models during effective-model building.",
                e);
    } catch (final FactoryConfigurationError e) {
        logger.warn("Failed to peek at POM coordinate for: " + pom + " Reason: " + e.getMessage()
                + "\nThis POM will NOT be available as an ancestor to other models during effective-model building.",
                e);
    } finally {
        if (xml != null) {
            try {
                xml.close();
            } catch (final XMLStreamException e) {
            }
        }

        try {
            reader.close();
        } catch (final IOException ioe) {
        }
    }
}

From source file:org.commonjava.maven.galley.maven.parse.PomPeek.java

private void parseCoordElements() {
    InputStream in = null;//  w w w .ja  v a2s  .com
    XMLStreamReader xml = null;
    try {
        if (pom != null) {
            in = new FileInputStream(pom);
        } else if (transfer != null) {
            in = transfer.openInputStream(false);
        } else {
            in = stream;
        }

        xml = XMLInputFactory.newFactory().createXMLStreamReader(in);

        final Stack<String> path = new Stack<>();
        while (xml.hasNext()) {
            final int evt = xml.next();
            switch (evt) {
            case START_ELEMENT: {
                final String elem = xml.getLocalName();
                if (captureValue(elem, path, xml)) {
                    // seems like xml.getElementText() traverses the END_ELEMENT event...
                    path.pop();
                }
                break;
            }
            case END_ELEMENT: {
                path.pop();
                break;
            }
            default: {
            }
            }

            if (foundAll()) {
                return;
            }
        }
    } catch (final IOException | FactoryConfigurationError | XMLStreamException e) {
        logger.warn("Failed to peek at POM coordinate for: " + pom + " Reason: " + e.getMessage()
                + "\nThis POM will NOT be available as an ancestor to other models during effective-model building.",
                e);
    } finally {
        if (xml != null) {
            try {
                xml.close();
            } catch (final XMLStreamException e) {
                logger.warn("Failed to close XMLStreamReader: " + e.getMessage(), e);
            }
        }

        closeQuietly(in);
    }
}

From source file:org.deegree.client.core.renderer.OutputXMLRenderer.java

private void encodeXML(ResponseWriter writer, String value) throws IOException {
    int depth = 0;
    try {//w ww  . jav a 2s  .  c om
        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(value));
        boolean lastWasEndElement = false;
        boolean lastWasComment = false;
        while (reader.hasNext()) {
            switch (reader.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                if (!lastWasComment) {
                    writer.startElement("br", null);
                    writer.endElement("br");
                }
                writer.write(getSpaces(depth));
                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&lt;");
                writer.endElement("span");

                writer.startElement("span", null);
                writer.writeAttribute("class", "tag", null);
                String prefix = reader.getPrefix();
                writer.write(
                        (prefix != null && prefix.length() > 0 ? prefix + ":" : "") + reader.getLocalName());
                writer.endElement("span");

                for (int i = 0; i < reader.getAttributeCount(); i++) {
                    writer.startElement("span", null);
                    writer.writeAttribute("class", "attributeName", null);
                    writer.write("&#160;");
                    String attributePrefix = reader.getAttributePrefix(i);
                    writer.write(
                            (attributePrefix != null && attributePrefix.length() > 0 ? attributePrefix + ":"
                                    : "") + reader.getAttributeLocalName(i));
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("=\"");
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "text", null);
                    writer.write(encodeString(reader.getAttributeValue(i)));
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("\"");
                    writer.endElement("span");
                }

                for (int i = 0; i < reader.getNamespaceCount(); i++) {
                    writer.startElement("span", null);
                    writer.writeAttribute("class", "attributeName", null);
                    writer.write("&#160;");
                    String nsPrefix = reader.getNamespacePrefix(i);
                    writer.write("xmlns");
                    if (nsPrefix != null && !nsPrefix.isEmpty()) {
                        writer.write(":" + nsPrefix);
                    }
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("=\"");
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "text", null);
                    writer.write(reader.getNamespaceURI(i));
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("\"");
                    writer.endElement("span");
                }

                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&gt;");
                writer.endElement("span");
                depth++;
                lastWasEndElement = false;
                lastWasComment = false;
                break;
            case XMLStreamConstants.CHARACTERS:
                String text = reader.getText();
                if (text.trim().length() > 0) {
                    writer.startElement("span", null);
                    writer.writeAttribute("class", "text", null);
                    writer.write(encodeString(text));
                    writer.endElement("span");
                    lastWasEndElement = false;
                    lastWasComment = false;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                depth--;
                if (lastWasEndElement) {
                    writer.startElement("br", null);
                    writer.endElement("br");
                    writer.write(getSpaces(depth));
                }
                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&lt;/");
                writer.endElement("span");

                writer.startElement("span", null);
                writer.writeAttribute("class", "tag", null);
                prefix = reader.getPrefix();
                writer.write(
                        (prefix != null && prefix.length() > 0 ? prefix + ":" : "") + reader.getLocalName());
                writer.endElement("span");

                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&gt;");
                writer.endElement("span");
                lastWasEndElement = true;
                lastWasComment = false;
                break;
            case XMLStreamConstants.COMMENT:
                writer.startElement("div", null);
                writer.writeAttribute("class", "comment", null);
                writer.write("&lt;/!--" + reader.getText() + "--&gt;");
                writer.endElement("div");
                lastWasEndElement = false;
                lastWasComment = true;
                break;
            default:
                break;
            }
            reader.next();

        }
        reader.close();
    } catch (Throwable e) {
        if (depth == 0) {
            writer.writeText("Response could not parsed as XML.", null);
        } else {
            writer.writeText("... (if you want the complete document, please click the download button)", null);
        }
    }
}

From source file:org.deegree.commons.config.AbstractResourceManager.java

@Override
protected ExtendedResourceProvider<T> getProvider(URL file) {
    String namespace = null;/*from   ww w . j  av a 2  s  . co  m*/
    InputStream is = null;
    try {
        is = new DURL(file.toExternalForm()).openStream();
        XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(is);
        XMLStreamUtils.nextElement(xmlReader);
        namespace = xmlReader.getNamespaceURI();
        LOG.debug("Config namespace: '" + namespace + "'");
        xmlReader.close();
        return nsToProvider.get(namespace);
    } catch (Throwable e) {
        String msg = "Error determining configuration namespace for file '" + file + "'";
        LOG.error(msg);
    } finally {
        IOUtils.closeQuietly(is);
    }
    return null;
}

From source file:org.deegree.services.wps.execute.ExecuteRequestXMLAdapter.java

/**
 * Parses and validates the given <code>wps:ComplexData</code> element as an {@link EmbeddedComplexInput} object.
 * <p>//from   w w w .j a  v  a2  s . c om
 * The following "semantical" properties are validated by this method:
 * <ul>
 * <li>The specified UOM (unit-of-measure) must be supported according to the given {@link LiteralInputDefinition}.
 * If it is not specified (uom attribute is missing), the UOM from the definition is assumed.</li>
 * <li>If the dataType attribute is present, it must have the same value as specified by the
 * {@link LiteralInputDefinition}.</li>
 * </ul>
 * </p>
 * 
 * @param definition
 *            input parameter definition (from process description)
 * @param complexDataElement
 *            <code>wps:ComplexData</code> element to be parsed
 * @param title
 *            title for the input parameter (may be null)
 * @param summary
 *            abstract (narrative description) for the input parameter (may be null)
 * @param eCustomizer
 * @return corresponding {@link BoundingBoxInput} object
 * @throws OWSException
 *             if the element is not valid
 */
private EmbeddedComplexInput parseComplexData(ComplexInputDefinition definition, OMElement complexDataElement,
        LanguageString title, LanguageString summary, ExceptionCustomizer eCustomizer) throws OWSException {

    ComplexFormatType format = new ComplexFormatType();
    // "mimeType" attribute (optional)
    format.setMimeType(complexDataElement.getAttributeValue(new QName("mimeType")));
    // "encoding" attribute (optional)
    format.setEncoding(complexDataElement.getAttributeValue(new QName("encoding")));
    // "schema" attribute (optional)
    format.setSchema(complexDataElement.getAttributeValue(new QName("schema")));

    format = validateAndAugmentFormat(format, definition, eCustomizer);

    StreamBufferStore store = storageManager.newInputSink();
    LOG.debug("Storing embedded ComplexInput as XML");
    XMLStreamReader xmlReader = complexDataElement.getXMLStreamReaderWithoutCaching();
    XMLStreamWriter xmlWriter = null;
    try {
        xmlWriter = xmlOutputFactory.createXMLStreamWriter(store);
        XMLStreamUtils.skipStartDocument(xmlReader);
        XMLAdapter.writeElement(xmlWriter, xmlReader);
    } catch (Throwable t) {
        String msg = "Unable to extract embedded complex input: " + t.getMessage();
        throw new OWSException(msg, OWSException.NO_APPLICABLE_CODE);
    } finally {
        try {
            xmlReader.close();
        } catch (XMLStreamException e) {
            // nothing to do
        }
        try {
            xmlWriter.close();
        } catch (XMLStreamException e) {
            // nothing to do
        }
        IOUtils.closeQuietly(store);
    }

    return new EmbeddedComplexInput(definition, title, summary, format, store);
}

From source file:org.deegree.services.wps.input.EmbeddedComplexInput.java

@Override
public InputStream getValueAsBinaryStream() {

    XMLStreamReader xmlStream = null;
    String textValue = null;/*from   ww  w.  j a v  a2 s.com*/
    try {
        try {
            xmlStream = XMLInputFactory.newInstance().createXMLStreamReader(store.getInputStream());
        } catch (Throwable t) {
            throw new RuntimeException(t.getMessage());
        }
        XMLStreamUtils.skipStartDocument(xmlStream);
        textValue = xmlStream.getElementText();
    } catch (XMLStreamException e) {
        LOG.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage());
    } finally {
        if (xmlStream != null) {
            try {
                xmlStream.close();
            } catch (XMLStreamException e) {
                // nothing to do
            }
        }
    }

    ByteArrayInputStream is = null;

    if ("base64".equals(getEncoding())) {
        LOG.debug("Performing base64 decoding of embedded ComplexInput: " + textValue);
        is = new ByteArrayInputStream(Base64.decodeBase64(textValue));
    } else {
        LOG.warn("Unsupported encoding '" + getEncoding() + "'.");
        is = new ByteArrayInputStream(textValue.getBytes());
    }

    return is;
}

From source file:org.deegree.services.wps.provider.jrxml.contentprovider.Utils.java

public static ProcessletInputs getInputs(String parameterId, String mimeType, String schema,
        InputStream complexInput) throws IOException, XMLStreamException, FactoryConfigurationError {
    List<ProcessletInput> inputs = new ArrayList<ProcessletInput>();
    ProcessletInputs in = new ProcessletInputs(inputs);

    ComplexInputDefinition definition = new ComplexInputDefinition();
    definition.setTitle(getAsLanguageStringType(parameterId));
    definition.setIdentifier(getAsCodeType(parameterId));
    ComplexFormatType format = new ComplexFormatType();

    format.setEncoding("UTF-8");
    format.setMimeType(mimeType);/*from  www .  j  a va  2  s  .  c  om*/
    format.setSchema(schema);
    definition.setDefaultFormat(format);
    definition.setMaxOccurs(BigInteger.valueOf(1));
    definition.setMinOccurs(BigInteger.valueOf(0));

    File f = File.createTempFile("tmpStore", "");
    StreamBufferStore store = new StreamBufferStore(1024, f);

    XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(complexInput);
    XMLStreamWriter xmlWriter = null;
    try {
        xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(store);
        if (xmlReader.getEventType() == START_DOCUMENT) {
            xmlReader.nextTag();
        }
        XMLAdapter.writeElement(xmlWriter, xmlReader);
    } finally {
        try {
            xmlReader.close();
        } catch (XMLStreamException e) {
            // nothing to do
        }
        try {
            xmlWriter.close();
        } catch (XMLStreamException e) {
            // nothing to do
        }
        IOUtils.closeQuietly(store);
    }

    ComplexInputImpl mapProcesslet = new EmbeddedComplexInput(definition, new LanguageString("title", "ger"),
            new LanguageString("summary", "ger"), format, store);

    inputs.add(mapProcesslet);
    return in;
}

From source file:org.deegree.style.persistence.se.SeStyleStoreBuilder.java

@Override
public StyleStore build() {
    InputStream in = null;//  ww  w  .  j a  va  2 s .  co m
    XMLStreamReader reader = null;
    try {
        in = metadata.getLocation().getAsStream();
        XMLInputFactory fac = XMLInputFactory.newInstance();
        reader = fac.createXMLStreamReader(in);
        SymbologyParser parser = new SymbologyParser(metadata.getLocation());
        Style style = parser.parse(reader);
        return new SEStyleStore(style, metadata);
    } catch (Exception e) {
        throw new ResourceInitException("Could not read SE style file.", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (XMLStreamException e) {
            // eat it
        }
        closeQuietly(in);
    }
}

From source file:org.deegree.style.persistence.se.SEStyleStoreProvider.java

@Override
public SEStyleStore create(URL configUrl) throws ResourceInitException {
    InputStream in = null;//w  w w.j  a va  2 s .c  om
    XMLStreamReader reader = null;
    try {
        in = configUrl.openStream();
        XMLInputFactory fac = XMLInputFactory.newInstance();
        reader = fac.createXMLStreamReader(configUrl.toExternalForm(), in);
        Style style = SymbologyParser.INSTANCE.parse(reader);
        return new SEStyleStore(style);
    } catch (Throwable e) {
        throw new ResourceInitException("Could not read SE style file.", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (XMLStreamException e) {
            // eat it
        }
        closeQuietly(in);
    }
}