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:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Parses the operation response as a collection of entities. Reads entity data from the
 * specified input stream using the specified class type and optionally projects each entity result with the
 * specified resolver into an {@link ODataPayload} containing a collection of {@link TableResult} objects. .
 * /*from w w w  . j a va2  s.c o  m*/
 * @param inStream
 *            The <code>InputStream</code> to read the data to parse from.
 * @param clazzType
 *            The class type <code>T</code> implementing {@link TableEntity} for the entities returned. Set to
 *            <code>null</code> to ignore the returned entities and copy only response properties into the
 *            {@link TableResult} objects.
 * @param resolver
 *            An {@link EntityResolver} instance to project the entities into instances of type <code>R</code>. Set
 *            to <code>null</code> to return the entities as instances of the class type <code>T</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         An {@link ODataPayload} containing a collection of {@link TableResult} objects 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.
 */
@SuppressWarnings("unchecked")
protected static <T extends TableEntity, R> ODataPayload<?> parseResponse(final InputStream inStream,
        final Class<T> clazzType, final EntityResolver<R> resolver, final OperationContext opContext)
        throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException,
        StorageException {
    ODataPayload<T> corePayload = null;
    ODataPayload<R> resolvedPayload = null;
    ODataPayload<?> commonPayload = null;

    if (resolver != null) {
        resolvedPayload = new ODataPayload<R>();
        commonPayload = resolvedPayload;
    } else {
        corePayload = new ODataPayload<T>();
        commonPayload = corePayload;
    }

    final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(inStream);
    int eventType = xmlr.getEventType();
    xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null);
    eventType = xmlr.next();

    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.FEED);
    // skip feed chars
    eventType = xmlr.next();

    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.ENTRY)) {
                final TableResult res = parseEntity(xmlr, clazzType, resolver, opContext);
                if (corePayload != null) {
                    corePayload.tableResults.add(res);
                }

                if (resolver != null) {
                    resolvedPayload.results.add((R) res.getResult());
                } else {
                    corePayload.results.add((T) res.getResult());
                }
            }
        } else if (eventType == XMLStreamConstants.END_ELEMENT
                && name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.FEED)) {
            break;
        }
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.FEED);
    return commonPayload;
}

From source file:com.rockhoppertech.music.midi.js.xml.ModeFactoryXMLHelper.java

/**
 * Read modes.xml and create {@code Scale instances} from those definitions.
 *//*ww  w  .  j  a va2 s  .  c o m*/
public static void init() {
    List<Integer> intervals = null;
    Scale currentMode = null;
    String tagContent = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = null;
    try {
        reader = factory.createXMLStreamReader(ClassLoader.getSystemResourceAsStream("modes.xml"));
    } catch (XMLStreamException e) {
        e.printStackTrace();
        return;
    }

    try {
        while (reader.hasNext()) {
            int event = reader.next();

            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                String el = reader.getLocalName();
                logger.debug("start element '{}'", el);
                if ("mode".equals(el)) {
                    currentMode = new Scale();
                    intervals = new ArrayList<>();
                }
                if ("modes".equals(el)) {
                    modeList = new ArrayList<>();
                }
                break;

            case XMLStreamConstants.CHARACTERS:
                tagContent = reader.getText().trim();
                logger.debug("tagcontent '{}'", tagContent);
                break;

            case XMLStreamConstants.END_ELEMENT:
                switch (reader.getLocalName()) {
                case "mode":
                    // wow. both guava and commmons to get an int[] array
                    Integer[] array = FluentIterable.from(intervals).toArray(Integer.class);
                    // same as Integer[] array = intervals.toArray(new
                    // Integer[intervals.size()]);
                    int[] a = ArrayUtils.toPrimitive(array);
                    currentMode.setIntervals(a);
                    modeList.add(currentMode);
                    ScaleFactory.registerScale(currentMode);
                    break;
                case "interval":
                    logger.debug("interval '{}'", tagContent);
                    logger.debug("intervals '{}'", intervals);
                    intervals.add(Integer.parseInt(tagContent));
                    break;
                case "name":
                    currentMode.setName(tagContent);
                    break;
                }
                break;

            case XMLStreamConstants.START_DOCUMENT:
                modeList = new ArrayList<>();
                intervals = new ArrayList<>();
                break;
            }
        }
    } catch (XMLStreamException e) {
        logger.error(e.getLocalizedMessage(), e);
        e.printStackTrace();
    }

    logger.debug("mode list \n{}", modeList);
}

From source file:MDRevealer.ResistanceTests.java

private static ArrayList<HashMap<String, String>> parse_test(File rt_input)
        throws XMLStreamException, FileNotFoundException {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader xsr = xif.createXMLStreamReader(new FileInputStream(rt_input));
    ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> hm = new HashMap<String, String>();
    String key = "null";
    while (xsr.hasNext() == true) {

        int constant = xsr.next();

        switch (constant) {
        case XMLStreamConstants.START_ELEMENT:
            key = xsr.getLocalName();//from  www  . ja  v  a2 s . c o m
            if (xsr.getAttributeCount() > 0) {
                for (int i = 0; i < xsr.getAttributeCount(); i++) {
                    hm.put(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
                }
                test.add(hm);
                hm = new HashMap<String, String>();
            }
            break;
        case XMLStreamConstants.CHARACTERS:
            if (!xsr.isWhiteSpace()) {
                hm.put(key, xsr.getText());
                test.add(hm);
            }
            hm = new HashMap<String, String>();
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (xsr.getLocalName().equals("condition")) {
                hm.put("condition_over", "true");
                test.add(hm);
                hm = new HashMap<String, String>();
            }
            break;
        }
    }
    return test;
}

From source file:edu.utah.further.core.xml.stax.XmlStreamElementPrinter.java

@Override
public void visitProcessingInstruction(final XMLStreamReader xmlReader) {
    os.print("<?");
    if (xmlReader.hasText())
        os.print(xmlReader.getText());
    os.print("?>");
}

From source file:com.lin.umws.service.impl.UserServiceImpl.java

public User login(String username, String password) throws UserException {
    System.out.println("spring: " + springService);
    HeaderList headerList = (HeaderList) cxt.getMessageContext()
            .get(JAXWSProperties.INBOUND_HEADER_LIST_PROPERTY);
    Header header = headerList.get(new QName("http://service.umws.lin.com/", "licenseType"), true);
    try {/*from   w  w  w. jav  a  2 s .c o  m*/
        XMLStreamReader reader = header.readHeader();
        while (reader.hasNext()) {
            int type = reader.next();
            if (type == XMLStreamReader.CHARACTERS) {
                System.out.println(reader.getText());
            }
        }
    } catch (XMLStreamException e) {
        e.printStackTrace();
    }

    for (User user : userMap.values()) {
        if (username.equals(user.getUsername()) && password.equals(user.getPassword())) {
            return user;
        }
    }

    throw new UserException("?");
}

From source file:edu.utah.further.core.xml.stax.XmlStreamElementPrinter.java

@Override
public void visitComment(final XMLStreamReader xmlReader) {
    if (isPrintComments()) {
        os.print("<!--");
        if (xmlReader.hasText())
            os.print(xmlReader.getText());
        os.print("-->");
    }/*from  w  w  w . j a  v  a  2 s. c om*/
}

From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.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.
 * //w w  w  .j a v a 2s. c  o m
 * @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.
 */
protected static <T extends TableEntity, R> TableResult parseEntity(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);

    res.setEtag(StringEscapeUtils.unescapeHtml4(
            xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.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)) {
                res.setId(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(readProperties(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().get(TableConstants.PARTITION_KEY);
    if (tempProp != null) {
        res.getProperties().remove(TableConstants.PARTITION_KEY);
        partitionKey = tempProp.getValueAsString();
    }

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

    tempProp = res.getProperties().get(TableConstants.TIMESTAMP);
    if (tempProp != null) {
        res.getProperties().remove(TableConstants.TIMESTAMP);
        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:edu.utah.further.core.xml.stax.XmlStreamElementPrinter.java

@Override
public void visitEntityReference(final XMLStreamReader xmlReader) {
    final String str = xmlReader.getLocalName() + "=";
    os.print(str);//from  ww w .  jav a2  s.  com
    if (xmlReader.hasText()) {
        os.print("[" + xmlReader.getText() + "]");
    }
}

From source file:com.cedarsoft.serialization.stax.mate.StaxMateSerializerTest.java

License:asdf

@Nonnull
@Override/*  ww w.  j  a  v a  2s . c  o  m*/
protected AbstractStaxMateSerializer<String> getSerializer() {
    return new AbstractStaxMateSerializer<String>("aString", "http://www.lang.java/String",
            new VersionRange(new Version(1, 5, 3), new Version(1, 5, 3))) {
        @Override
        public void serialize(@Nonnull SMOutputElement serializeTo, @Nonnull String object,
                @Nonnull Version formatVersion) throws XMLStreamException {
            assert isVersionWritable(formatVersion);
            serializeTo.addCharacters(object);
        }

        @Override
        @Nonnull
        public String deserialize(@Nonnull XMLStreamReader deserializeFrom, @Nonnull Version formatVersion)
                throws XMLStreamException {
            assert isVersionReadable(formatVersion);
            deserializeFrom.next();
            String text = deserializeFrom.getText();
            closeTag(deserializeFrom);
            return text;
        }
    };
}

From source file:Main.java

public static void dumpXML(XMLStreamReader parser) throws XMLStreamException {
    int depth = 0;
    do {//from  w ww.  j a  v a2  s . c o  m
        switch (parser.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
            for (int i = 1; i < depth; ++i) {
                System.out.print("    ");
            }
            System.out.print("<");
            System.out.print(parser.getLocalName());
            for (int i = 0; i < parser.getAttributeCount(); ++i) {
                System.out.print(" ");
                System.out.print(parser.getAttributeLocalName(i));
                System.out.print("=\"");
                System.out.print(parser.getAttributeValue(i));
                System.out.print("\"");
            }
            System.out.println(">");

            ++depth;
            break;
        case XMLStreamConstants.END_ELEMENT:
            --depth;
            for (int i = 1; i < depth; ++i) {
                System.out.print("    ");
            }
            System.out.print("</");
            System.out.print(parser.getLocalName());
            System.out.println(">");
            break;
        case XMLStreamConstants.CHARACTERS:
            for (int i = 1; i < depth; ++i) {
                System.out.print("    ");
            }

            System.out.println(parser.getText());
            break;
        }

        if (depth > 0)
            parser.next();
    } while (depth > 0);
}