List of usage examples for javax.xml.stream XMLEventReader nextEvent
public XMLEvent nextEvent() throws XMLStreamException;
From source file:org.keycloak.saml.common.util.StaxParserUtilTest.java
@Test public void testGetDOMElementSameElements() throws XMLStreamException, ParsingException { String xml = "<root><test><test><a>b</a></test></test></root>"; XMLEventReader reader = StaxParserUtil .getXMLEventReader(IOUtils.toInputStream(xml, Charset.defaultCharset())); assertThat(reader.nextEvent(), instanceOf(StartDocument.class)); assertStartTag(reader.nextEvent(), "root"); Element element = StaxParserUtil.getDOMElement(reader); assertThat(element.getNodeName(), is("test")); assertThat(element.getChildNodes().getLength(), is(1)); assertThat(element.getChildNodes().item(0), instanceOf(Element.class)); Element e = (Element) element.getChildNodes().item(0); assertThat(e.getNodeName(), is("test")); assertThat(e.getChildNodes().getLength(), is(1)); assertThat(e.getChildNodes().item(0), instanceOf(Element.class)); Element e1 = (Element) e.getChildNodes().item(0); assertThat(e1.getNodeName(), is("a")); assertThat(e1.getChildNodes().getLength(), is(1)); assertThat(e1.getChildNodes().item(0), instanceOf(Text.class)); assertThat(((Text) e1.getChildNodes().item(0)).getWholeText(), is("b")); assertEndTag(reader.nextEvent(), "root"); assertThat(reader.nextEvent(), instanceOf(EndDocument.class)); expectedException.expect(NoSuchElementException.class); Assert.fail(String.valueOf(reader.nextEvent())); }
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. * /* w ww . ja v a2 s. c o m*/ * @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
private String getValue(XMLEventReader eventReader) throws XMLStreamException { XMLEvent event = eventReader.nextEvent(); return event.asCharacters().getData(); }
From source file:org.openhab.binding.dwdunwetter.internal.data.DwdWarningsData.java
private BigDecimal getBigDecimalValue(XMLEventReader eventReader) throws XMLStreamException { XMLEvent event = eventReader.nextEvent(); try {/*from w w w .j a v a 2s. c o m*/ return new BigDecimal(event.asCharacters().getData()); } catch (NumberFormatException e) { logger.debug("Exception while parsing a BigDecimal", e); return BigDecimal.ZERO; } }
From source file:org.openhab.binding.dwdunwetter.internal.data.DwdWarningsData.java
private Instant getTimestampValue(XMLEventReader eventReader) throws XMLStreamException { XMLEvent event = eventReader.nextEvent(); String dateTimeString = event.asCharacters().getData(); try {//from w ww . j a va2 s .c om OffsetDateTime dateTime = OffsetDateTime.parse(dateTimeString, formatter); return dateTime.toInstant(); } catch (DateTimeParseException e) { logger.debug("Exception while parsing a DateTime", e); return Instant.MIN; } }
From source file:org.openhab.binding.dwdunwetter.internal.data.DwdWarningsData.java
/** * Refreshes the Warnings Data/*from ww w . j av a 2s. c o 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;// w w w . java 2 s . c om 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);//from w w w . j a v a2 s. c o 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 w w . j a v a 2 s . c o m*/ 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 <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 w w . j a va2s. c om 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; }