/** * This test was inspired by an actual bug in one of implementations: initial state was not * properly set if nextTag() was called (instead of nextEvent()), and subsequent peek() failed. */ public void testPeek() throws XMLStreamException { String XML = "<root>text</root>"; for (int i = 0; i < 4; ++i) { boolean ns = (i & 1) != 0; boolean coal = (i & 2) != 0; XMLEventReader er = getReader(XML, ns, coal); assertTokenType(START_DOCUMENT, er.nextEvent().getEventType()); XMLEvent tag = er.nextTag(); assertTokenType(START_ELEMENT, tag.getEventType()); // Now, peek() should produce text.. XMLEvent text = er.peek(); assertTokenType(CHARACTERS, text.getEventType()); Characters chars = text.asCharacters(); assertNotNull(chars); assertEquals("text", chars.getData()); // and need nextEvent() to get rid of it, too: text = er.nextEvent(); // Let's verify it again: assertTokenType(CHARACTERS, text.getEventType()); chars = text.asCharacters(); assertNotNull(chars); assertEquals("text", chars.getData()); assertTokenType(END_ELEMENT, er.nextTag().getEventType()); assertTokenType(END_DOCUMENT, er.nextEvent().getEventType()); // And at the end, peek() should return null assertNull(er.peek()); } }
@SuppressWarnings({"unchecked"}) private JaxbHibernateConfiguration unmarshal( XMLEventReader staxEventReader, final Origin origin) { XMLEvent event; try { event = staxEventReader.peek(); while (event != null && !event.isStartElement()) { staxEventReader.nextEvent(); event = staxEventReader.peek(); } } catch (Exception e) { throw new HibernateException("Error accessing stax stream", e); } if (event == null) { throw new HibernateException("Could not locate root element"); } if (!isNamespaced(event.asStartElement())) { // if the elements are not namespaced, wrap the reader in a reader which will namespace them // as pulled. log.debug( "cfg.xml document did not define namespaces; wrapping in custom event reader to introduce namespace information"); staxEventReader = new NamespaceAddingEventReader(staxEventReader, HIBERNATE_CONFIGURATION_URI); } final Object target; final ContextProvidingValidationEventHandler handler = new ContextProvidingValidationEventHandler(); try { JAXBContext jaxbContext = JAXBContext.newInstance(JaxbHibernateConfiguration.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setSchema(schema()); unmarshaller.setEventHandler(handler); target = unmarshaller.unmarshal(staxEventReader); return (JaxbHibernateConfiguration) target; } catch (JAXBException e) { StringBuilder builder = new StringBuilder(); builder .append("Unable to perform unmarshalling at line number ") .append(handler.getLineNumber()) .append(" and column ") .append(handler.getColumnNumber()) .append(" in ") .append(origin.getType().name()) .append(" ") .append(origin.getName()) .append(". Message: ") .append(handler.getMessage()); throw new ConfigurationException(builder.toString(), e); } }
public void testNextTagOk() throws XMLStreamException { String XML = "<root>\n" + "<branch> <leaf> </leaf></branch>" + "</root>"; for (int i = 0; i < 4; ++i) { boolean ns = (i & 1) != 0; boolean coal = (i & 2) != 0; XMLEventReader er = getReader(XML, ns, coal); assertTokenType(START_DOCUMENT, er.nextEvent().getEventType()); assertTokenType(START_ELEMENT, er.nextTag().getEventType()); assertTokenType(START_ELEMENT, er.nextTag().getEventType()); /* Ok, let's mix in bit of peeking to ensure reader won't * be confused too badly... */ // This should be space between <branch> and <leaf>... assertTokenType(CHARACTERS, er.peek().getEventType()); // And then the leaf assertTokenType(START_ELEMENT, er.nextTag().getEventType()); assertTokenType(END_ELEMENT, er.nextTag().getEventType()); assertTokenType(END_ELEMENT, er.nextTag().getEventType()); assertTokenType(END_ELEMENT, er.nextTag().getEventType()); assertTokenType(END_DOCUMENT, er.nextEvent().getEventType()); assertFalse(er.hasNext()); } }
private Object unmarshal0(XMLEventReader reader, JaxBeanInfo expectedType) throws JAXBException { if (reader == null) { throw new IllegalArgumentException(Messages.format(Messages.NULL_READER)); } try { XMLEvent event = reader.peek(); if (!event.isStartElement() && !event.isStartDocument()) { // TODO: convert event into event name throw new IllegalStateException( Messages.format(Messages.ILLEGAL_READER_STATE, event.getEventType())); } // Quick hack until SJSXP fixes 6270116 boolean isZephyr = reader.getClass().getName().equals("com.sun.xml.stream.XMLReaderImpl"); XmlVisitor h = createUnmarshallerHandler(null, false, expectedType); if (!isZephyr) { h = new InterningXmlVisitor(h); } new StAXEventConnector(reader, h).bridge(); return h.getContext().getResult(); } catch (XMLStreamException e) { throw handleStreamException(e); } }
public void testElementText() throws XMLStreamException { String TEXT1 = "some\ntest"; String TEXT2 = "inside CDATA too!"; String XML = "<root>" + TEXT1 + "<![CDATA[" + TEXT2 + "]]></root>"; // First, let's see how things work without peeking: for (int i = 0; i < 4; ++i) { boolean ns = (i & 1) != 0; boolean coal = (i & 2) != 0; XMLEventReader er = getReader(XML, ns, coal); assertTokenType(START_DOCUMENT, er.nextEvent().getEventType()); XMLEvent elem = er.nextEvent(); assertTokenType(START_ELEMENT, elem.getEventType()); try { assertEquals(TEXT1 + TEXT2, er.getElementText()); } catch (XMLStreamException sex) { fail("Failed on XMLEventReader.getElementText(): " + sex); } /* 06-Jan-2006, TSa: I'm really not sure whether to expect * END_ELEMENT, or END_DOCUMENT here... maybe the latter * makes more sense? For now let's accept both, however. */ elem = er.nextEvent(); if (elem.getEventType() != END_DOCUMENT && elem.getEventType() != END_ELEMENT) { fail("Expected END_DOCUMENT or END_ELEMENT, got " + tokenTypeDesc(elem.getEventType())); } } // and then with peeking: for (int i = 0; i < 4; ++i) { boolean ns = (i & 1) != 0; boolean coal = (i & 2) != 0; XMLEventReader er = getReader(XML, ns, coal); assertTokenType(START_DOCUMENT, er.nextEvent().getEventType()); XMLEvent elem = er.nextEvent(); assertTokenType(START_ELEMENT, elem.getEventType()); XMLEvent peeked = er.peek(); assertTokenType(CHARACTERS, peeked.getEventType()); assertEquals(TEXT1 + TEXT2, er.getElementText()); /* 06-Jan-2006, TSa: I'm really not sure whether to expect * END_ELEMENT, or END_DOCUMENT here... maybe the latter * makes more sense? For now let's accept both, however. */ elem = er.nextEvent(); if (elem.getEventType() != END_DOCUMENT && elem.getEventType() != END_ELEMENT) { fail("Expected END_DOCUMENT or END_ELEMENT, got " + tokenTypeDesc(elem.getEventType())); } } }
public Amplitude(XMLEventReader reader) throws XMLStreamException, SeisFileException { StartElement startE = StaxUtil.expectStartElement(ELEMENT_NAME, reader); publicID = StaxUtil.pullAttribute(startE, QuakeMLTagNames.publicId); while (reader.hasNext()) { XMLEvent e = reader.peek(); if (e.isStartElement()) { String elName = e.asStartElement().getName().getLocalPart(); if (elName.equals(QuakeMLTagNames.comment)) { commentList.add(new Comment(reader)); } else if (elName.equals(QuakeMLTagNames.type)) { type = StaxUtil.pullText(reader, QuakeMLTagNames.type); } else if (elName.equals(QuakeMLTagNames.category)) { category = StaxUtil.pullText(reader, QuakeMLTagNames.category); } else if (elName.equals(QuakeMLTagNames.unit)) { unit = StaxUtil.pullText(reader, QuakeMLTagNames.unit); } else if (elName.equals(QuakeMLTagNames.methodID)) { methodID = StaxUtil.pullText(reader, QuakeMLTagNames.methodID); } else if (elName.equals(QuakeMLTagNames.snr)) { snr = StaxUtil.pullFloat(reader, QuakeMLTagNames.snr); } else if (elName.equals(QuakeMLTagNames.scalingTime)) { scalingTime = new Time(reader, QuakeMLTagNames.scalingTime); } else if (elName.equals(QuakeMLTagNames.timeWindow)) { timeWindow = new TimeWindow(reader); } else if (elName.equals(QuakeMLTagNames.waveformID)) { waveformID = new WaveformStreamID(reader, QuakeMLTagNames.waveformID); } else if (elName.equals(QuakeMLTagNames.filterID)) { filterID = StaxUtil.pullText(reader, QuakeMLTagNames.filterID); } else if (elName.equals(QuakeMLTagNames.magnitudeHint)) { magnitudeHint = StaxUtil.pullText(reader, QuakeMLTagNames.magnitudeHint); } else if (elName.equals(QuakeMLTagNames.pickID)) { pickID = StaxUtil.pullText(reader, QuakeMLTagNames.pickID); } else if (elName.equals(QuakeMLTagNames.period)) { period = new RealQuantity(reader, QuakeMLTagNames.period); } else if (elName.equals(QuakeMLTagNames.evaluationMode)) { evaluationMode = StaxUtil.pullText(reader, QuakeMLTagNames.evaluationMode); } else if (elName.equals(QuakeMLTagNames.evaluationStatus)) { evaluationStatus = StaxUtil.pullText(reader, QuakeMLTagNames.evaluationStatus); } else if (elName.equals(QuakeMLTagNames.genericAmplitude)) { genericAmplitude = new RealQuantity(reader, QuakeMLTagNames.genericAmplitude); } else if (elName.equals(QuakeMLTagNames.creationInfo)) { creationInfo = new CreationInfo(reader); } else { StaxUtil.skipToMatchingEnd(reader); } } else if (e.isEndElement()) { reader.nextEvent(); return; } else { e = reader.nextEvent(); } } }
@Override protected OAIPMHtype parseElement(XMLEventReader reader) throws ParseException { OAIPMHtype pmh = new OAIPMHtype(); try { if (!reader.peek().asStartElement().getName().getLocalPart().equals(NAME)) throw new ParseException("Expecting " + NAME + " element"); reader.nextEvent(); this.nextElement(reader); pmh.setResponseDate( super.getConfiguration().getFormatter().parse(this.getElement(reader, RESPONSE_DATE))); pmh.setRequest(reqParser.parse(reader)); String name = reader.peek().asStartElement().getName().getLocalPart(); if (name.equals("ListRecords")) pmh.setListRecords(listRecordsParser.parse(reader)); else if (name.equals("GetRecord")) pmh.setGetRecord(getRecordParser.parse(reader)); else if (name.equals("ListIdentifiers")) pmh.setListIdentifiers(listIdentifiersParser.parse(reader)); else if (name.equals("ListSets")) pmh.setListSets(listSetsParser.parse(reader)); else if (name.equals("ListMetadataFormats")) pmh.setListMetadataFormats(listMetadataFormatsParser.parse(reader)); else if (name.equals("Identify")) pmh.setIdentify(identifyParser.parse(reader)); else { while (reader.peek().asStartElement().getName().getLocalPart().equals("error")) { pmh.getError().add(errorParser.parse(reader)); } } } catch (XMLStreamException e) { throw new ParseException(e); } catch (java.text.ParseException e) { throw new ParseException(e); } return pmh; }
private static StringBuilder readCharacters(XMLEventReader eventReader) throws XMLStreamException { StringBuilder buffer = new StringBuilder(); XMLEvent next; do { next = eventReader.nextEvent(); String data = next.asCharacters().getData(); buffer.append(data.trim()); next = eventReader.peek(); } while (next != null && next.isCharacters()); return buffer; }
public ResponseListElement(XMLEventReader reader) throws XMLStreamException, StationXMLException { StartElement startE = StaxUtil.expectStartElement(StationXMLTagNames.POLESZEROS, reader); while (reader.hasNext()) { XMLEvent e = reader.peek(); if (e.isStartElement()) { String elName = e.asStartElement().getName().getLocalPart(); if (elName.equals(StationXMLTagNames.FREQUENCY)) { frequency = StaxUtil.pullFloat(reader, StationXMLTagNames.FREQUENCY); } else if (elName.equals(StationXMLTagNames.AMPLITUDE)) { amplitude = StaxUtil.pullFloat(reader, StationXMLTagNames.AMPLITUDE); } else if (elName.equals(StationXMLTagNames.PHASE)) { phase = StaxUtil.pullFloat(reader, StationXMLTagNames.PHASE); } else { StaxUtil.skipToMatchingEnd(reader); } } else if (e.isEndElement()) { reader.nextEvent(); return; } else { e = reader.nextEvent(); } } }
/** * Check to see if the next even is just a new line character. If so add it to the end of the last * events string. */ private void checkForNewLine() { preWhiteSpace = ""; postWhiteSpace = ""; if (hasNext()) { // If there is a next event... try { XMLEvent event = parser.peek(); // ...peek at it and... String eventString = event.toString(); // ...get it's character representation. // Then if the next event is just a new ling and whitespace... if (eventString.matches(UNIX_NEW_LINE_REGEXP) || eventString.matches(SYSTEM_NEW_LINE_REGEXP)) { // Record the whitespace that needs to be placed before the next real element. preWhiteSpace = eventString.substring(eventString.indexOf('\n') + 1); // Record the whitespace that needs to be placed after this element. postWhiteSpace = eventString.substring(0, eventString.indexOf('\n') + 1); parser.nextEvent(); // Lastly move on to the next element what ever it may be. } } catch (XMLStreamException e) { System.out.println("SORT THIS OUT!: " + e.getMessage()); } } }
public void testSkip() throws XMLStreamException { String XML = "<?xml version='1.0' ?><!DOCTYPE root><root>\n" + "<branch> <leaf> </leaf></branch><!-- comment -->" + "</root>"; for (int i = 0; i < 4; ++i) { boolean ns = (i & 1) != 0; boolean coal = (i & 2) != 0; XMLEventReader er = getReader(XML, ns, coal); XMLEvent ev; assertTokenType(START_DOCUMENT, er.peek().getEventType()); assertTokenType(START_DOCUMENT, er.nextEvent().getEventType()); assertTokenType(DTD, er.peek().getEventType()); assertTokenType(DTD, er.nextEvent().getEventType()); assertTokenType(START_ELEMENT, er.peek().getEventType()); assertTokenType(START_ELEMENT, er.nextEvent().getEventType()); assertTokenType(CHARACTERS, er.peek().getEventType()); assertTokenType(CHARACTERS, er.nextEvent().getEventType()); // branch assertTokenType(START_ELEMENT, er.peek().getEventType()); assertTokenType(START_ELEMENT, er.nextEvent().getEventType()); assertTokenType(CHARACTERS, er.peek().getEventType()); assertTokenType(CHARACTERS, er.nextEvent().getEventType()); // leaf assertTokenType(START_ELEMENT, er.peek().getEventType()); assertTokenType(START_ELEMENT, er.nextEvent().getEventType()); assertTokenType(CHARACTERS, er.peek().getEventType()); assertTokenType(CHARACTERS, er.nextEvent().getEventType()); assertTokenType(END_ELEMENT, er.peek().getEventType()); assertTokenType(END_ELEMENT, er.nextEvent().getEventType()); assertTokenType(END_ELEMENT, er.peek().getEventType()); assertTokenType(END_ELEMENT, er.nextEvent().getEventType()); assertTokenType(COMMENT, er.peek().getEventType()); assertTokenType(COMMENT, er.nextEvent().getEventType()); assertTokenType(END_ELEMENT, er.peek().getEventType()); assertTokenType(END_ELEMENT, er.nextEvent().getEventType()); assertTokenType(END_DOCUMENT, er.peek().getEventType()); assertTokenType(END_DOCUMENT, er.nextEvent().getEventType()); assertFalse(er.hasNext()); } }
public void parse(XMLEventReader input) throws XMLStreamException, XNIException { XMLEvent currentEvent = input.peek(); if (currentEvent != null) { int eventType = currentEvent.getEventType(); if (eventType != XMLStreamConstants.START_DOCUMENT && eventType != XMLStreamConstants.START_ELEMENT) { throw new XMLStreamException(); } fLocationWrapper.setLocation(currentEvent.getLocation()); fSchemaDOMParser.startDocument(fLocationWrapper, null, fNamespaceContext, null); loop: while (input.hasNext()) { currentEvent = input.nextEvent(); eventType = currentEvent.getEventType(); switch (eventType) { case XMLStreamConstants.START_ELEMENT: ++fDepth; StartElement start = currentEvent.asStartElement(); fillQName(fElementQName, start.getName()); fLocationWrapper.setLocation(start.getLocation()); fNamespaceContext.setNamespaceContext(start.getNamespaceContext()); fillXMLAttributes(start); fillDeclaredPrefixes(start); addNamespaceDeclarations(); fNamespaceContext.pushContext(); fSchemaDOMParser.startElement(fElementQName, fAttributes, null); break; case XMLStreamConstants.END_ELEMENT: EndElement end = currentEvent.asEndElement(); fillQName(fElementQName, end.getName()); fillDeclaredPrefixes(end); fLocationWrapper.setLocation(end.getLocation()); fSchemaDOMParser.endElement(fElementQName, null); fNamespaceContext.popContext(); --fDepth; if (fDepth <= 0) { break loop; } break; case XMLStreamConstants.CHARACTERS: sendCharactersToSchemaParser(currentEvent.asCharacters().getData(), false); break; case XMLStreamConstants.SPACE: sendCharactersToSchemaParser(currentEvent.asCharacters().getData(), true); break; case XMLStreamConstants.CDATA: fSchemaDOMParser.startCDATA(null); sendCharactersToSchemaParser(currentEvent.asCharacters().getData(), false); fSchemaDOMParser.endCDATA(null); break; case XMLStreamConstants.PROCESSING_INSTRUCTION: ProcessingInstruction pi = (ProcessingInstruction) currentEvent; fillProcessingInstruction(pi.getData()); fSchemaDOMParser.processingInstruction(pi.getTarget(), fTempString, null); break; case XMLStreamConstants.DTD: /* There shouldn't be a DTD in the schema */ break; case XMLStreamConstants.ENTITY_REFERENCE: /* Not needed for schemas */ break; case XMLStreamConstants.COMMENT: /* No point in sending comments */ break; case XMLStreamConstants.START_DOCUMENT: fDepth++; /* We automatically call startDocument before the loop */ break; case XMLStreamConstants.END_DOCUMENT: /* We automatically call endDocument after the loop */ break; } } fLocationWrapper.setLocation(null); fNamespaceContext.setNamespaceContext(null); fSchemaDOMParser.endDocument(null); } }
private static void untilFirstStartElement(XMLEventReader reader) throws XMLStreamException { while (reader.peek() != null && !reader.peek().isStartElement() && !reader.peek().isEndDocument()) reader.nextEvent(); }
public static XMLEvent peekNextTag(XMLEventReader eventReader) throws XMLStreamException { while (!(eventReader.peek().isEndElement() || eventReader.peek().isStartElement())) { eventReader.nextEvent(); } return eventReader.peek(); }