Example usage for javax.xml.stream XMLStreamReader next

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

Introduction

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

Prototype

public int next() throws XMLStreamException;

Source Link

Document

Get next parsing event - a processor may return all contiguous character data in a single chunk, or it may split it into several chunks.

Usage

From source file:org.jwebsocket.config.xml.JWebSocketConfigHandler.java

/**
 * private method that reads the list of server configs
 *
 * @param aStreamReader/*  w  w w  .  ja  va  2 s  .  c  o m*/
 *      the stream reader object
 * @return the list of server configs
 * @throws XMLStreamException
 *       if exception occurs reading xml
 */
private List<ServerConfig> handleServers(XMLStreamReader aStreamReader) throws XMLStreamException {
    List<ServerConfig> lServers = new FastList<ServerConfig>();
    while (aStreamReader.hasNext()) {
        aStreamReader.next();
        if (aStreamReader.isStartElement()) {
            String lElementName = aStreamReader.getLocalName();
            if (lElementName.equals(ELEMENT_SERVER)) {
                ServerConfig lServer = (ServerConfig) handlerContext.get(lElementName)
                        .processConfig(aStreamReader);
                lServers.add(lServer);
            }
        }
        if (aStreamReader.isEndElement()) {
            String lElementName = aStreamReader.getLocalName();
            if (lElementName.equals(ELEMENT_SERVERS)) {
                break;
            }
        }
    }
    return lServers;
}

From source file:org.jwebsocket.config.xml.JWebSocketConfigHandler.java

/**
 * private method that reads the list of engines config from the xml file
 *
 * @param aStreamReader/*  w ww  . j av  a 2  s  .c o m*/
 *      the stream reader object
 * @return the list of engine configs
 * @throws XMLStreamException
 *       if exception occurs while reading
 */
private List<LibraryConfig> handleLibraries(XMLStreamReader aStreamReader) throws XMLStreamException {
    List<LibraryConfig> lLibraries = new FastList<LibraryConfig>();
    while (aStreamReader.hasNext()) {
        aStreamReader.next();
        if (aStreamReader.isStartElement()) {
            String lElementName = aStreamReader.getLocalName();
            if (lElementName.equals(ELEMENT_LIBRARY)) {
                LibraryConfig lLibrary = (LibraryConfig) handlerContext.get(lElementName)
                        .processConfig(aStreamReader);
                lLibraries.add(lLibrary);
            }
        }
        if (aStreamReader.isEndElement()) {
            String lElementName = aStreamReader.getLocalName();
            if (lElementName.equals(ELEMENT_LIBRARIES)) {
                break;
            }
        }
    }
    return lLibraries;
}

From source file:org.jwebsocket.config.xml.JWebSocketConfigHandler.java

/**
 * private method that reads the list of engines config from the xml file
 *
 * @param aStreamReader//from   w  ww  .  ja  v a  2s  .  c  om
 *      the stream reader object
 * @return the list of engine configs
 * @throws XMLStreamException
 *       if exception occurs while reading
 */
private List<EngineConfig> handleEngines(XMLStreamReader aStreamReader) throws XMLStreamException {
    List<EngineConfig> lEngines = new FastList<EngineConfig>();
    while (aStreamReader.hasNext()) {
        aStreamReader.next();
        if (aStreamReader.isStartElement()) {
            String lElementName = aStreamReader.getLocalName();
            if (lElementName.equals(ELEMENT_ENGINE)) {
                EngineConfig lEngine = (EngineConfig) handlerContext.get(lElementName)
                        .processConfig(aStreamReader);
                lEngines.add(lEngine);
            }
        }
        if (aStreamReader.isEndElement()) {
            String lElementName = aStreamReader.getLocalName();
            if (lElementName.equals(ELEMENT_ENGINES)) {
                break;
            }
        }
    }
    return lEngines;
}

From source file:org.jwebsocket.config.xml.JWebSocketConfigHandler.java

/**
 * Read the map of plug-in specific settings
 * @param aStreamReader// w  w  w . j a v a 2 s  .c o m
 *        the stream reader object
 * @return the list of domains for the engine
 * @throws XMLStreamException
 *         in case of stream exception
 */
public static Map<String, Object> getSettings(XMLStreamReader aStreamReader) throws XMLStreamException {

    Map<String, Object> lSettings = new FastMap<String, Object>();
    while (aStreamReader.hasNext()) {
        aStreamReader.next();
        if (aStreamReader.isStartElement()) {
            String lElementName = aStreamReader.getLocalName();
            if (lElementName.equals(SETTING)) {
                String lKey = aStreamReader.getAttributeValue(null, "key");
                String lType = aStreamReader.getAttributeValue(null, "type");

                aStreamReader.next();
                String lValue = aStreamReader.getText();

                if (lKey != null && lValue != null) {
                    if ("json".equalsIgnoreCase(lType)) {
                        JSONObject lJSON = null;
                        try {
                            lJSON = new JSONObject(lValue);
                        } catch (JSONException lEx) {
                            // TODO: handle invalid JSON code in settings properly!
                        }
                        lSettings.put(lKey, lJSON);
                    } else {
                        lSettings.put(lKey, lValue);
                    }
                }
            }
        }

        if (aStreamReader.isEndElement()) {
            String lElementName = aStreamReader.getLocalName();
            if (lElementName.equals(SETTINGS)) {
                break;
            }
        }
    }

    return lSettings;
}

From source file:org.maodian.flyingcat.xmpp.state.SASLCommandTest.java

@Test
public void testPlainMechanismSuccess() throws Exception {
    String inXML = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>AGp1bGlldAByMG0zMG15cjBtMzA=</auth>";

    Writer writer = new StringWriter();
    XMLStreamReader xmlsr1 = newXMLStreamReader(new StringReader(inXML));
    XMLStreamWriter xmlsw = newXMLStreamWriter(writer);
    // skipt start document
    xmlsr1.nextTag();/* ww  w . j a v a  2  s .  co  m*/
    State state = cmd.execute(xmlsr1, xmlsw);

    Reader reader = new StringReader(writer.toString());
    XMLStreamReader xmlsr = XMLInputFactoryHolder.getXMLInputFactory().createXMLStreamReader(reader);

    xmlsr.next();
    QName qname = new QName(XmppNamespace.SASL, "success");
    assertEquals(qname, xmlsr.getName());
    assertTrue(state instanceof AuthenticatedStreamState);
}

From source file:org.modeldriven.fuml.xmi.stream.StreamReader.java

@SuppressWarnings("unchecked")
public Collection read(InputStream stream) {
    List<Object> results = new ArrayList<Object>();
    InputStream source = stream;//from w  w w. jav  a2s  .c  o m
    StreamContext context = null;

    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();

        factory.setXMLResolver(new XMLResolver() {

            @Override
            public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace)
                    throws XMLStreamException {
                // TODO Auto-generated method stub
                return null;
            }

        });

        /*
        XStream xstream = new XStream(new StaxDriver() {
           protected XMLStreamReader createParser(Reader xml) throws
           XMLStreamException {
           return getInputFactory().createXMLStreamReader(xml);
           }
           protected XMLStreamReader createParser(InputStream xml) throws
           XMLStreamException {
           return getInputFactory().createXMLStreamReader(xml);
           }
           });
        */

        //factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES,Boolean.FALSE);
        //factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,Boolean.TRUE);
        //set the IS_COALESCING property to true , if application desires to
        //get whole text data as one event.            
        //factory.setProperty(XMLInputFactory.IS_COALESCING , Boolean.TRUE);

        factory.setEventAllocator(new EventAllocator());

        allocator = factory.getEventAllocator();
        XMLStreamReader streamReader = factory.createXMLStreamReader(stream);

        int eventType = streamReader.getEventType();
        StreamNode node = null;
        StreamNode parent = null;
        int level = 0;
        int ignoredNodeLevel = -1;

        while (streamReader.hasNext()) {
            eventType = streamReader.next();
            //if (log.isDebugEnabled())
            //    log.debug(this.getEventTypeString(eventType));

            switch (eventType) {
            case XMLEvent.START_ELEMENT:
                level++;
                if (ignoredNodeLevel >= 0)
                    break;

                XMLEvent event = allocateXMLEvent(streamReader);
                if (level == 1) {
                    if (context != null)
                        throw new XmiException("existing context unexpected");
                    context = new StreamContext(event);
                }

                // debugging
                if (event.toString().contains("plasma:PlasmaType")) {
                    int foo = 1;
                    foo++;
                }

                node = new StreamNode(event, context);
                if (node.isIgnored()) {
                    if (log.isDebugEnabled()) {
                        Location loc = event.getLocation();
                        String msg = "start ignoring elements - level:  " + String.valueOf(level)
                                + " - line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber() + "] - ";
                        log.debug(msg);
                    }
                    ignoredNodeLevel = level;
                    break;
                }

                logEventInfo(event);
                parent = null;
                if (nodes.size() > 0) {
                    parent = nodes.peek();
                    parent.add(node);
                    node.setParent(parent);
                    if (isRootNode(node, context))
                        results.add(node);
                } else {
                    if (isRootNode(node, context))
                        results.add(node);
                }

                nodes.push(node);
                fireStreamNodeCreated(node, parent);
                break;
            case XMLEvent.END_ELEMENT:
                if (ignoredNodeLevel >= 0) {
                    if (ignoredNodeLevel == level) {
                        if (log.isDebugEnabled()) {
                            event = allocateXMLEvent(streamReader);
                            Location loc = event.getLocation();
                            String msg = "end ignoring elements - level:  " + String.valueOf(level)
                                    + " - line:col[" + loc.getLineNumber() + ":" + loc.getColumnNumber()
                                    + "] - ";
                            log.debug(msg);
                        }
                        ignoredNodeLevel = -1;
                    }
                    level--;
                    break;
                }

                level--;
                node = nodes.pop();
                parent = null;
                if (nodes.size() > 0)
                    parent = nodes.peek();
                fireStreamNodeCompleted(node, parent);
                break;
            case XMLEvent.CHARACTERS:
                if (ignoredNodeLevel >= 0)
                    break;
                node = nodes.peek();
                event = allocateXMLEvent(streamReader);
                String data = event.asCharacters().getData();
                if (data != null) {
                    data = data.trim();
                    if (data.length() > 0) {
                        if (log.isDebugEnabled())
                            log.debug("CHARACTERS: '" + data + "'");
                        if (data.length() > 0) {
                            node = nodes.peek();
                            node.addCharactersEvent(event);
                        }
                    }
                }
                break;
            default:
                if (log.isDebugEnabled()) {
                    event = allocateXMLEvent(streamReader);
                    logEventInfo(event);
                }
                break;
            }
        }
        if (results.size() > 1)
            throw new XmiException("found multiple root nodes (" + results.size() + ")");
    } catch (XMLStreamException e) {
        throw new XmiException(e);
    } finally {
        try {
            source.close();
        } catch (IOException e) {
        }
    }

    return results;
}

From source file:org.mule.module.xml.util.XMLUtils.java

public static void copy(XMLStreamReader reader, XMLStreamWriter writer, boolean fragment)
        throws XMLStreamException {
    // number of elements read in
    int read = 0;
    int event = reader.getEventType();

    while (reader.hasNext()) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            read++;/*from www.  j  ava 2  s . c  o m*/
            writeStartElement(reader, writer);
            break;
        case XMLStreamConstants.END_ELEMENT:
            writer.writeEndElement();
            read--;
            if (read <= 0 && !fragment) {
                return;
            }
            break;
        case XMLStreamConstants.CHARACTERS:
            writer.writeCharacters(reader.getText());
            break;
        case XMLStreamConstants.START_DOCUMENT:
        case XMLStreamConstants.END_DOCUMENT:
        case XMLStreamConstants.ATTRIBUTE:
        case XMLStreamConstants.NAMESPACE:
            break;
        default:
            break;
        }
        event = reader.next();
    }
}

From source file:org.mule.modules.jive.api.xml.XmlMapper.java

/**Maps an xml from a {@link Reader} to a {@link Map}.
 * @param reader The {@link Reader} with the xml data
 * @return The map with the entity data// ww w.  j a v a 2  s .  c  o  m
 * */
@SuppressWarnings("unchecked")
public final Map<String, Object> xml2map(final Reader reader) {
    final Map<String, Object> ret = new HashMap<String, Object>();
    final Stack<Map<String, Object>> maps = new Stack<Map<String, Object>>();
    Map<String, Object> current = ret;

    try {
        final XMLStreamReader r = xmlInputFactory.createXMLStreamReader(reader);
        StringBuilder lastText = new StringBuilder();
        String currentElement = null;
        int returnCount = 0;
        while (r.hasNext()) {
            final int eventType = r.next();
            if (eventType == CHARACTERS || eventType == CDATA || eventType == SPACE
                    || eventType == ENTITY_REFERENCE) {
                lastText.append(r.getText());
            } else if (eventType == END_DOCUMENT) {
                break;
            } else if (eventType == START_ELEMENT) {
                if (currentElement != null) {
                    maps.push(current);
                    final Map<String, Object> map = new HashMap<String, Object>();
                    if (StringUtils.startsWith(currentElement, "return")) {
                        currentElement = currentElement + "--" + String.valueOf(returnCount);
                        returnCount++;
                    }
                    current.put(currentElement, map);
                    current = map;
                }
                currentElement = r.getLocalName();
            } else if (eventType == END_ELEMENT) {
                if (currentElement == null) {
                    current = maps.pop();
                } else {
                    current.put(currentElement, lastText.toString().trim());
                    currentElement = null;
                    lastText = new StringBuilder();
                }
            } else {
                throw new XMLStreamException("Unexpected event type " + eventType);
            }
        }

        final Object obj = ret.get(ret.keySet().iterator().next());
        if (obj instanceof String) {
            Map<String, Object> responseTag = new HashMap<String, Object>();
            responseTag.put("response", ret.keySet().iterator().next().toString());
            return responseTag;
        } else {
            final Map<String, Object> returnXMLElement = (Map<String, Object>) ret
                    .get(ret.keySet().iterator().next());

            if (returnXMLElement.keySet().contains("return--1")) {
                return returnXMLElement;
            }
            return (Map<String, Object>) returnXMLElement.get("return--0");
        }

    } catch (XMLStreamException e) {
        throw new UnhandledException(e);
    }
}

From source file:org.mule.transport.sap.transformer.XmlToJcoFunctionTransformer.java

public JCoFunction transform(InputStream stream, String encoding) throws XMLStreamException {

    XMLStreamReader reader = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    String functionName = null;/*  w  w w  .  j  av a2 s  .c  om*/
    String tableName = null;
    String structureName = null;
    String rowId = null;
    String fieldName = null;
    String value = null;

    JCoFunction function = null;

    try {
        reader = factory.createXMLStreamReader(stream);
        String localName = null;
        while (reader.hasNext()) {
            int eventType = reader.next();

            if (eventType == XMLStreamReader.START_DOCUMENT) {
                // find START_DOCUMENT

            } else if (eventType == XMLStreamReader.START_ELEMENT) {
                // find START_ELEMENT
                localName = reader.getLocalName();

                logger.debug("START ELEMENT IS FOUND");
                logger.debug("start localName = " + localName);

                if (localName.equals(MessageConstants.JCO)) {
                    functionName = getAttributeValue(MessageConstants.JCO_ATTR_NAME, reader);

                    try {
                        function = this.connector.getAdapter().getFunction(functionName);
                    } catch (JCoException e) {
                        throw new XMLStreamException(e);
                    }
                    logger.debug("function name:" + functionName);

                } else if (functionName != null) {
                    if (localName.equals(MessageConstants.IMPORT)) {
                        //recordType = IMPORT;

                        push(function.getImportParameterList());
                    } else if (localName.equals(MessageConstants.EXPORT)) {
                        //recordType = EXPORT;

                        push(function.getExportParameterList());
                    } else if (localName.equals(MessageConstants.TABLES)) {
                        //recordType = TABLES;
                        tableName = null;
                        push(function.getTableParameterList());

                    } else if (localName.equals(MessageConstants.TABLE)) {
                        if (tableName != null) {
                            pop();
                        }
                        tableName = getAttributeValue(MessageConstants.TABLE_ATTR_NAME, reader);

                        logger.debug("tableName = " + tableName);
                        push(this.record.getTable(tableName));
                    } else if (localName.equals(MessageConstants.STRUCTURE)) {
                        structureName = getAttributeValue(MessageConstants.STRUCTURE_ATTR_NAME, reader);
                        push(this.record.getStructure(structureName));
                    } else if (localName.equals(MessageConstants.ROW)) {
                        rowId = getAttributeValue(MessageConstants.ROW_ATTR_ID, reader);
                        logger.debug("rowId = " + rowId);
                        if (this.record instanceof JCoTable) {
                            ((JCoTable) this.record).appendRow();
                        }
                    } else if (localName.equals(MessageConstants.FIELD)) {
                        fieldName = getAttributeValue(MessageConstants.STRUCTURE_ATTR_NAME, reader);
                        value = reader.getElementText().trim(); // get an element value
                        logger.debug("FieldName = " + fieldName);
                        logger.debug("value = " + value);

                        this.record.setValue(fieldName, value);

                    }
                }

            } else if (eventType == XMLStreamReader.END_DOCUMENT) {

                // find END_DOCUMENT
                logger.debug("END DOCUMENT IS FOUND");
            } else if (eventType == XMLStreamReader.END_ELEMENT) {
                logger.debug("END ELEMENT IS FOUND");
                logger.debug("end localName = " + localName);
                // find END_ELEMENT
                if (localName.equals(MessageConstants.IMPORT) || localName.equals(MessageConstants.EXPORT)
                        || localName.equals(MessageConstants.TABLES) || localName.equals(MessageConstants.TABLE)
                        || localName.equals(MessageConstants.STRUCTURE)) {
                    pop();
                }
            }
        }
    } catch (Exception e) {
        logger.fatal(e);
        throw new TransformerException(this, e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (XMLStreamException ex) {
            }
        }
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException ex) {
            }
        }
        logger.debug("\n" + function.getImportParameterList().toXML());
        logger.debug("\n" + function.getExportParameterList().toXML());
        logger.debug("\n" + function.getTableParameterList().toXML());

        return function;
    }
}

From source file:org.neo4j.gis.spatial.osm.OSMImporter.java

public void importFile(OSMWriter<?> osmWriter, String dataset, boolean allPoints, Charset charset)
        throws IOException, XMLStreamException {
    System.out.println("Importing with osm-writer: " + osmWriter);
    osmWriter.getOrCreateOSMDataset(layerName);
    osm_dataset = osmWriter.getDatasetId();

    long startTime = System.currentTimeMillis();
    long[] times = new long[] { 0L, 0L, 0L, 0L };
    javax.xml.stream.XMLInputFactory factory = javax.xml.stream.XMLInputFactory.newInstance();
    CountedFileReader reader = new CountedFileReader(dataset, charset);
    javax.xml.stream.XMLStreamReader parser = factory.createXMLStreamReader(reader);
    int countXMLTags = 0;
    beginProgressMonitor(100);// w w w .  j  a  v  a2s.  c  o  m
    setLogContext(dataset);
    boolean startedWays = false;
    boolean startedRelations = false;
    try {
        ArrayList<String> currentXMLTags = new ArrayList<String>();
        int depth = 0;
        Map<String, Object> wayProperties = null;
        ArrayList<Long> wayNodes = new ArrayList<Long>();
        Map<String, Object> relationProperties = null;
        ArrayList<Map<String, Object>> relationMembers = new ArrayList<Map<String, Object>>();
        LinkedHashMap<String, Object> currentNodeTags = new LinkedHashMap<String, Object>();
        while (true) {
            updateProgressMonitor(reader.getPercentRead());
            incrLogContext();
            int event = parser.next();
            if (event == javax.xml.stream.XMLStreamConstants.END_DOCUMENT) {
                break;
            }
            switch (event) {
            case javax.xml.stream.XMLStreamConstants.START_ELEMENT:
                currentXMLTags.add(depth, parser.getLocalName());
                String tagPath = currentXMLTags.toString();
                if (tagPath.equals("[osm]")) {
                    osmWriter.setDatasetProperties(extractProperties(parser));
                } else if (tagPath.equals("[osm, bounds]")) {
                    osmWriter.addOSMBBox(extractProperties("bbox", parser));
                } else if (tagPath.equals("[osm, node]")) {
                    // <node id="269682538" lat="56.0420950"
                    // lon="12.9693483" user="sanna" uid="31450"
                    // visible="true" version="1" changeset="133823"
                    // timestamp="2008-06-11T12:36:28Z"/>
                    osmWriter.createOSMNode(extractProperties("node", parser));
                } else if (tagPath.equals("[osm, way]")) {
                    // <way id="27359054" user="spull" uid="61533"
                    // visible="true" version="8" changeset="4707351"
                    // timestamp="2010-05-15T15:39:57Z">
                    if (!startedWays) {
                        startedWays = true;
                        times[0] = System.currentTimeMillis();
                        osmWriter.optimize();
                        times[1] = System.currentTimeMillis();
                    }
                    wayProperties = extractProperties("way", parser);
                    wayNodes.clear();
                } else if (tagPath.equals("[osm, way, nd]")) {
                    Map<String, Object> properties = extractProperties(parser);
                    wayNodes.add(Long.parseLong(properties.get("ref").toString()));
                } else if (tagPath.endsWith("tag]")) {
                    Map<String, Object> properties = extractProperties(parser);
                    currentNodeTags.put(properties.get("k").toString(), properties.get("v").toString());
                } else if (tagPath.equals("[osm, relation]")) {
                    // <relation id="77965" user="Grillo" uid="13957"
                    // visible="true" version="24" changeset="5465617"
                    // timestamp="2010-08-11T19:25:46Z">
                    if (!startedRelations) {
                        startedRelations = true;
                        times[2] = System.currentTimeMillis();
                        osmWriter.optimize();
                        times[3] = System.currentTimeMillis();
                    }
                    relationProperties = extractProperties("relation", parser);
                    relationMembers.clear();
                } else if (tagPath.equals("[osm, relation, member]")) {
                    relationMembers.add(extractProperties(parser));
                }
                if (startedRelations) {
                    if (countXMLTags < 10) {
                        log("Starting tag at depth " + depth + ": " + currentXMLTags.get(depth) + " - "
                                + currentXMLTags.toString());
                        for (int i = 0; i < parser.getAttributeCount(); i++) {
                            log("\t" + currentXMLTags.toString() + ": " + parser.getAttributeLocalName(i) + "["
                                    + parser.getAttributeNamespace(i) + "," + parser.getAttributePrefix(i) + ","
                                    + parser.getAttributeType(i) + "," + "] = " + parser.getAttributeValue(i));
                        }
                    }
                    countXMLTags++;
                }
                depth++;
                break;
            case javax.xml.stream.XMLStreamConstants.END_ELEMENT:
                if (currentXMLTags.toString().equals("[osm, node]")) {
                    osmWriter.addOSMNodeTags(allPoints, currentNodeTags);
                } else if (currentXMLTags.toString().equals("[osm, way]")) {
                    osmWriter.createOSMWay(wayProperties, wayNodes, currentNodeTags);
                } else if (currentXMLTags.toString().equals("[osm, relation]")) {
                    osmWriter.createOSMRelation(relationProperties, relationMembers, currentNodeTags);
                }
                depth--;
                currentXMLTags.remove(depth);
                // log("Ending tag at depth "+depth+": "+currentTags.get(depth));
                break;
            default:
                break;
            }
        }
    } finally {
        endProgressMonitor();
        parser.close();
        osmWriter.finish();
        this.osm_dataset = osmWriter.getDatasetId();
    }
    describeTimes(startTime, times);
    osmWriter.describeMissing();
    osmWriter.describeLoaded();

    long stopTime = System.currentTimeMillis();
    log("info | Elapsed time in seconds: " + (1.0 * (stopTime - startTime) / 1000.0));
    stats.dumpGeomStats();
    stats.printTagStats();
}