Example usage for javax.xml.stream XMLEventReader hasNext

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

Introduction

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

Prototype

@Override
public boolean hasNext();

Source Link

Document

Check if there are more events.

Usage

From source file:org.jwifisd.eyefi.Main.java

private static void getPhotoStatus(Request request, Response response, final String date)
        throws FactoryConfigurationError, XMLStreamException, IOException {
    String macaddress = null;//w  w w.  j  a  v a 2  s . com
    String credential = null;
    String filename = null;
    String filesize = null;
    String filesignature = null;
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader eventReader = inputFactory.createXMLEventReader(request.getInputStream());
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        if (event.isStartElement()) {
            if (event.asStartElement().getName().getLocalPart().equals("macaddress")) {
                event = eventReader.nextEvent();
                macaddress = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("credential")) {
                event = eventReader.nextEvent();
                credential = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("filename")) {
                event = eventReader.nextEvent();
                filename = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("filesize")) {
                event = eventReader.nextEvent();
                filesize = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("filesignature")) {
                event = eventReader.nextEvent();
                filesignature = event.asCharacters().getData();
                continue;
            }
        }
    }
    System.out.println("macaddress:" + macaddress);
    System.out.println("credential:" + credential);
    System.out.println("filename:" + filename);
    System.out.println("filesize:" + filesize);
    System.out.println("filesignature:" + filesignature);

    response.setHeader("Server", "Eye-Fi Agent/2.0.4.0");
    response.setHeader("Date", date);
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Content-Type", "text/xml; charset=\"utf-8\"");

    String responseText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //
            "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" + //
            /**/"<SOAP-ENV:Body>\n" + //
            /*  */"<GetPhotoStatusResponse xmlns=\"http://localhost/api/soap/eyefilm\">" + //
            /*    */"<fileid>1</fileid><offset>0</offset>" + //
            /*  */"</GetPhotoStatusResponse>" + //
            /**/"</SOAP-ENV:Body>" + //
            "</SOAP-ENV:Envelope>";

    response.setContentLength(responseText.length());
    response.getWriter().write(responseText);
}

From source file:org.jwifisd.eyefi.Main.java

private static void startSession(Request request, Response response, final String date)
        throws Exception, IOException {
    String macaddress = null;/*w  w w .ja  v  a  2s. co m*/
    String cnonce = null;
    String transfermode = null;
    String transfermodetimestamp = null;
    System.out.println("connectx");
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader eventReader = inputFactory.createXMLEventReader(request.getInputStream());
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();
        if (event.isStartElement()) {
            if (event.asStartElement().getName().getLocalPart().equals("macaddress")) {
                event = eventReader.nextEvent();
                macaddress = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("cnonce")) {
                event = eventReader.nextEvent();
                cnonce = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("transfermode")) {
                event = eventReader.nextEvent();
                transfermode = event.asCharacters().getData();
                continue;
            }
            if (event.asStartElement().getName().getLocalPart().equals("transfermodetimestamp")) {
                event = eventReader.nextEvent();
                transfermodetimestamp = event.asCharacters().getData();
                continue;
            }
        }
    }
    System.out.println("macaddress:" + macaddress);
    System.out.println("cnonce:" + cnonce);
    System.out.println("transfermode:" + transfermode);
    System.out.println("transfermodetimestamp:" + transfermodetimestamp);
    byte[] cnonceBytes = Hex.decodeHex(cnonce.toCharArray());
    byte[] uploadKey = Hex.decodeHex("00000000000000000000000000000000".toCharArray());
    byte[] credential = md5(Hex.decodeHex(macaddress.toCharArray()), cnonceBytes, uploadKey);
    String credentialStr = Hex.encodeHexString(credential);

    response.setHeader("Server", "Eye-Fi Agent/2.0.4.0");
    response.setHeader("Date", date);
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Content-Type", "text/xml; charset=\"utf-8\"");

    String responseText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + //
            "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\">" + //
            /**/"<SOAP-ENV:Body>" + //
            /*  */"<StartSessionResponse xmlns=\"http://localhost/api/soap/eyefilm\">" + //
            /*    */"<credential>" + credentialStr + "</credential>" + //
            /*    */"<snonce>" + cnonce + "</snonce>" + //
            /*    */"<transfermode>2</transfermode>" + //
            /*    */"<transfermodetimestamp>1230268824</transfermodetimestamp>" + //
            /*    */"<upsyncallowed>false</upsyncallowed>" + //
            /*  */"</StartSessionResponse>" + //
            /**/"</SOAP-ENV:Body>" + //
            "</SOAP-ENV:Envelope>";
    System.out.println(responseText);
    response.setContentLength(responseText.length());
    response.getWriter().write(responseText);
}

From source file:org.omnaest.utils.xml.XMLNestedMapConverter.java

/**
 * Template method for {@link #newNamespaceAwareMapFromXML(CharSequence)} and {@link #newMapFromXML(CharSequence)} which allows
 * to convert the {@link QName} based key values to other representations.
 * //from  ww w.  j a  va 2s  .  com
 * @param xmlContent
 * @return new (nested) {@link Map} instance
 */
protected <K> Map<K, Object> newMapFromXML(CharSequence xmlContent,
        final ElementConverter<QName, K> keyElementConverter) {
    //
    final Map<K, Object> retmap = new LinkedHashMap<K, Object>();

    //
    Assert.isNotNull(keyElementConverter, "keyElementConverter must not be null");

    //
    final ExceptionHandler exceptionHandler = this.exceptionHandler;

    //    
    try {
        //
        final XMLInputFactory xmlInputFactory = this.xmlInstanceContextFactory.newXmlInputFactory();
        Assert.isNotNull(xmlInputFactory, "xmlInputFactory must not be null");

        //
        final Reader reader = new CharSequenceReader(xmlContent);
        final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(reader);

        //
        final class Helper {
            /* ********************************************** Variables ********************************************** */
            private List<TupleTwo<QName, Object>> stackList = new ArrayList<TupleTwo<QName, Object>>();

            /* ********************************************** Methods ********************************************** */

            /**
             * Manifests a single tag node recursively
             * 
             * @return
             * @throws XMLStreamException
             */
            @SuppressWarnings("unchecked")
            public TupleTwo<QName, Object> manifest() throws XMLStreamException {
                //
                TupleTwo<QName, Object> retval = null;

                //          
                while (xmlEventReader.hasNext()) {
                    //
                    final XMLEvent xmlEvent = xmlEventReader.nextEvent();

                    //
                    if (xmlEvent.isStartElement()) {
                        //
                        final StartElement startElement = xmlEvent.asStartElement();
                        final QName name = startElement.getName();

                        //
                        this.addNewStackElement().setValueFirst(name);

                        //
                        final Iterator<Attribute> attributeIterator = startElement.getAttributes();
                        if (attributeIterator.hasNext()) {
                            //
                            final Map<QName, Object> map = new LinkedHashMap<QName, Object>();
                            for (Attribute attribute : IterableUtils.valueOf(attributeIterator)) {
                                map.put(attribute.getName(), attribute.getValue());
                            }

                            //
                            this.updateCurrentStackValue(map);
                        }
                    } else if (xmlEvent.isEndElement()) {
                        //
                        retval = this.removeStackElement();

                        //
                        final Object manifestation = retval.getValueSecond();
                        final QName tagname = retval.getValueFirst();

                        //
                        updateCurrentStackValue(manifestation, tagname);
                    } else if (xmlEvent.isCharacters()) {
                        //
                        final Characters characters = xmlEvent.asCharacters();
                        if (!characters.isWhiteSpace()) {
                            //
                            final TupleTwo<QName, Object> currentStackValue = this.getCurrentStackValue();
                            currentStackValue.setValueSecond(
                                    ObjectUtils.defaultIfNull(currentStackValue.getValueSecond(), "")
                                            + characters.getData());

                        }
                    }

                }

                //
                return retval;
            }

            /**
             * Updates the current stack value
             * 
             * @param manifestation
             * @param tagname
             */
            private void updateCurrentStackValue(Object manifestation, QName tagname) {
                //
                final Map<QName, Object> tagNameToManifestationMap = new LinkedHashMap<QName, Object>();
                tagNameToManifestationMap.put(tagname, manifestation);
                this.updateCurrentStackValue(tagNameToManifestationMap);
            }

            @SuppressWarnings("unchecked")
            private void updateCurrentStackValue(Map<QName, Object> tagNameToManifestationMap) {
                //
                final TupleTwo<QName, Object> currentStackValue = this.getCurrentStackValue();

                //
                if (currentStackValue != null) {
                    //
                    Map<K, Object> map = null;
                    {
                        //
                        final Object valueSecond = currentStackValue.getValueSecond();
                        if (valueSecond instanceof Map) {
                            map = (Map<K, Object>) valueSecond;
                        } else {
                            //
                            map = new LinkedHashMap<K, Object>();
                            if (valueSecond instanceof String) {
                                map.put(keyElementConverter.convert(new QName("")), valueSecond);
                            }
                        }
                    }

                    //
                    for (Entry<QName, Object> tagNameToManifestationEntry : tagNameToManifestationMap
                            .entrySet()) {
                        //
                        final K tagname = keyElementConverter.convert(tagNameToManifestationEntry.getKey());
                        final Object manifestation = tagNameToManifestationEntry.getValue();

                        //
                        if (!map.containsKey(tagname)) {
                            map.put(tagname, manifestation);
                        } else {
                            //
                            final Object object = map.get(tagname);
                            if (object instanceof List) {
                                //
                                final List<Object> list = (List<Object>) object;
                                list.add(manifestation);
                            } else {
                                //
                                final List<Object> list = new ArrayList<Object>();
                                list.add(object);
                                list.add(manifestation);
                                map.put(tagname, list);
                            }
                        }
                    }

                    //
                    currentStackValue.setValueSecond(map);
                }
            }

            private TupleTwo<QName, Object> getCurrentStackValue() {
                return ListUtils.firstElement(this.stackList);
            }

            private TupleTwo<QName, Object> removeStackElement() {
                return ListUtils.removeFirst(this.stackList);
            }

            private TupleTwo<QName, Object> addNewStackElement() {
                //
                final TupleTwo<QName, Object> retval = new TupleTwo<QName, Object>();
                this.stackList.add(0, retval);
                return retval;
            }
        }

        //  
        try {
            final Helper helper = new Helper();
            final TupleTwo<QName, Object> result = helper.manifest();
            retmap.put(keyElementConverter.convert(result.getValueFirst()), result.getValueSecond());
        } catch (Exception e) {
            if (exceptionHandler != null) {
                exceptionHandler.handleException(e);
            }
        }

        //
        xmlEventReader.close();
        reader.close();

    } catch (Exception e) {
        if (exceptionHandler != null) {
            exceptionHandler.handleException(e);
        }
    }

    //
    return retmap;
}

From source file:org.openhab.binding.dwdunwetter.internal.data.DwdWarningsData.java

/**
 * Refreshes the Warnings Data/*from  ww  w.j  av a  2 s .co  m*/
 */
public boolean refresh() {
    String rawData = dataAccessCached.getValue();
    if (StringUtils.isEmpty(rawData)) {
        logger.debug("No Data from Endpoint");
        return false;
    }

    cityData.clear();

    try {
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        XMLStreamReader reader = inputFactory.createXMLStreamReader(new StringReader(rawData));
        XMLEventReader eventReader = inputFactory.createXMLEventReader(reader);
        DwdWarningData gemeindeData = new DwdWarningData();
        boolean insideGemeinde = false;
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (!insideGemeinde && event.isStartElement()) {
                DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asStartElement().getName().getLocalPart());
                switch (xmlTag) {
                case WARNUNGEN_GEMEINDEN:
                    gemeindeData = new DwdWarningData();
                    insideGemeinde = true;
                    break;
                default:
                    break;
                }
            } else if (insideGemeinde && event.isStartElement()) {
                DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asStartElement().getName().getLocalPart());
                switch (xmlTag) {
                case SEVERITY:
                    gemeindeData.setSeverity(Severity.getSeverity(getValue(eventReader)));
                    break;
                case DESCRIPTION:
                    gemeindeData.setDescription(getValue(eventReader));
                    break;
                case EFFECTIVE:
                    gemeindeData.setEffective(getTimestampValue(eventReader));
                    break;
                case EXPIRES:
                    gemeindeData.setExpires(getTimestampValue(eventReader));
                    break;
                case EVENT:
                    gemeindeData.setEvent(getValue(eventReader));
                    break;
                case STATUS:
                    gemeindeData.setStatus(getValue(eventReader));
                    break;
                case MSGTYPE:
                    gemeindeData.setMsgType(getValue(eventReader));
                    break;
                case HEADLINE:
                    gemeindeData.setHeadline(getValue(eventReader));
                    break;
                case ONSET:
                    gemeindeData.setOnset(getTimestampValue(eventReader));
                    break;
                case ALTITUDE:
                    gemeindeData.setAltitude(getBigDecimalValue(eventReader));
                    break;
                case CEILING:
                    gemeindeData.setCeiling(getBigDecimalValue(eventReader));
                    break;
                case IDENTIFIER:
                    gemeindeData.setId(getValue(eventReader));
                    break;
                case INSTRUCTION:
                    gemeindeData.setInstruction(getValue(eventReader));
                    break;
                case URGENCY:
                    gemeindeData.setUrgency(Urgency.getUrgency(getValue(eventReader)));
                    break;
                default:
                    break;
                }
            } else if (insideGemeinde && event.isEndElement()) {
                DwdXmlTag xmlTag = DwdXmlTag.getDwdXmlTag(event.asEndElement().getName().getLocalPart());
                switch (xmlTag) {
                case WARNUNGEN_GEMEINDEN:
                    if (!gemeindeData.isTest() && !gemeindeData.isCancel()) {
                        cityData.add(gemeindeData);
                    }
                    insideGemeinde = false;
                    break;
                default:
                    break;
                }
            }
        }
    } catch (XMLStreamException e) {
        logger.debug("Exception while parsing the XML Response", e);
        return false;
    }
    Collections.sort(cityData, new SeverityComparator());
    return true;
}

From source file:org.openhim.mediator.denormalization.EnrichRegistryStoredQueryActor.java

private String enrichStoredQueryXML(Identifier id, InputStream xml) throws XMLStreamException {
    XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(xml);
    StringWriter output = new StringWriter();
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
    XMLEventFactory eventFactory = XMLEventFactory.newFactory();

    String curSlot = null;//from  w  ww  . j  a  v a2 s. c o  m
    boolean patientIdSlot = false;

    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();

        if (event.getEventType() == XMLEvent.START_ELEMENT) {
            StartElement elem = event.asStartElement();
            if ("Slot".equals(elem.getName().getLocalPart())) {
                curSlot = elem.getAttributeByName(new QName("name")).getValue();
            } else if ("Value".equals(elem.getName().getLocalPart())
                    && ParseRegistryStoredQueryActor.PATIENT_ID_SLOT_TYPE.equals(curSlot)) {
                patientIdSlot = true;
                writer.add(event);
            }
        } else if (event.getEventType() == XMLEvent.END_ELEMENT) {
            EndElement elem = event.asEndElement();
            if (patientIdSlot && "Value".equals(elem.getName().getLocalPart())) {
                XMLEvent ecidEvent = eventFactory.createCharacters("'" + id.toString() + "'");
                writer.add(ecidEvent);
                patientIdSlot = false;
            }
        }

        if (!patientIdSlot) {
            writer.add(event);
        }
    }

    writer.close();
    return output.toString();
}

From source file:org.openhim.mediator.enrichers.IdentityEnricher.java

public String enrich(String xml) throws XMLStreamException {
    InputStream in = IOUtils.toInputStream(xml);
    XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(in);
    StringWriter output = new StringWriter();
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);

    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        processXMLEvent(writer, event);// w w  w .ja  v  a2s  .co m
    }

    writer.close();
    return output.toString();
}

From source file:org.qi4j.valueserialization.stax.StaxValueDeserializer.java

@Override
protected Object readPlainValue(XMLEventReader input) throws Exception {
    if (!input.hasNext()) {
        return null;
    }//w  ww .ja v  a 2  s  .c  om
    XMLEvent nextEvent = input.nextEvent();
    if (nextEvent.getEventType() == XMLEvent.START_ELEMENT
            && "null".equals(nextEvent.asStartElement().getName().getLocalPart())) {
        input.nextTag();
        return null;
    }
    if (nextEvent.getEventType() != XMLEvent.CHARACTERS) {
        throw new ValueSerializationException("Expected characters but got: " + nextEvent);
    }
    String stringValue = nextEvent.asCharacters().getData();
    return detectAndConvertStringValue(stringValue);
}

From source file:org.qi4j.valueserialization.stax.StaxValueDeserializer.java

@Override
protected <T> Collection<T> readArrayInCollection(XMLEventReader input,
        Function<XMLEventReader, T> deserializer, Collection<T> collection) throws Exception {
    if (!input.hasNext()) {
        return null;
    }/*from  ww w  .  j a va  2s.c o  m*/
    XMLEvent nextTag = input.nextTag();
    if (nextTag.isStartElement() && "null".equals(nextTag.asStartElement().getName().getLocalPart())) {
        input.nextTag();
        return null;
    }
    if (!nextTag.isStartElement() || !"array".equals(nextTag.asStartElement().getName().getLocalPart())) {
        throw new ValueSerializationException("Expected an <array/> but got: " + nextTag);
    }
    WHILE: while (input.hasNext()) {
        XMLEvent currentTag = input.nextTag();
        if (currentTag.isEndElement()) {
            String endElementName = currentTag.asEndElement().getName().getLocalPart();
            switch (endElementName) {
            case "array":
                break WHILE;
            case "value":
                continue;
            }
        }
        if (!"value".equals(currentTag.asStartElement().getName().getLocalPart())) {
            throw new ValueSerializationException("Expected a <value/> but got: " + currentTag);
        }
        T item = deserializer.map(input);
        collection.add(item);
    }
    return collection;
}

From source file:org.qi4j.valueserialization.stax.StaxValueDeserializer.java

@Override
protected <K, V> Map<K, V> readMapInMap(XMLEventReader input, Function<XMLEventReader, K> keyDeserializer,
        Function<XMLEventReader, V> valueDeserializer, Map<K, V> map) throws Exception {
    if (!input.hasNext()) {
        return null;
    }//from w ww .  j a v  a  2s  .  c o m
    XMLEvent nextTag = input.nextTag();
    if (nextTag.isStartElement() && "null".equals(nextTag.asStartElement().getName().getLocalPart())) {
        input.nextTag();
        return null;
    }
    if (!nextTag.isStartElement() || !"array".equals(nextTag.asStartElement().getName().getLocalPart())) {
        throw new ValueSerializationException("Expected an <array/> but got: " + nextTag);
    }
    XMLEvent currentTag = input.nextTag(); // <object>
    while (!currentTag.isEndElement() || !"array".equals(currentTag.asEndElement().getName().getLocalPart())) {
        if (!currentTag.isStartElement()
                || !"object".equals(currentTag.asStartElement().getName().getLocalPart())) {
            throw new ValueSerializationException("Expected an <object/> but got: " + nextTag);
        }
        currentTag = input.nextTag(); // <field>
        K key = null;
        V value = null;
        while (!currentTag.isEndElement()
                || !"object".equals(currentTag.asEndElement().getName().getLocalPart())) {
            input.nextTag(); // <name>
            String keyOrValue = input.nextEvent().asCharacters().getData();
            input.nextTag(); // </name>
            input.nextTag(); // <value>
            switch (keyOrValue) {
            case "key":
                key = keyDeserializer.map(input);
                break;
            case "value":
                value = valueDeserializer.map(input);
                break;
            default:
                readObjectTree(input);
                break;
            }
            input.nextTag(); // </value>
            input.nextTag(); // </field>
            currentTag = input.nextTag();
        }
        if (key != null) {
            map.put(key, value);
        }
        currentTag = input.nextTag();
    }
    return map;
}

From source file:org.qi4j.valueserialization.stax.StaxValueDeserializer.java

private static String readElementBody(XMLEventReader input) throws XMLStreamException {
    StringWriter buf = new StringWriter(1024);
    int depth = 0;
    while (input.hasNext()) {
        // peek event
        XMLEvent xmlEvent = input.peek();
        if (xmlEvent.isStartElement()) {
            ++depth;/*from w  w w.  j a va  2s .c o m*/
        } else if (xmlEvent.isEndElement()) {
            --depth;
            // reached END_ELEMENT tag?
            // break loop, leave event in stream
            if (depth < 0) {
                break;
            }
        }
        // consume event
        xmlEvent = input.nextEvent();
        // print out event
        xmlEvent.writeAsEncodedUnicode(buf);
    }
    return buf.getBuffer().toString();
}