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.apache.axiom.util.stax.XMLStreamReaderUtilsTest.java

private void testGetDataHandlerFromElementWithUnexpectedContent(boolean useDHR) throws Exception {
    XMLStreamReader reader = StAXUtils.createXMLStreamReader(new StringReader("<test>\n<child/>\n</test>"));
    if (useDHR) {
        reader = new XOPDecodingStreamReader(reader, null);
    }// w  w w . j  a v  a  2s .c  o  m
    try {
        reader.next();

        // Check precondition
        assertTrue(reader.isStartElement());

        try {
            XMLStreamReaderUtils.getDataHandlerFromElement(reader);
            fail("Expected XMLStreamException");
        } catch (XMLStreamException ex) {
            // Expected
        }
    } finally {
        reader.close();
    }
}

From source file:org.apache.axiom.util.stax.XMLStreamReaderUtilsTest.java

private void testGetDataHandlerFromElementNonCoalescing(boolean useDHR) throws Exception {
    // We generate base64 that is sufficiently large to force the parser to generate
    // multiple CHARACTER events
    StringBuffer buffer = new StringBuffer("<test>");
    Base64EncodingStringBufferOutputStream out = new Base64EncodingStringBufferOutputStream(buffer);
    byte[] data = new byte[65536];
    new Random().nextBytes(data);
    out.write(data);/*w  ww. j  av a2s  .c om*/
    out.complete();
    buffer.append("</test>");
    XMLStreamReader reader = StAXUtils.createXMLStreamReader(StAXParserConfiguration.NON_COALESCING,
            new StringReader(buffer.toString()));
    if (useDHR) {
        reader = new XOPDecodingStreamReader(reader, null);
    }
    try {
        reader.next();

        // Check precondition
        assertTrue(reader.isStartElement());

        DataHandler dh = XMLStreamReaderUtils.getDataHandlerFromElement(reader);

        // Check postcondition
        assertTrue(reader.isEndElement());
        assertTrue(Arrays.equals(data, IOUtils.toByteArray(dh.getInputStream())));
    } finally {
        reader.close();
    }
}

From source file:org.apache.axis2.addressing.EndpointReference.java

/**
 * Read the EPR to the specified InputStream.
 *//*from  www .  j ava  2 s  .c om*/
public void readExternal(java.io.ObjectInput inObject) throws IOException, ClassNotFoundException {
    SafeObjectInputStream in = SafeObjectInputStream.install(inObject);

    // revision ID
    int revID = in.readInt();

    // make sure the object data is in a revision level we can handle
    if (revID != REVISION_2) {
        throw new ClassNotFoundException(ExternalizeConstants.UNSUPPORTED_REVID);
    }

    // String object id
    logCorrelationIDString = (String) in.readObject();

    // Read xml content
    in.readUTF(); // read marker
    int numBytes = in.readInt();

    byte[] serBytes = new byte[numBytes];

    // read the data from the input stream

    int bytesRead = 0;
    int numberOfBytesLastRead;

    while (bytesRead < numBytes) {
        numberOfBytesLastRead = in.read(serBytes, bytesRead, numBytes - bytesRead);

        if (numberOfBytesLastRead == -1) {
            // TODO: What should we do if the reconstitution fails?
            // For now, log the event and throw an exception
            if (log.isDebugEnabled()) {
                log.debug("readObject(): EPR logCorrelationID [" + logCorrelationIDString + "] "
                        + " ***WARNING*** unexpected end to data:    data read from input stream [" + bytesRead
                        + "]    expected data size [" + numBytes + "]");
            }

            IOException ioe = new IOException(
                    "Unable to deserialize the EndpointReference with logCorrelationID ["
                            + logCorrelationIDString + "]"
                            + "  Cause: Unexpected end to data from input stream");

            throw ioe;
        }

        bytesRead += numberOfBytesLastRead;
    }

    if (bytesRead == 0) {
        IOException ioe = new IOException("Unable to deserialize the EndpointReference with logCorrelationID ["
                + logCorrelationIDString + "]" + "  Cause: No data from input stream");

        throw ioe;
    }
    in.readUTF(); // read marker

    ByteArrayInputStream bais = new ByteArrayInputStream(serBytes);

    if (log.isDebugEnabled()) {
        String content = new String(serBytes);

        log.debug("readObject(): EPR logCorrelationID [" + logCorrelationIDString + "] "
                + "    expected content size [" + numBytes + "]" + "    content size [" + content.length() + "]"
                + "    EPR buffered content [" + content + "]");
    }

    XMLStreamReader xmlReader = null;

    try {
        OMElement om = OMXMLBuilderFactory.createOMBuilder(bais).getDocumentElement();

        // expand the OM so we can close the stream reader
        om.build();

        // trace point
        if (log.isDebugEnabled()) {
            log.debug(myClassName + ":readObject():  " + " EPR [" + logCorrelationIDString + "]"
                    + " EPR OM content [" + om.toString() + "]");
        }

        EndpointReferenceHelper.fromOM(this, om, AddressingConstants.Final.WSA_NAMESPACE);

    } catch (Exception e) {
        IOException ioe = new IOException("Unable to deserialize the EndpointReference with logCorrelationID ["
                + logCorrelationIDString + "]");
        ioe.initCause(e);

        if (log.isDebugEnabled()) {
            log.debug("readObject(): Unable to deserialize the EPR with logCorrelationID ["
                    + logCorrelationIDString + "]   original error [" + e.getClass().getName() + "]  message ["
                    + e.getMessage() + "]", e);
        }

        throw ioe;

    } finally {
        // Make sure that the reader is properly closed
        // Note that closing a ByteArrayInputStream has no effect

        if (xmlReader != null) {
            try {
                xmlReader.close();
            } catch (Exception e2) {
                IOException ioe2 = new IOException(
                        "Unable to close the XMLStreamReader for the EndpointReference with logCorrelationID ["
                                + logCorrelationIDString + "]");
                ioe2.initCause(e2);

                if (log.isDebugEnabled()) {
                    log.debug(
                            "readObject(): Unable to close the XMLStreamReader for the EPR with logCorrelationID ["
                                    + logCorrelationIDString + "]   original error [" + e2.getClass().getName()
                                    + "]  message [" + e2.getMessage() + "]",
                            e2);
                }

                throw ioe2;
            }
        }
    }
}

From source file:org.apache.axis2.jaxws.message.util.impl.SAAJConverterImpl.java

/**
 * Build SOAPTree Either the root or the parent is null. If the root is null, a new element is
 * created under the parent using information from the reader If the parent is null, the existing
 * root is updated with the information from the reader
 *
 * @param nc         NameCreator//from  w  w w .  j ava 2 s  .  c  o m
 * @param root       SOAPElement (the element that represents the data in the reader)
 * @param parent     (the parent of the element represented by the reader)
 * @param reader     XMLStreamReader. the first START_ELEMENT matches the root
 * @param quitAtBody - true if quit reading after the body START_ELEMENT
 */
protected SOAPElement buildSOAPTree(NameCreator nc, SOAPElement root, SOAPElement parent,
        XMLStreamReader reader, boolean quitAtBody) throws WebServiceException {
    try {
        while (reader.hasNext()) {
            int eventID = reader.next();
            switch (eventID) {
            case XMLStreamReader.START_ELEMENT: {

                // The first START_ELEMENT defines the prefix and attributes of the root
                if (parent == null) {
                    updateTagData(nc, root, reader, false);
                    parent = root;
                } else {
                    parent = createElementFromTag(nc, parent, reader);
                    if (root == null) {
                        root = parent;
                    }
                }
                if (quitAtBody && parent instanceof SOAPBody) {
                    return root;
                }
                break;
            }
            case XMLStreamReader.ATTRIBUTE: {
                String eventName = "ATTRIBUTE";
                this._unexpectedEvent(eventName);
                break;
            }
            case XMLStreamReader.NAMESPACE: {
                String eventName = "NAMESPACE";
                this._unexpectedEvent(eventName);
                break;
            }
            case XMLStreamReader.END_ELEMENT: {
                if (parent instanceof SOAPEnvelope) {
                    parent = null;
                } else {
                    parent = parent.getParentElement();
                }
                break;
            }
            case XMLStreamReader.CHARACTERS: {
                parent.addTextNode(reader.getText());
                break;
            }
            case XMLStreamReader.CDATA: {
                parent.addTextNode(reader.getText());
                break;
            }
            case XMLStreamReader.COMMENT: {
                // SOAP really doesn't have an adequate representation for comments.
                // The defacto standard is to add the whole element as a text node.
                parent.addTextNode("<!--" + reader.getText() + "-->");
                break;
            }
            case XMLStreamReader.SPACE: {
                parent.addTextNode(reader.getText());
                break;
            }
            case XMLStreamReader.START_DOCUMENT: {
                // Ignore
                break;
            }
            case XMLStreamReader.END_DOCUMENT: {
                // Close reader and ignore
                reader.close();
                break;
            }
            case XMLStreamReader.PROCESSING_INSTRUCTION: {
                // Ignore
                break;
            }
            case XMLStreamReader.ENTITY_REFERENCE: {
                // Ignore. this is unexpected in a web service message
                break;
            }
            case XMLStreamReader.DTD: {
                // Ignore. this is unexpected in a web service message
                break;
            }
            default:
                this._unexpectedEvent("EventID " + String.valueOf(eventID));
            }
        }
    } catch (WebServiceException e) {
        throw e;
    } catch (XMLStreamException e) {
        throw ExceptionFactory.makeWebServiceException(e);
    } catch (SOAPException e) {
        throw ExceptionFactory.makeWebServiceException(e);
    }
    return root;
}

From source file:org.apache.solr.handler.AnalysisRequestHandler.java

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    SolrParams params = req.getParams();
    Iterable<ContentStream> streams = req.getContentStreams();
    if (streams != null) {
        for (ContentStream stream : req.getContentStreams()) {
            InputStream is = null;
            XMLStreamReader parser = null;
            try {
                is = stream.getStream();
                final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType());
                parser = (charset == null) ? inputFactory.createXMLStreamReader(is)
                        : inputFactory.createXMLStreamReader(is, charset);

                NamedList<Object> result = processContent(parser, req.getSchema());
                rsp.add("response", result);
            } finally {
                if (parser != null)
                    parser.close();
                IOUtils.closeQuietly(is);
            }//  w  ww. j  ava  2 s .  c o  m
        }
    }
}

From source file:org.apache.solr.handler.AnalysisRequestHandler.java

NamedList<Object> processContent(XMLStreamReader parser, IndexSchema schema)
        throws XMLStreamException, IOException {
    NamedList<Object> result = new SimpleOrderedMap<Object>();
    while (true) {
        int event = parser.next();
        switch (event) {
        case XMLStreamConstants.END_DOCUMENT: {
            parser.close();
            return result;
        }// w  w  w .j  a v  a 2s .  co  m
        case XMLStreamConstants.START_ELEMENT: {
            String currTag = parser.getLocalName();
            if ("doc".equals(currTag)) {
                log.trace("Tokenizing doc...");

                SolrInputDocument doc = readDoc(parser);
                SchemaField uniq = schema.getUniqueKeyField();
                NamedList<NamedList<NamedList<Object>>> theTokens = new SimpleOrderedMap<NamedList<NamedList<Object>>>();
                result.add(doc.getFieldValue(uniq.getName()).toString(), theTokens);
                for (String name : doc.getFieldNames()) {
                    FieldType ft = schema.getFieldType(name);
                    Analyzer analyzer = ft.getAnalyzer();
                    Collection<Object> vals = doc.getFieldValues(name);
                    for (Object val : vals) {
                        Reader reader = new StringReader(val.toString());
                        TokenStream tstream = analyzer.tokenStream(name, reader);
                        NamedList<NamedList<Object>> tokens = getTokens(tstream);
                        theTokens.add(name, tokens);
                    }
                }
            }
            break;
        }
        }
    }
}

From source file:org.apache.solr.handler.DocumentAnalysisRequestHandler.java

/**
 * Resolves the {@link DocumentAnalysisRequest} from the given solr request.
 *
 * @param req The solr request./*from ww w  .j a  v a 2 s .co m*/
 *
 * @return The resolved document analysis request.
 *
 * @throws IOException        Thrown when reading/parsing the content stream of the request fails.
 * @throws XMLStreamException Thrown when reading/parsing the content stream of the request fails.
 */
DocumentAnalysisRequest resolveAnalysisRequest(SolrQueryRequest req) throws IOException, XMLStreamException {

    DocumentAnalysisRequest request = new DocumentAnalysisRequest();

    SolrParams params = req.getParams();

    String query = params.get(AnalysisParams.QUERY, params.get(CommonParams.Q, null));
    request.setQuery(query);

    boolean showMatch = params.getBool(AnalysisParams.SHOW_MATCH, false);
    request.setShowMatch(showMatch);

    ContentStream stream = extractSingleContentStream(req);
    InputStream is = null;
    XMLStreamReader parser = null;

    try {
        is = stream.getStream();
        final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType());
        parser = (charset == null) ? inputFactory.createXMLStreamReader(is)
                : inputFactory.createXMLStreamReader(is, charset);

        while (true) {
            int event = parser.next();
            switch (event) {
            case XMLStreamConstants.END_DOCUMENT: {
                parser.close();
                return request;
            }
            case XMLStreamConstants.START_ELEMENT: {
                String currTag = parser.getLocalName();
                if ("doc".equals(currTag)) {
                    log.trace("Reading doc...");
                    SolrInputDocument document = readDocument(parser, req.getSchema());
                    request.addDocument(document);
                }
                break;
            }
            }
        }

    } finally {
        if (parser != null)
            parser.close();
        IOUtils.closeQuietly(is);
    }
}

From source file:org.apache.solr.handler.loader.XMLLoader.java

@Override
public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream,
        UpdateRequestProcessor processor) throws Exception {
    final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType());

    InputStream is = null;/*ww w  .j a  v  a 2s  .  c o m*/
    XMLStreamReader parser = null;

    String tr = req.getParams().get(CommonParams.TR, null);
    if (tr != null) {
        final Transformer t = getTransformer(tr, req);
        final DOMResult result = new DOMResult();

        // first step: read XML and build DOM using Transformer (this is no overhead, as XSL always produces
        // an internal result DOM tree, we just access it directly as input for StAX):
        try {
            is = stream.getStream();
            final InputSource isrc = new InputSource(is);
            isrc.setEncoding(charset);
            final XMLReader xmlr = saxFactory.newSAXParser().getXMLReader();
            xmlr.setErrorHandler(xmllog);
            xmlr.setEntityResolver(EmptyEntityResolver.SAX_INSTANCE);
            final SAXSource source = new SAXSource(xmlr, isrc);
            t.transform(source, result);
        } catch (TransformerException te) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, te.getMessage(), te);
        } finally {
            IOUtils.closeQuietly(is);
        }
        // second step: feed the intermediate DOM tree into StAX parser:
        try {
            parser = inputFactory.createXMLStreamReader(new DOMSource(result.getNode()));
            this.processUpdate(req, processor, parser);
        } catch (XMLStreamException e) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
        } finally {
            if (parser != null)
                parser.close();
        }
    }
    // Normal XML Loader
    else {
        try {
            is = stream.getStream();
            if (log.isTraceEnabled()) {
                final byte[] body = IOUtils.toByteArray(is);
                // TODO: The charset may be wrong, as the real charset is later
                // determined by the XML parser, the content-type is only used as a hint!
                log.trace("body",
                        new String(body, (charset == null) ? ContentStreamBase.DEFAULT_CHARSET : charset));
                IOUtils.closeQuietly(is);
                is = new ByteArrayInputStream(body);
            }
            parser = (charset == null) ? inputFactory.createXMLStreamReader(is)
                    : inputFactory.createXMLStreamReader(is, charset);
            this.processUpdate(req, processor, parser);
        } catch (XMLStreamException e) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
        } finally {
            if (parser != null)
                parser.close();
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:org.apache.solr.handler.loader.XMLLoader.java

/**
 * @since solr 1.2/*  w  w  w.  jav  a  2  s  . c  o m*/
 */
void processUpdate(SolrQueryRequest req, UpdateRequestProcessor processor, XMLStreamReader parser)
        throws XMLStreamException, IOException, FactoryConfigurationError {
    AddUpdateCommand addCmd = null;
    SolrParams params = req.getParams();
    while (true) {
        int event = parser.next();
        switch (event) {
        case XMLStreamConstants.END_DOCUMENT:
            parser.close();
            return;

        case XMLStreamConstants.START_ELEMENT:
            String currTag = parser.getLocalName();
            if (currTag.equals(UpdateRequestHandler.ADD)) {
                log.trace("SolrCore.update(add)");

                addCmd = new AddUpdateCommand(req);

                // First look for commitWithin parameter on the request, will be overwritten for individual <add>'s
                addCmd.commitWithin = params.getInt(UpdateParams.COMMIT_WITHIN, -1);
                addCmd.overwrite = params.getBool(UpdateParams.OVERWRITE, true);

                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String attrName = parser.getAttributeLocalName(i);
                    String attrVal = parser.getAttributeValue(i);
                    if (UpdateRequestHandler.OVERWRITE.equals(attrName)) {
                        addCmd.overwrite = StrUtils.parseBoolean(attrVal);
                    } else if (UpdateRequestHandler.COMMIT_WITHIN.equals(attrName)) {
                        addCmd.commitWithin = Integer.parseInt(attrVal);
                    } else {
                        log.warn("XML element <add> has invalid XML attr: " + attrName);
                    }
                }

            } else if ("doc".equals(currTag)) {
                if (addCmd != null) {
                    log.trace("adding doc...");
                    addCmd.clear();
                    addCmd.solrDoc = readDoc(parser);
                    processor.processAdd(addCmd);
                } else {
                    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                            "Unexpected <doc> tag without an <add> tag surrounding it.");
                }
            } else if (UpdateRequestHandler.COMMIT.equals(currTag)
                    || UpdateRequestHandler.OPTIMIZE.equals(currTag)) {
                log.trace("parsing " + currTag);

                CommitUpdateCommand cmd = new CommitUpdateCommand(req,
                        UpdateRequestHandler.OPTIMIZE.equals(currTag));
                ModifiableSolrParams mp = new ModifiableSolrParams();

                for (int i = 0; i < parser.getAttributeCount(); i++) {
                    String attrName = parser.getAttributeLocalName(i);
                    String attrVal = parser.getAttributeValue(i);
                    mp.set(attrName, attrVal);
                }

                RequestHandlerUtils.validateCommitParams(mp);
                SolrParams p = SolrParams.wrapDefaults(mp, req.getParams()); // default to the normal request params for commit options
                RequestHandlerUtils.updateCommit(cmd, p);

                processor.processCommit(cmd);
            } // end commit
            else if (UpdateRequestHandler.ROLLBACK.equals(currTag)) {
                log.trace("parsing rollback");

                RollbackUpdateCommand cmd = new RollbackUpdateCommand(req);

                processor.processRollback(cmd);
            } // end rollback
            else if (UpdateRequestHandler.DELETE.equals(currTag)) {
                log.trace("parsing delete");
                processDelete(req, processor, parser);
            } // end delete
            break;
        }
    }
}

From source file:org.apache.solr.handler.XMLLoader.java

@Override
public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream) throws Exception {
    errHeader = "XMLLoader: " + stream.getSourceInfo();
    InputStream is = null;/* w ww.  jav a  2 s .  c  om*/
    XMLStreamReader parser = null;
    try {
        is = stream.getStream();
        final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType());
        if (XmlUpdateRequestHandler.log.isTraceEnabled()) {
            final byte[] body = IOUtils.toByteArray(is);
            // TODO: The charset may be wrong, as the real charset is later
            // determined by the XML parser, the content-type is only used as a hint!
            XmlUpdateRequestHandler.log.trace("body",
                    new String(body, (charset == null) ? ContentStreamBase.DEFAULT_CHARSET : charset));
            IOUtils.closeQuietly(is);
            is = new ByteArrayInputStream(body);
        }
        parser = (charset == null) ? inputFactory.createXMLStreamReader(is)
                : inputFactory.createXMLStreamReader(is, charset);
        this.processUpdate(req, processor, parser);
    } catch (XMLStreamException e) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
    } finally {
        if (parser != null)
            parser.close();
        IOUtils.closeQuietly(is);
    }
}