Example usage for javax.xml.stream XMLStreamReader hasNext

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

Introduction

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

Prototype

public boolean hasNext() throws XMLStreamException;

Source Link

Document

Returns true if there are more parsing events and false if there are no more events.

Usage

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   w ww.  j av a  2 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.stanford.cfuller.colocalization3d.correction.Correction.java

/**
 * Reads a stored correction from disk./*from  ww  w  . j a  v  a  2s.  c o  m*/
 * 
 * @param filename                  The name of the file containing the Correction that was previously written to disk.
 * @return                          The Correction contained in the file.
 * @throws java.io.IOException      if the Correction cannot be successfully read.
 * @throws ClassNotFoundException   if the file does not contain a Correction.
 */
public static Correction readFromDisk(String filename) throws java.io.IOException, ClassNotFoundException {

    File f = new File(filename);

    FileReader fr = new FileReader(f);

    XMLStreamReader xsr = null;
    String encBinData = null;

    try {
        xsr = XMLInputFactory.newFactory().createXMLStreamReader(fr);

        while (xsr.hasNext()) {

            int event = xsr.next();

            if (event != XMLStreamReader.START_ELEMENT)
                continue;

            if (xsr.hasName() && xsr.getLocalName() == BINARY_DATA_ELEMENT) {

                encBinData = xsr.getElementText();

                break;

            }

        }
    } catch (XMLStreamException e) {
        java.util.logging.Logger.getLogger(LOG_NAME)
                .severe("Exception encountered while reading XML correction: " + e.getMessage());
    }
    byte[] binData = (new HexBinaryAdapter()).unmarshal(encBinData);

    ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(binData));

    Object o = oi.readObject();

    return (Correction) o;

}

From source file:Main.java

/**
 * /*from   w  w w.  j  a  v a2s  .  c o  m*/
 * Checks indentation (over a single line - multipline text nodes is not supported)
 * 
 * @param out
 * @param indentSize
 * @return
 * @throws Exception
 */

public static boolean isIndented(String out, int indentSize) throws Exception {
    BufferedReader reader = new BufferedReader(new StringReader(out));

    boolean indentated = false;

    int level = 0;
    int line = 0;

    String string = reader.readLine();
    while (string != null) {
        int newLevel = 0;
        while (newLevel < string.length()) {
            if (!Character.isWhitespace(string.charAt(newLevel))) {
                break;
            }
            newLevel++;
        }
        if ((newLevel % indentSize) != 0) {
            throw new IllegalArgumentException("Unexpected " + newLevel + " whitespace chars at line " + line);
        }
        if (Math.abs(level - newLevel) > indentSize) {
            throw new IllegalArgumentException("Unexpected jump from " + level + " to " + newLevel
                    + " whitespace chars at line " + line + " for indenting with " + indentSize + " chars");
        }
        level = newLevel;

        string = reader.readLine();
        line++;

        if (level > 0) {
            indentated = true;
        }
    }

    if (!indentated) {
        // see if a simple xml piece
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        XMLStreamReader parser = inputFactory.createXMLStreamReader(new StringReader(out));

        int elementMaxLevel = -1;
        int elementLevel = 0;
        do {
            int event = parser.next();
            if (event == XMLStreamConstants.START_ELEMENT) {
                elementLevel++;

                if (elementMaxLevel < elementLevel) {
                    elementMaxLevel = elementLevel;
                }
            } else if (event == XMLStreamConstants.END_ELEMENT) {
                elementLevel--;
            }
        } while (parser.hasNext());

        if (elementMaxLevel > 1) { // should be indentated
            return false;
        }
        return true;
    }

    return indentated;
}

From source file:sdmx.net.service.nomis.NOMISRESTServiceRegistry.java

public static List<NOMISGeography> parseGeography(InputStream in, String cubeId, String cubeName)
        throws XMLStreamException {
    List<NOMISGeography> geogList = new ArrayList<NOMISGeography>();
    String tagContent = null;//from   w  w  w. j  a  va  2 s .c o m
    XMLInputFactory factory = XMLInputFactory.newInstance();

    XMLStreamReader reader = factory.createXMLStreamReader(in);
    int state = 0;
    String lastLang = null;
    while (reader.hasNext()) {
        int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            if (reader.getLocalName().equals("Type")) {
                NOMISGeography geog = new NOMISGeography();
                geog.setCubeId(cubeId);
                geog.setCubeName(cubeName);
                geog.setGeography(reader.getAttributeValue("", "value"));
                geog.setGeographyName(reader.getAttributeValue("", "name"));
                geogList.add(geog);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            break;
        }
    }
    return geogList;
}

From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Reads the properties of an entity from the stream into a map of property names to
 * typed values. Reads the entity data as an AtomPub Entry Resource from the specified {@link XMLStreamReader} into
 * a map of <code>String</code> property names to {@link EntityProperty} data typed values.
 * //from  w  w  w .  j  a v a  2  s.  co  m
 * @param xmlr
 *            The <code>XMLStreamReader</code> to read the data from.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @return
 *         A <code>java.util.HashMap</code> containing a map of <code>String</code> property names to
 *         {@link EntityProperty} data typed values found in the entity data.
 * @throws XMLStreamException
 *             if an error occurs accessing the stream.
 * @throws ParseException
 *             if an error occurs converting the input to a particular data type.
 */
protected static HashMap<String, EntityProperty> readProperties(final XMLStreamReader xmlr,
        final OperationContext opContext) throws XMLStreamException, ParseException {
    int eventType = xmlr.getEventType();
    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.PROPERTIES);
    final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>();

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

        if (eventType == XMLStreamConstants.START_ELEMENT
                && xmlr.getNamespaceURI().equals(ODataConstants.DATA_SERVICES_NS)) {
            final String key = xmlr.getLocalName();
            String val = Constants.EMPTY_STRING;
            String edmType = null;

            if (xmlr.getAttributeCount() > 0) {
                edmType = xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE);
            }

            // move to chars
            eventType = xmlr.next();

            if (eventType == XMLStreamConstants.CHARACTERS) {
                val = xmlr.getText();

                // end element
                eventType = xmlr.next();
            }

            xmlr.require(XMLStreamConstants.END_ELEMENT, null, key);

            final EntityProperty newProp = new EntityProperty(val, EdmType.parse(edmType));
            properties.put(key, newProp);
        } else if (eventType == XMLStreamConstants.END_ELEMENT && xmlr.getName().toString()
                .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) {
            // End read properties
            break;
        }
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.PROPERTIES);
    return properties;
}

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  ww.j a  va  2 s . com
 * @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:net.cloudkit.enterprises.ws.SuperPassQueryTest.java

public static String parsingReceiptStatus(String responseContext) throws XMLStreamException {
    String serviceResponseCode = "-1";
    XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(responseContext));
    try {//from w ww.ja va  2  s.  c  o m
        int event = reader.getEventType();
        while (true) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                // System.out.println(reader.getName());
                if (reader.getName().toString().equals("ServiceResponseCode")) {
                    // System.out.println(reader.getElementText());
                    serviceResponseCode = reader.getElementText();
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                // System.out.println("End Element:" + r.getName());
                break;
            }
            if (!reader.hasNext())
                break;
            event = reader.next();
        }
    } finally {
        reader.close();
    }
    return serviceResponseCode;
}

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 {// w w  w. jav  a2 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:com.autonomy.aci.client.services.impl.ErrorProcessorTest.java

@Test(expected = ProcessorException.class)
public void testXMLStreamException() throws XMLStreamException, AciErrorException, ProcessorException {
    final XMLStreamReader mockXmlStreamReader = mock(XMLStreamReader.class);
    when(mockXmlStreamReader.hasNext()).thenThrow(new XMLStreamException("JUnit test exception"));

    processor.process(mockXmlStreamReader);

    fail("Should have raised a ProcessorException.");
}

From source file:StAXStreamTreeViewer.java

private void parseRestOfDocument(XMLStreamReader reader, DefaultMutableTreeNode current)
        throws XMLStreamException {

    while (reader.hasNext()) {
        int type = reader.next();
        switch (type) {
        case XMLStreamConstants.START_ELEMENT:

            DefaultMutableTreeNode element = new DefaultMutableTreeNode(reader.getLocalName());
            current.add(element);// w ww .  java 2s  .c om
            current = element;

            if (reader.getNamespaceURI() != null) {
                String prefix = reader.getPrefix();
                if (prefix == null) {
                    prefix = "[None]";
                }
                DefaultMutableTreeNode namespace = new DefaultMutableTreeNode(
                        "prefix = '" + prefix + "', URI = '" + reader.getNamespaceURI() + "'");
                current.add(namespace);
            }

            if (reader.getAttributeCount() > 0) {
                for (int i = 0; i < reader.getAttributeCount(); i++) {
                    DefaultMutableTreeNode attribute = new DefaultMutableTreeNode(
                            "Attribute (name = '" + reader.getAttributeLocalName(i) + "', value = '"
                                    + reader.getAttributeValue(i) + "')");
                    String attURI = reader.getAttributeNamespace(i);
                    if (attURI != null) {
                        String attPrefix = reader.getAttributePrefix(i);
                        if (attPrefix == null || attPrefix.equals("")) {
                            attPrefix = "[None]";
                        }
                        DefaultMutableTreeNode attNamespace = new DefaultMutableTreeNode(
                                "prefix=" + attPrefix + ",URI=" + attURI);
                        attribute.add(attNamespace);
                    }
                    current.add(attribute);
                }
            }

            break;
        case XMLStreamConstants.END_ELEMENT:
            current = (DefaultMutableTreeNode) current.getParent();
            break;
        case XMLStreamConstants.CHARACTERS:
            if (!reader.isWhiteSpace()) {
                DefaultMutableTreeNode data = new DefaultMutableTreeNode("CD:" + reader.getText());
                current.add(data);
            }
            break;
        case XMLStreamConstants.DTD:
            DefaultMutableTreeNode dtd = new DefaultMutableTreeNode("DTD:" + reader.getText());
            current.add(dtd);
            break;
        case XMLStreamConstants.SPACE:
            break;
        case XMLStreamConstants.COMMENT:
            DefaultMutableTreeNode comment = new DefaultMutableTreeNode(reader.getText());
            current.add(comment);
            break;
        default:
            System.out.println(type);
        }
    }
}