public AtomParser(final ContentSource contentSource, final InputStream inputStream) { super(contentSource, inputStream); availableSetters = new String [] {"setTitle", "setUpdated", "setLink", "setContent", "setPublished"}; try { startElementMethods.put(TAG_FEED, ObjectUtil.assertNotNull(getDeclaredMethod("createParsingElement", String.class, XMLEvent.class, XMLEventReader.class), TAG_FEED)); startElementMethods.put(TAG_ENTRY, ObjectUtil.assertNotNull(getDeclaredMethod("pushElementIntoMap", String.class, XMLEvent.class, XMLEventReader.class), TAG_ENTRY)); // used for the feed and entry startElementMethods.put(TAG_UPDATED, ObjectUtil.assertNotNull(getDeclaredMethod("parseStandardElement", String.class, XMLEvent.class, XMLEventReader.class), TAG_UPDATED)); // used only in entry startElementMethods.put(TAG_TITLE, ObjectUtil.assertNotNull(getDeclaredMethod("parseStandardElement", String.class, XMLEvent.class, XMLEventReader.class), TAG_TITLE)); startElementMethods.put(TAG_LINK, ObjectUtil.assertNotNull(getDeclaredMethod("parseStandardElement", String.class, XMLEvent.class, XMLEventReader.class), TAG_LINK)); startElementMethods.put(TAG_CONTENT, ObjectUtil.assertNotNull(getDeclaredMethod("parseStandardElement", String.class, XMLEvent.class, XMLEventReader.class), TAG_CONTENT)); startElementMethods.put(TAG_PUBLISHED, ObjectUtil.assertNotNull(getDeclaredMethod("parseStandardElement", String.class, XMLEvent.class, XMLEventReader.class), TAG_PUBLISHED)); endElementMehods.put(TAG_ENTRY, ObjectUtil.assertNotNull(getDeclaredMethod("popElementFromStack"), TAG_ENTRY)); specialMethods.put(TAG_ENTRY, ObjectUtil.assertNotNull(getDeclaredMethod("createItemObject"), TAG_ENTRY)); } catch (final SecurityException e) { LOGGER.error("Failed creating {} because", getClass(), e ); } }
@Test public void testEventReader2() { try { // Now advance underlying reader and then call peek on event reader XMLStreamReader s1 = inputFactory.createXMLStreamReader(new java.io.StringReader(xml)); Assert.assertEquals(s1.getEventType(), XMLStreamConstants.START_DOCUMENT); s1.next(); s1.next(); // advance to <TITLE> Assert.assertTrue(s1.getLocalName().equals("TITLE")); XMLEventReader e3 = inputFactory.createXMLEventReader(s1); Assert.assertEquals(e3.peek().getEventType(), XMLStreamConstants.START_ELEMENT); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void test() { String xmlData = "<?xml version=\"1.0\"?><Test>Hello</Test>"; try { XMLEventReader xmlReader = XMLInputFactory.newInstance().createXMLEventReader(new ByteArrayInputStream(xmlData.getBytes())); XMLEvent event = xmlReader.nextEvent(); System.out.println(event.getClass()); // xmlReader.peek(); // error in both cases with/without peek() event = xmlReader.nextTag(); // nextEvent() would work fine // nextTag() forgets to set fLastEvent System.out.println(event.getClass()); String text = xmlReader.getElementText(); System.out.println(text); } catch (XMLStreamException e) { Assert.fail(e.getMessage()); } }
public JaxbRoot unmarshal(InputStream stream, Origin origin) { try { XMLEventReader staxReader = staxFactory().createXMLEventReader( stream ); try { return unmarshal( staxReader, origin ); } finally { try { staxReader.close(); } catch ( Exception ignore ) { } } } catch ( XMLStreamException e ) { throw new MappingException( "Unable to create stax reader", e, origin ); } }
public JaxbHibernateConfiguration unmarshal(InputStream stream, Origin origin) { try { XMLEventReader staxReader = staxFactory().createXMLEventReader( stream ); try { return unmarshal( staxReader, origin ); } finally { try { staxReader.close(); } catch ( Exception ignore ) { } } } catch ( XMLStreamException e ) { throw new MappingException( "Unable to create stax reader", e, origin ); } }
/** * Test: 6419687 NPE in XMLEventWriterImpl. */ @Test public void testCR6419687() { try { InputStream in = getClass().getResourceAsStream("ReaderToWriterTest.wsdl"); OutputStream out = new FileOutputStream(USER_DIR + "ReaderToWriterTest-out.xml"); XMLEventReader reader = XML_INPUT_FACTORY.createXMLEventReader(in); XMLEventWriter writer = XML_OUTPUT_FACTORY.createXMLEventWriter(out, "UTF-8"); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); writer.add(event); } reader.close(); writer.close(); } catch (XMLStreamException xmlStreamException) { xmlStreamException.printStackTrace(); Assert.fail(xmlStreamException.toString()); } catch (FileNotFoundException fileNotFoundException) { fileNotFoundException.printStackTrace(); Assert.fail(fileNotFoundException.toString()); } }
private Document toDom4jDocument(XMLEventReader staxEventReader, Origin origin) { STAXEventReader dom4jStaxEventReader = new STAXEventReader(); try { // the dom4j converter class is touchy about comments (aka, comments make it implode) // so wrap the event stream in a filtering stream to filter out comment events staxEventReader = new FilteringXMLEventReader( staxEventReader ) { @Override protected XMLEvent filterEvent(XMLEvent event, boolean peek) { return event.getEventType() == XMLStreamConstants.COMMENT ? null : event; } }; return dom4jStaxEventReader.readDocument( staxEventReader ); } catch (XMLStreamException e) { throw new InvalidMappingException( "Unable to read StAX source as dom4j Document for processing", origin, e ); } }
/** * Test XMLStreamWriter parsing a file with an external entity reference. */ @Test public void testXMLStreamWriter() { try { XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(System.out); XMLInputFactory inputFactory = XMLInputFactory.newInstance(); String file = getClass().getResource("XMLEventWriterTest.xml").getPath(); XMLEventReader eventReader = inputFactory.createXMLEventReader(new StreamSource(new File(file))); // adds the event to the consumer. eventWriter.add(eventReader); eventWriter.flush(); eventWriter.close(); // expected success } catch (Exception exception) { exception.printStackTrace(); Assert.fail(exception.toString()); } }
/** * Method checks if the storage type is supported and transforms it to XMLEventReader instance which is then returned. * Throws PolicyException if the transformation is not succesfull or if the storage type is not supported. * * @param storage An XMLEventReader instance. * @return The storage cast to an XMLEventReader. * @throws PolicyException If the XMLEventReader cast failed. */ private XMLEventReader createXMLEventReader(final Object storage) throws PolicyException { if (storage instanceof XMLEventReader) { return (XMLEventReader) storage; } else if (!(storage instanceof Reader)) { throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0022_STORAGE_TYPE_NOT_SUPPORTED(storage.getClass().getName()))); } try { return XMLInputFactory.newInstance().createXMLEventReader((Reader) storage); } catch (XMLStreamException e) { throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0014_UNABLE_TO_INSTANTIATE_READER_FOR_STORAGE(), e)); } }
public TubelineFeature parse(XMLEventReader reader) throws WebServiceException { try { final StartElement element = reader.nextEvent().asStartElement(); boolean attributeEnabled = true; final Iterator iterator = element.getAttributes(); while (iterator.hasNext()) { final Attribute nextAttribute = (Attribute) iterator.next(); final QName attributeName = nextAttribute.getName(); if (ENABLED_ATTRIBUTE_NAME.equals(attributeName)) { attributeEnabled = ParserUtil.parseBooleanValue(nextAttribute.getValue()); } else if (NAME_ATTRIBUTE_NAME.equals(attributeName)) { // TODO use name attribute } else { // TODO logging message throw LOGGER.logSevereException(new WebServiceException("Unexpected attribute")); } } return parseFactories(attributeEnabled, element, reader); } catch (XMLStreamException e) { throw LOGGER.logSevereException(new WebServiceException("Failed to unmarshal XML document", e)); } }
public void eventReaderTest(XMLInputFactory xif) { XMLEventReader eventReader = null; try { eventReader = xif.createXMLEventReader(this.getClass().getResourceAsStream(INPUT_FILE)); XMLEventReader filteredEventReader = xif.createFilteredReader(eventReader, new EventFilter() { public boolean accept(XMLEvent event) { if (!event.isStartElement()) { return false; } QName elementQName = event.asStartElement().getName(); if ((elementQName.getLocalPart().equals(ATTACHMENT_NAME.getLocalPart()) || elementQName.getLocalPart().equals("Attachment")) && elementQName.getNamespaceURI().equals(VF_GENERIC_TT_NAMESPACE)) { return true; } return false; } }); if (filteredEventReader.hasNext()) { System.out.println("containsAttachments() returns true"); } } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } finally { if (eventReader != null) { try { eventReader.close(); } catch (XMLStreamException xse) { // Ignored by intention } } } }
private XMLEventReader getXMLEventReader(final String filename) { XMLInputFactory xmlif = null; XMLEventReader xmlr = null; try { xmlif = XMLInputFactory.newInstance(); xmlif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); xmlif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); xmlif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); xmlif.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); // FileInputStream fis = new FileInputStream(filename); FileInputStream fis = new FileInputStream(new File(ValidatorTest.class.getResource(filename).toURI())); xmlr = xmlif.createXMLEventReader(filename, fis); } catch (Exception ex) { ex.printStackTrace(); Assert.fail("Exception : " + ex.getMessage()); } return xmlr; }
@Test public void test0() { try { XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(getClass().getResource("sgml.xml").toString(), getClass().getResourceAsStream("sgml.xml")); XMLEventReader xer = xif.createXMLEventReader(xsr); Assert.assertTrue(xer.peek().getEventType() == XMLEvent.START_DOCUMENT); Assert.assertTrue(xer.peek() == xer.nextEvent()); xsr.close(); } catch (Exception e) { Assert.fail(e.getMessage()); } }
/** * Test method for GetAttributesResponseUnmarshaller */ @Test public final void testUnmarshall() throws Exception { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(DomainMetadataResultUnmarshallerTest.class .getResourceAsStream("GetAttributesResponse.xml")); StaxUnmarshallerContext unmarshallerContext = new StaxUnmarshallerContext(eventReader); GetAttributesResponse result = new GetAttributesResponseUnmarshaller() .unmarshall(unmarshallerContext); assertTrue(!result.attributes().isEmpty()); assertTrue(result.attributes().size() == 2); assertTrue(result.attributes().get(0).name().equals("Color")); assertTrue(result.attributes().get(0).value().equals("Blue")); assertTrue(result.attributes().get(1).name().equals("Price")); assertTrue(result.attributes().get(1).value().equals("$2.50")); }
/** * Test method for DomainMetadataResultXpathUnmarshaller */ @Test public final void testXpathUnmarshaller() throws Exception { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(DomainMetadataResultUnmarshallerTest.class .getResourceAsStream("DomainMetadataResponse.xml")); StaxUnmarshallerContext unmarshallerContext = new StaxUnmarshallerContext(eventReader); DomainMetadataResponse result = new DomainMetadataResponseUnmarshaller() .unmarshall(unmarshallerContext); assertTrue(result.itemCount() == 25); assertTrue(result.itemNamesSizeBytes() == 12345); assertTrue(result.attributeNameCount() == 20); assertTrue(result.attributeNamesSizeBytes() == 2345); assertTrue(result.attributeValueCount() == 25); assertTrue(result.attributeValuesSizeBytes() == 1234); assertTrue(result.timestamp() == 5555); }
@Test public void testNoEncoding() { try { InputStream in = util.BOMInputStream.createStream("UTF-16BE", this.getClass().getResourceAsStream(INPUT_FILE)); OutputStream out = new FileOutputStream(OUTPUT_FILE); XMLEventReader reader = XML_INPUT_FACTORY.createXMLEventReader(in); XMLEventWriter writer = XML_OUTPUT_FACTORY.createXMLEventWriter(out); writeEvents(reader, writer); checkOutput(OUTPUT_FILE); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception occured: " + e.getMessage()); } finally { File file = new File(OUTPUT_FILE); if (file.exists()) file.delete(); } }
/** * Pushes a element into the local stack. * <br> * <b>Attention: Reflection-Method - do not change method header</b> * @param localPart * @param event - not used * @param eventReader - not used */ protected void pushElementIntoMap(final String localPart, final XMLEvent event, final XMLEventReader eventReader) { actualElement.push(localPart); if (specialMethods.containsKey(localPart)) { Method method; try { method = specialMethods.get(localPart); method.invoke(this); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) { LOGGER.error("Error while invoking method for local part: {}", localPart, e); } } }
/** * Returns an instance of XMLEventReader. * * @return an instance of XMLEventReader. */ private XMLEventReader getXMLEventReader() { XMLEventReader r = null; try { r = XMLInputFactory.newInstance().createXMLEventReader( new ByteArrayInputStream("".getBytes())); } catch (XMLStreamException ex) {} return r; }
public static void readXMLByStAX() throws XMLStreamException, FileNotFoundException { XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader reader = factory.createXMLEventReader(new FileInputStream("test.xml"));//StaxDemo.class.getResourceAsStream("test.xml") XMLEvent event; StringBuffer parsingResult = new StringBuffer(); while (reader.hasNext()) { event = reader.nextEvent(); if (event.isStartElement()) { StartElement se = event.asStartElement(); parsingResult.append("<"); parsingResult.append(se.getName()); if (se.getName().getLocalPart().equals("catalog")) { parsingResult.append("id="); parsingResult.append(se.getAttributeByName(new QName("id")).getValue()); parsingResult.append(""); } parsingResult.append(">"); } else if (event.isCharacters()) { parsingResult.append(event.asCharacters().getData()); } else if (event.isEndElement()) { parsingResult.append("</"); parsingResult.append(event.asEndElement().getName()); parsingResult.append(">"); } } System.out.println(parsingResult); }
/** * Parse a text-format message from {@code input} and merge the contents into {@code builder}. * Extensions will be recognized if they are registered in {@code extensionRegistry}. * @throws IOException */ public void merge(InputStream input, Charset cs, ExtensionRegistry extensionRegistry, Message.Builder builder) throws IOException { XMLEventReader parser; try { parser = xmlInputFactory.createXMLEventReader(input); merge(parser, extensionRegistry, builder); } catch (XMLStreamException e) { throw new IOException(e); } }
private void handleMissingField(String fieldName, XMLEventReader parser, XMLEvent event, ExtensionRegistry extensionRegistry, UnknownFieldSet.Builder builder) throws XMLStreamException { // skip over the unknown fields, since we can't map them by id, then this message must not know about them. // We 'could' map them into the UnknownFieldSet, however none of the other formatters support this.. // but in the future it would probably be useful for the case: Message A (v2) -> Message B (v1) -> Xml -> Message A (v2) // this would require extra meta data in the xml to know the type of the unknown-field. if (event.isStartElement()) { /** * This loop will eat up everything inside "6" * So when this method is called, fieldName = 6, and event is set at index="11" * <unknown-field index="6"> * <unknown-field index="11">566667</unknown-field> * <unknown-field index="15"> * <unknown-field index="16">566667</unknown-field> * </unknown-field> * </unknown-field> */ int depth = 1; // we start 1 level down, the value of "6" while (parser.hasNext()) { XMLEvent nextEvent = parser.nextEvent(); if (nextEvent.isEndElement()) { depth--; if (depth <= 0 && parser.peek().isEndElement()) { break; } } else if (nextEvent.isStartElement()) { depth++; } } } else if (event.isCharacters()) { // done, let it slide. } }
private Object handleObject(XMLEventReader parser, XMLEvent startEvent, ExtensionRegistry extensionRegistry, Message.Builder builder, FieldDescriptor field, ExtensionRegistry.ExtensionInfo extension) throws XMLStreamException { Message.Builder subBuilder = createSubBuilder(builder, field, extension); XMLEvent event = startEvent; int depth = 0; // initialize to 0 do { if (event.isStartElement()) { depth++; // we're inside the element mergeField(parser, event, extensionRegistry, subBuilder); XMLEvent nextEvent = parser.nextTag(); if (nextEvent.isEndElement()) { depth--; // if we're back under the top level obj, and there is another close, we're done. if (depth <= 0 && parser.peek().isEndElement()) { break; } } else if (nextEvent.isStartElement()) { depth++; } } else { // something is potentially wrong.. break; } } while (parser.hasNext() && (event = parser.nextTag()) != null); return subBuilder.build(); }
private void checkOutput(String output) throws Exception { InputStream in = new FileInputStream(output); XMLEventReader reader = XML_INPUT_FACTORY.createXMLEventReader(in); while (reader.hasNext()) { reader.next(); } reader.close(); }
private XMLEventReader getReader(String XML) throws Exception { inputFactory = XMLInputFactory.newInstance(); // Check if event reader returns the correct event XMLEventReader er = inputFactory.createXMLEventReader(new StringReader(XML)); return er; }
/** * * @param eventReader * @throws XMLStreamException */ public void add(XMLEventReader eventReader) throws XMLStreamException { if(eventReader == null) throw new XMLStreamException(CommonResourceBundle.getInstance().getString("message.nullEventReader")); while(eventReader.hasNext()){ add(eventReader.nextEvent()); } }
public static Map<URI, Policy> unmarshal(final Reader source) throws PolicyException { LOGGER.entering(source); try { XMLEventReader reader = XML_INPUT_FACTORY.get().createXMLEventReader(source); ExternalAttachmentsUnmarshaller instance = new ExternalAttachmentsUnmarshaller(); final Map<URI, Policy> map = instance.unmarshal(reader, null); LOGGER.exiting(map); return Collections.unmodifiableMap(map); } catch (XMLStreamException ex) { throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0086_FAILED_CREATE_READER(source)), ex); } }
private Map<URI, Policy> unmarshal(final XMLEventReader reader, final StartElement parentElement) throws PolicyException { XMLEvent event = null; while (reader.hasNext()) { try { event = reader.peek(); switch (event.getEventType()) { case XMLStreamConstants.START_DOCUMENT: case XMLStreamConstants.COMMENT: reader.nextEvent(); break; case XMLStreamConstants.CHARACTERS: processCharacters(event.asCharacters(), parentElement, map); reader.nextEvent(); break; case XMLStreamConstants.END_ELEMENT: processEndTag(event.asEndElement(), parentElement); reader.nextEvent(); return map; case XMLStreamConstants.START_ELEMENT: final StartElement element = event.asStartElement(); processStartTag(element, parentElement, reader, map); break; case XMLStreamConstants.END_DOCUMENT: return map; default: throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0087_UNKNOWN_EVENT(event))); } } catch (XMLStreamException e) { final Location location = event == null ? null : event.getLocation(); throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0088_FAILED_PARSE(location)), e); } } return map; }
private void readPolicy(final XMLEventReader reader) throws PolicyException { final PolicySourceModel policyModel = POLICY_UNMARSHALLER.unmarshalModel(reader); final PolicyModelTranslator translator = PolicyModelTranslator.getTranslator(); final Policy policy = translator.translate(policyModel); if (this.currentUri != null) { map.put(this.currentUri, policy); this.currentUri = null; this.currentPolicy = null; } else { this.currentPolicy = policy; } }
private String unmarshalNodeContent(final NamespaceVersion nsVersion, final ModelNode node, final QName nodeElementName, final XMLEventReader reader) throws PolicyException { StringBuilder valueBuffer = null; loop: while (reader.hasNext()) { try { final XMLEvent xmlParserEvent = reader.nextEvent(); switch (xmlParserEvent.getEventType()) { case XMLStreamConstants.COMMENT: break; // skipping the comments case XMLStreamConstants.CHARACTERS: valueBuffer = processCharacters(node.getType(), xmlParserEvent.asCharacters(), valueBuffer); break; case XMLStreamConstants.END_ELEMENT: checkEndTagName(nodeElementName, xmlParserEvent.asEndElement()); break loop; // data exctraction for currently processed policy node is done case XMLStreamConstants.START_ELEMENT: final StartElement childElement = xmlParserEvent.asStartElement(); ModelNode childNode = addNewChildNode(nsVersion, node, childElement); String value = unmarshalNodeContent(nsVersion, childNode, childElement.getName(), reader); if (childNode.isDomainSpecific()) { parseAssertionData(nsVersion, value, childNode, childElement); } break; default: throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0011_UNABLE_TO_UNMARSHALL_POLICY_XML_ELEM_EXPECTED())); } } catch (XMLStreamException e) { throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e)); } } return (valueBuffer == null) ? null : valueBuffer.toString().trim(); }
@Override public <T> JAXBElement<T> unmarshal(XMLEventReader reader, Class<T> expectedType) throws JAXBException { if(expectedType==null) { throw new IllegalArgumentException(); } return (JAXBElement)unmarshal0(reader,getBeanInfo(expectedType)); }
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.internal.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); } }
/** * DTDEvent instances constructed via event reader are missing the notation * and entity declaration information */ @Test public void testDTDEvent() { String XML = "<?xml version='1.0' ?>" + "<!DOCTYPE root [\n" + "<!ENTITY intEnt 'internal'>\n" + "<!ENTITY extParsedEnt SYSTEM 'url:dummy'>\n" + "<!NOTATION notation PUBLIC 'notation-public-id'>\n" + "<!NOTATION notation2 SYSTEM 'url:dummy'>\n" + "<!ENTITY extUnparsedEnt SYSTEM 'url:dummy2' NDATA notation>\n" + "]>" + "<root />"; try { XMLEventReader er = getReader(XML); XMLEvent evt = er.nextEvent(); // StartDocument evt = er.nextEvent(); // DTD if (evt.getEventType() != XMLStreamConstants.DTD) { Assert.fail("Expected DTD event"); } DTD dtd = (DTD) evt; List entities = dtd.getEntities(); if (entities == null) { Assert.fail("No entity found. Expected 3."); } else { Assert.assertEquals(entities.size(), 3); } // Let's also verify they are all of right type... testListElems(entities, EntityDeclaration.class); List notations = dtd.getNotations(); if (notations == null) { Assert.fail("No notation found. Expected 2."); } else { Assert.assertEquals(notations.size(), 2); } // Let's also verify they are all of right type... testListElems(notations, NotationDeclaration.class); } catch (Exception e) { Assert.fail(e.getMessage()); } }
@Test public void testNotReplacing() throws Exception { JAXPTestUtilities.tryRunWithTmpPermission(() -> { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty("javax.xml.stream.isReplacingEntityReferences", false); StringReader sr = new StringReader(XML); XMLEventReader reader = factory.createXMLEventReader(sr); boolean sawUndef = false; boolean sawDef = false; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); // System.out.println("Event: " + event); if (event.isEntityReference()) { EntityReference ref = (EntityReference) event; if ("def".equals(ref.getName())) { sawDef = true; } else if ("undef".equals(ref.getName())) { sawUndef = true; } else { throw new IllegalArgumentException("Unexpected entity name"); } } } Assert.assertEquals(true, sawDef); Assert.assertEquals(true, sawUndef); reader.close(); }, new FilePermission("/tmp/this/does/not/exist/but/that/is/ok", "read")); }
@Test public void testEventReader1() { try { // Check if event reader returns the correct event XMLEventReader e1 = inputFactory.createXMLEventReader(inputFactory.createXMLStreamReader(new java.io.StringReader(xml))); Assert.assertEquals(e1.peek().getEventType(), XMLStreamConstants.START_DOCUMENT); // Repeat same steps to test factory state XMLEventReader e2 = inputFactory.createXMLEventReader(inputFactory.createXMLStreamReader(new java.io.StringReader(xml))); Assert.assertEquals(e2.peek().getEventType(), XMLStreamConstants.START_DOCUMENT); } catch (Exception e) { Assert.fail(e.getMessage()); } }
public StAXInputSource(XMLEventReader source, boolean consumeRemainingContent) { super(null, getEventReaderSystemId(source), null); if (source == null) { throw new IllegalArgumentException("XMLEventReader parameter cannot be null."); } fStreamReader = null; fEventReader = source; fConsumeRemainingContent = consumeRemainingContent; }
private static String getEventReaderSystemId(XMLEventReader reader) { try { if (reader != null) { return reader.peek().getLocation().getSystemId(); } } catch (XMLStreamException e) {} return null; }
StaxXMLInputSource getStaxInputSource(Object object){ if(object == null) return null ; if(object instanceof java.io.InputStream){ return new StaxXMLInputSource(new XMLInputSource(null, null, null, (InputStream)object, null)); } else if(object instanceof XMLStreamReader){ return new StaxXMLInputSource((XMLStreamReader)object) ; }else if(object instanceof XMLEventReader){ return new StaxXMLInputSource((XMLEventReader)object) ; } return null ; }
@Test(dataProvider = "xml-data") public void testEventReader(String xml, int chunkSize, int expectedNumOfChunks, boolean withinLimit) throws Exception { XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty("http://java.sun.com/xml/stream/properties/report-cdata-event", true); if (chunkSize > 0) { xif.setProperty(CDATA_CHUNK_SIZE, chunkSize); } XMLEventReader reader = xif.createXMLEventReader(new StringReader(xml)); StringBuilder cdata = new StringBuilder(); int numOfChunks = 0; boolean isWithinLimit = true; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); //All text events get reported as Characters events if (event.getEventType() == XMLStreamConstants.CHARACTERS) { Characters cdataEvent = (Characters) event; if (cdataEvent.isCData()) { String text = cdataEvent.getData(); numOfChunks++; if (text.length() > chunkSize) { isWithinLimit = false; } debugPrint("\nCDATA: " + text.length()); cdata.append(text); } } } debugPrint("CData in single chunk:" + cdata.toString().length()); Assert.assertEquals(numOfChunks, expectedNumOfChunks); Assert.assertEquals(isWithinLimit, withinLimit); }
@Test public void test() { try { XMLInputFactory xif = XMLInputFactory.newInstance(); XMLEventReader reader = xif.createXMLEventReader(this.getClass().getResourceAsStream("xml11.xml.data")); while (reader.hasNext()) reader.next(); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.toString()); } }