Example usage for javax.xml.stream XMLStreamReader getText

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

Introduction

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

Prototype

public String getText();

Source Link

Document

Returns the current value of the parse event as a string, this returns the string value of a CHARACTERS event, returns the value of a COMMENT, the replacement value for an ENTITY_REFERENCE, the string value of a CDATA section, the string value for a SPACE event, or the String value of the internal subset of the DTD.

Usage

From source file:XmlReaderToWriter.java

public static void write(XMLStreamReader xmlr, XMLStreamWriter writer) throws XMLStreamException {
    switch (xmlr.getEventType()) {
    case XMLEvent.START_ELEMENT:
        final String localName = xmlr.getLocalName();
        final String namespaceURI = xmlr.getNamespaceURI();
        if (namespaceURI != null && namespaceURI.length() > 0) {
            final String prefix = xmlr.getPrefix();
            if (prefix != null)
                writer.writeStartElement(prefix, localName, namespaceURI);
            else/*from w w w .ja va2 s. c o m*/
                writer.writeStartElement(namespaceURI, localName);
        } else {
            writer.writeStartElement(localName);
        }

        for (int i = 0, len = xmlr.getNamespaceCount(); i < len; i++) {
            writer.writeNamespace(xmlr.getNamespacePrefix(i), xmlr.getNamespaceURI(i));
        }

        for (int i = 0, len = xmlr.getAttributeCount(); i < len; i++) {
            String attUri = xmlr.getAttributeNamespace(i);
            if (attUri != null)
                writer.writeAttribute(attUri, xmlr.getAttributeLocalName(i), xmlr.getAttributeValue(i));
            else
                writer.writeAttribute(xmlr.getAttributeLocalName(i), xmlr.getAttributeValue(i));
        }
        break;
    case XMLEvent.END_ELEMENT:
        writer.writeEndElement();
        break;
    case XMLEvent.SPACE:
    case XMLEvent.CHARACTERS:
        writer.writeCharacters(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength());
        break;
    case XMLEvent.PROCESSING_INSTRUCTION:
        writer.writeProcessingInstruction(xmlr.getPITarget(), xmlr.getPIData());
        break;
    case XMLEvent.CDATA:
        writer.writeCData(xmlr.getText());
        break;

    case XMLEvent.COMMENT:
        writer.writeComment(xmlr.getText());
        break;
    case XMLEvent.ENTITY_REFERENCE:
        writer.writeEntityRef(xmlr.getLocalName());
        break;
    case XMLEvent.START_DOCUMENT:
        String encoding = xmlr.getCharacterEncodingScheme();
        String version = xmlr.getVersion();

        if (encoding != null && version != null)
            writer.writeStartDocument(encoding, version);
        else if (version != null)
            writer.writeStartDocument(xmlr.getVersion());
        break;
    case XMLEvent.END_DOCUMENT:
        writer.writeEndDocument();
        break;
    case XMLEvent.DTD:
        writer.writeDTD(xmlr.getText());
        break;
    }
}

From source file:com.amalto.core.load.xml.SetId.java

public void parse(StateContext context, XMLStreamReader reader) throws XMLStreamException {
    int next = reader.next();
    if (next == XMLEvent.END_ELEMENT) {
        // Means we started an ID but got no text in it, so set it to empty string
        context.getMetadata().setId(context.getCurrentIdElement(), StringUtils.EMPTY);
        // ... and move to EndElement state
        context.setCurrent(EndElement.INSTANCE);
        return;//from  w  ww . j a v a 2 s .  c o m
    } else if (next != XMLEvent.CHARACTERS) {
        // Everything else (not END_ELEMENT and not CHARACTERS is error).
        throw new IllegalStateException("Expected characters but got XML event id #" + next);
    }

    // We're parsing characters so call super.parse(context, reader)...
    super.parse(context, reader);
    // ...and we're also setting id for metadata
    context.getMetadata().setId(context.getCurrentIdElement(), reader.getText());
    // If we're ready, flush document
    if (doFlush(context)) {
        Utils.doParserCallback(context, reader, context.getMetadata());
    }
}

From source file:ar.com.zauber.commons.spring.test.impl.TamperdataHttpServletRequestFactory.java

/** hace el trabajo sucio 
 * @throws UnsupportedEncodingException */
private HttpServletRequest parse(final XMLStreamReader reader)
        throws XMLStreamException, UnsupportedEncodingException {
    final MockHttpServletRequest ret = new MockHttpServletRequest();
    ret.setMethod("POST");
    String header = null;/*w w  w.ja  v  a 2s  .  c om*/
    String postHeader = null;
    int event;
    while ((event = reader.next()) != XMLStreamConstants.END_DOCUMENT) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            final String name = reader.getLocalName();
            if (name.equals("tdRequestHeader") || name.equals("tdPostHeader")) {
                header = reader.getAttributeValue(0);
            } else if (name.equals("tdPostElements")) {
                ret.setMethod("POST");
            } else if (name.equals("tdPostElement")) {
                postHeader = reader.getAttributeValue(0);
            }
        } else if (event == XMLStreamConstants.CHARACTERS) {
            String text = reader.getText();
            if (text.length() > 1 && Character.isWhitespace(text.charAt(0))) {
                text = text.substring(1);
            }
            if (text.length() > 1 && Character.isWhitespace(text.charAt(text.length() - 1))) {
                text = text.substring(0, text.length() - 1);
            }

            final String value = URLDecoder.decode(URLDecoder.decode(text, encoding), encoding);
            if (header != null) {
                ret.addHeader(header, value);
            } else if (postHeader != null) {
                ret.addParameter(postHeader, value);
            }
            header = null;
            postHeader = null;
        } else {
            header = null;
            postHeader = null;
        }
    }
    reader.close();
    return ret;
}

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

/**
 * Reserved for internal use. Parses the operation response as an entity. Parses the result returned in the
 * specified stream in AtomPub format into a {@link TableResult} containing an entity of the specified class type
 * projected using the specified resolver.
 * //  www . j a v  a2  s .  com
 * @param xmlr
 *            An <code>XMLStreamReader</code> on the input stream.
 * @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 entity as an 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} containing the parsed entity result of the operation.
 * 
 * @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 parseAtomEntity(final XMLStreamReader xmlr,
        final Class<T> clazzType, final EntityResolver<R> resolver, final OperationContext opContext)
        throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException,
        StorageException {
    int eventType = xmlr.getEventType();
    final TableResult res = new TableResult();

    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.ENTRY);

    String etag = StringEscapeUtils.unescapeHtml4(
            xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.ETAG));

    res.setEtag(etag);

    while (xmlr.hasNext()) {
        eventType = xmlr.next();
        if (eventType == XMLStreamConstants.CHARACTERS) {
            xmlr.getText();
            continue;
        }

        final String name = xmlr.getName().toString();

        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.ID)) {
                Utility.readElementFromXMLReader(xmlr, ODataConstants.ID);
            } else if (name
                    .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) {
                // Do read properties
                if (resolver == null && clazzType == null) {
                    return res;
                } else {
                    res.setProperties(readAtomProperties(xmlr, opContext));
                    break;
                }
            }
        }
    }

    // Move to end Content
    eventType = xmlr.next();
    if (eventType == XMLStreamConstants.CHARACTERS) {
        eventType = xmlr.next();
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.CONTENT);

    eventType = xmlr.next();
    if (eventType == XMLStreamConstants.CHARACTERS) {
        eventType = xmlr.next();
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.ENTRY);

    String rowKey = null;
    String partitionKey = null;
    Date timestamp = null;

    // Remove core properties from map and set individually
    EntityProperty tempProp = res.getProperties().remove(TableConstants.PARTITION_KEY);
    if (tempProp != null) {
        partitionKey = tempProp.getValueAsString();
    }

    tempProp = res.getProperties().remove(TableConstants.ROW_KEY);
    if (tempProp != null) {
        rowKey = tempProp.getValueAsString();
    }

    tempProp = res.getProperties().remove(TableConstants.TIMESTAMP);
    if (tempProp != null) {
        timestamp = tempProp.getValueAsDate();
    }

    if (resolver != null) {
        // Call resolver
        res.setResult(resolver.resolve(partitionKey, rowKey, timestamp, res.getProperties(), res.getEtag()));
    } else if (clazzType != null) {
        // Generate new entity and return
        final T entity = clazzType.newInstance();
        entity.setEtag(res.getEtag());

        entity.setPartitionKey(partitionKey);
        entity.setRowKey(rowKey);
        entity.setTimestamp(timestamp);

        entity.readEntity(res.getProperties(), opContext);

        res.setResult(entity);
    }

    return res;
}

From source file:com.sazneo.export.file.FileProcessor.java

/**
 * Process the XML file//from   w  ww  .  j a v a2 s  .  co m
 */
public void process() {
    try {
        Reader reader = new FileReader(exportFile);
        XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
        XMLStreamReader xmlStreamReader = xmlFactory.createXMLStreamReader(reader);
        boolean fileTag = false;
        String fileName = null;
        Integer fileSize = null;
        while (xmlStreamReader.hasNext()) {
            xmlStreamReader.next();

            if (xmlStreamReader.getEventType() == XMLStreamReader.START_ELEMENT) {
                if ("file".equals(xmlStreamReader.getLocalName())) {
                    fileTag = true;
                    fileName = MessageFormat.format("{0}_{1}", xmlStreamReader.getAttributeValue(null, "id"),
                            xmlStreamReader.getAttributeValue(null, "filename"));
                    fileSize = Integer.parseInt(xmlStreamReader.getAttributeValue(null, "size"));
                    logger.debug(MessageFormat.format("XML contains file with name: {0} and size {1} bytes",
                            fileName, fileSize));
                }
            }

            if (fileTag) {
                if (xmlStreamReader.getEventType() == XMLStreamReader.CHARACTERS) {
                    exportFile(xmlStreamReader.getText(), fileName, fileSize);
                }

                if (xmlStreamReader.getEventType() == XMLStreamReader.END_ELEMENT) {
                    fileSize = null;
                    fileName = null;
                    fileTag = false;
                }
            }
        }
    } catch (FileNotFoundException e) {
        logger.error(MessageFormat.format("Could not find export file:-\n{0}", e));
    } catch (XMLStreamException e) {
        logger.error(MessageFormat.format("Could not parse xml export file:-\n{0}", e));
    }
}

From source file:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java

private void parse(FtpSubscription ftpSubscription, final InputStream is) throws XMLStreamException {
    final XMLInputFactory factory = XMLInputFactory.newInstance();
    factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, true);
    factory.setProperty(XMLInputFactory.IS_COALESCING, true);
    final XMLStreamReader reader = factory.createXMLStreamReader(is, "UTF-8");
    CJProduct product = null;// www.  j a  v a 2  s .  co m
    String tagContent = null;
    //final ServiceContext serviceContext = new ServiceContext();

    //ServiceContext serviceContext = ServiceContextFactory.getInstance(
    //        BlogsEntry.class.getName(), actionRequest);

    //serviceContext.setScopeGroupId(20159);
    while (reader.hasNext()) {
        final int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            //tagContent = "";
            if ("product".equals(reader.getLocalName())) {
                product = _cjProductLocalService.createCJProduct(0);
            }
            break;
        case XMLStreamConstants.CHARACTERS:
            //tagContent += reader.getText().trim();
            tagContent = reader.getText().trim();
            break;
        case XMLStreamConstants.END_ELEMENT:
            switch (reader.getLocalName()) {
            case "product":
                try {

                    _log.warn("refreshing document...");
                    _cjProductLocalService.refresh(ftpSubscription, product);
                } catch (final SystemException e) {
                    _log.error(e);
                } catch (final PortalException e) {
                    _log.error(e);
                }
                break;
            case "programname":
                product.setProgramName(tagContent);
                break;
            case "programurl":
                product.setProgramUrl(tagContent);
                break;
            case "catalogname":
                product.setCatalogName(tagContent);
                break;
            case "lastupdated":
                product.setLastUpdated(tagContent);
                break;
            case "name":
                product.setName(tagContent);
                break;
            case "keywords":
                product.setKeywords(tagContent);
                break;
            case "description":
                product.setDescription(tagContent);
                break;
            case "sku":
                product.setSku(tagContent);
                break;
            case "manufacturer":
                product.setManufacturer(tagContent);
                break;
            case "manufacturerid":
                product.setManufacturerId(tagContent);
                break;
            case "currency":
                product.setCurrency(tagContent);
                break;
            case "price":
                product.setPrice(tagContent);
                break;
            case "buyurl":
                product.setBuyUrl(tagContent);
                break;
            case "impressionurl":
                product.setImpressionUrl(tagContent);
                break;
            case "imageurl":
                product.setImageUrl(tagContent);
                break;
            case "instock":
                product.setInStock(tagContent);
                break;
            }
            break;
        case XMLStreamConstants.START_DOCUMENT:
            break;
        }
    }
}

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

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

    if (parser == null) {
        return;//from ww w  . jav  a  2  s  .c  om
    }

    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:ddf.catalog.source.solr.DynamicSchemaResolver.java

/**
 * Given xml as a string, this method will parse out element text and CDATA text. It separates
 * each by one space character./*  w w  w.  j  ava2  s  .c o m*/
 *
 * @param xmlDatas List of XML as {@code String}
 * @return parsed CDATA and element text
 */
protected List<String> parseTextFrom(List<Serializable> xmlDatas) {

    StringBuilder builder = new StringBuilder();
    List<String> parsedTexts = new ArrayList<>();
    XMLStreamReader xmlStreamReader = null;
    StringReader sr = null;
    long starttime = System.currentTimeMillis();

    try {
        for (Serializable xmlData : xmlDatas) {
            // xml parser does not handle leading whitespace
            sr = new StringReader(xmlData.toString());
            xmlStreamReader = XML_INPUT_FACTORY.createXMLStreamReader(sr);

            while (xmlStreamReader.hasNext()) {
                int event = xmlStreamReader.next();

                if (event == XMLStreamConstants.CHARACTERS || event == XMLStreamConstants.CDATA) {

                    String text = xmlStreamReader.getText();

                    if (StringUtils.isNotBlank(text)) {
                        builder.append(" ").append(text.trim());
                    }

                }
                if (event == XMLStreamConstants.START_ELEMENT) {
                    for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) {

                        String text = xmlStreamReader.getAttributeValue(i);

                        if (StringUtils.isNotBlank(text)) {
                            builder.append(" ").append(text.trim());
                        }
                    }
                }
            }
            parsedTexts.add(builder.toString());
            builder.setLength(0);
        }
    } catch (XMLStreamException e1) {
        LOGGER.warn("Failure occurred in parsing the xml data. No data has been stored or indexed.", e1);
    } finally {
        IOUtils.closeQuietly(sr);
        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (XMLStreamException e) {
                LOGGER.debug("Exception closing XMLStreamReader", e);
            }
        }
    }
    long endTime = System.currentTimeMillis();

    LOGGER.debug("Parsing took {} ms", endTime - starttime);

    return parsedTexts;
}

From source file:davmail.exchange.ews.EWSMethod.java

protected String getTagContent(XMLStreamReader reader) throws XMLStreamException {
    String tagLocalName = reader.getLocalName();
    while (reader.hasNext() && !(reader.getEventType() == XMLStreamConstants.END_ELEMENT)) {
        reader.next();//from ww w  .  ja v  a2 s .  c o m
        if (reader.getEventType() == XMLStreamConstants.CHARACTERS) {
            return reader.getText();
        }
    }
    // empty tag
    if (reader.hasNext()) {
        return null;
    } else {
        throw new XMLStreamException("End element for " + tagLocalName + " not found");
    }
}

From source file:com.microsoft.tfs.core.memento.XMLMemento.java

/**
 * Reads the current element from the given reader and returns the
 * {@link XMLMemento} read from its data. The {@link XMLStreamReader} must
 * be positioned at {@link XMLStreamConstants#START_ELEMENT}.
 *
 * @param reader/*from ww w.  j  a v a 2s .  c o  m*/
 *        the reader (must not be <code>null</code>)
 * @return the {@link XMLMemento} read from the stream
 * @throws XMLStreamException
 *         if an error occurred reading from the reader
 */
private synchronized void readFromElement(final XMLStreamReader reader) throws XMLStreamException {
    Check.notNull(reader, "reader"); //$NON-NLS-1$

    /*
     * Read all the attributes from the current element.
     */
    final int attributeCount = reader.getAttributeCount();
    for (int i = 0; i < attributeCount; i++) {
        putString(reader.getAttributeLocalName(i), reader.getAttributeValue(i));
    }

    /*
     * Process child nodes (which may be text or child Mementos).
     */
    String localName;
    int event;
    do {
        event = reader.next();

        if (event == XMLStreamConstants.START_ELEMENT) {
            localName = reader.getLocalName();

            final XMLMemento child = (XMLMemento) createChild(localName);
            child.readFromElement(reader);
        } else if (event == XMLStreamConstants.CHARACTERS) {
            putTextData(reader.getText());
        }
    } while (event != XMLStreamConstants.END_ELEMENT);
}