public static String readUntilEndElement(String endElementName, XMLStreamReader reader, XmlEventHandler eventHandler) throws XMLStreamException { String text = null; int event; while (!((event = reader.next()) == XMLStreamConstants.END_ELEMENT && reader.getLocalName().equals(endElementName))) { text = null; switch (event) { case XMLStreamConstants.START_ELEMENT: if (eventHandler != null) { eventHandler.onStartElement(); } break; case XMLStreamConstants.CHARACTERS: text = reader.getText(); break; default: break; } } return text; }
/** * Processes a GateDocumentFeatures or Annotation element to build a * feature map. The element is expected to contain Feature children, * each with a Name and Value. The reader will be returned positioned * on the closing GateDocumentFeatures or Annotation tag. * * @throws XMLStreamException */ public static FeatureMap readFeatureMap(XMLStreamReader xsr) throws XMLStreamException { FeatureMap fm = Factory.newFeatureMap(); while(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) { xsr.require(XMLStreamConstants.START_ELEMENT, null, "Feature"); Object featureName = null; Object featureValue = null; while(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) { if("Name".equals(xsr.getLocalName())) { featureName = readFeatureNameOrValue(xsr); } else if("Value".equals(xsr.getLocalName())) { featureValue = readFeatureNameOrValue(xsr); } else { throw new XMLStreamException("Feature element should contain " + "only Name and Value children", xsr.getLocation()); } } fm.put(featureName, featureValue); } return fm; }
@Test public void testRootElementNamespace() { is = new java.io.ByteArrayInputStream(getXML().getBytes()); try { XMLStreamReader sr = factory.createFilteredReader(factory.createXMLStreamReader(is), (StreamFilter) filter); while (sr.hasNext()) { int eventType = sr.next(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (sr.getLocalName().equals(rootElement)) { Assert.assertTrue(sr.getNamespacePrefix(0).equals(prefixApple) && sr.getNamespaceURI(0).equals(namespaceURIApple)); } } } } catch (Exception ex) { Assert.fail("Exception: " + ex.getMessage()); } }
@Override public void accept(XMLStreamReader xr) { if((xr.getEventType() == XMLStreamConstants.START_ELEMENT) && xr.getLocalName().equals("cvParam")) { if (xr.getAttributeValue(null, "accession").equals("MS:1000511")) { this.currHeader.setMsLevel(Integer.valueOf(xr.getAttributeValue(null, "value"))); } else if(xr.getAttributeValue(null, "accession").equals("MS:1000016")) { // normalize to seconds if unit is a minute double norm = xr.getAttributeValue(null, "unitAccession") .equals("UO:0000031") ? 60.0 : 1.0; this.currHeader.setScanStartTime(norm * Double.valueOf(xr.getAttributeValue(null, "value"))); } else if(xr.getAttributeValue(null, "accession").equals("MS:1000744")) { this.currHeader.setSelectedIonMz(Double.valueOf(xr.getAttributeValue(null, "value"))); } else if(xr.getAttributeValue(null, "accession").equals("MS:1000041")) { this.currHeader.setSelectedIonCharge(Integer.valueOf(xr.getAttributeValue(null, "value"))); } else if(xr.getAttributeValue(null, "accession").equals("MS:1000042")) { this.currHeader.setSelectedIonIntensity(Double.valueOf(xr.getAttributeValue(null, "value"))); } } }
@Override protected int pullNextEvent() { try { switch (in.next()) { case XMLStreamConstants.START_DOCUMENT: case XMLStreamConstants.START_ELEMENT: return START_NODE; case XMLStreamConstants.END_DOCUMENT: case XMLStreamConstants.END_ELEMENT: return END_NODE; case XMLStreamConstants.CHARACTERS: return TEXT; case XMLStreamConstants.COMMENT: return COMMENT; default: return OTHER; } } catch (final XMLStreamException e) { throw new StreamException(e); } }
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 ); } }
/** * {@inheritDoc} */ @Override public int nextTag() throws XMLStreamException { int tag = super.nextTag(); if (tracing) { switch (tag) { case XMLStreamConstants.START_ELEMENT: System.err.println("[" + getLocalName()); break; case XMLStreamConstants.END_ELEMENT: System.err.println(getLocalName() + "]"); break; default: System.err.println((tagStrings.containsKey(tag)) ? tagStrings.get(tag) : "Weird tag: " + tag); break; } } return tag; }
@Test public void testPITargetAndData() { try { XMLInputFactory xif = XMLInputFactory.newInstance(); String PITarget = "soffice"; String PIData = "WebservicesArchitecture"; String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<?" + PITarget + " " + PIData + "?>" + "<foo></foo>"; // System.out.println("XML = " + xml) ; InputStream is = new java.io.ByteArrayInputStream(xml.getBytes()); XMLStreamReader sr = xif.createXMLStreamReader(is); while (sr.hasNext()) { int eventType = sr.next(); if (eventType == XMLStreamConstants.PROCESSING_INSTRUCTION) { String target = sr.getPITarget(); String data = sr.getPIData(); Assert.assertTrue(target.equals(PITarget) && data.equals(PIData)); } } } catch (Exception ex) { ex.printStackTrace(); } }
/** * Parses the handler and role information and sets it * on the {@link WSBinding}. * * @return true if <handler-chains> element present in DD * false otherwise. */ protected boolean setHandlersAndRoles(WSBinding binding, XMLStreamReader reader, QName serviceName, QName portName) { if (reader.getEventType() == XMLStreamConstants.END_ELEMENT || !reader.getName().equals(HandlerChainsModel.QNAME_HANDLER_CHAINS)) { return false; } HandlerAnnotationInfo handlerInfo = HandlerChainsModel.parseHandlerFile( reader, classLoader, serviceName, portName, binding); binding.setHandlerChain(handlerInfo.getHandlers()); if (binding instanceof SOAPBinding) { ((SOAPBinding) binding).setRoles(handlerInfo.getRoles()); } // move past </handler-chains> XMLStreamReaderUtil.nextContent(reader); return true; }
@Test public void testNamespaceContext() { try { XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); InputStream is = new java.io.ByteArrayInputStream(getXML().getBytes()); XMLStreamReader sr = xif.createXMLStreamReader(is); while (sr.hasNext()) { int eventType = sr.next(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (sr.getLocalName().equals(childElement)) { NamespaceContext context = sr.getNamespaceContext(); Assert.assertTrue(context.getPrefix(namespaceURI).equals(prefix)); } } } } catch (Exception ex) { ex.printStackTrace(); } }
/** * CR 6631264 / sjsxp Issue 45: * https://sjsxp.dev.java.net/issues/show_bug.cgi?id=45 * XMLStreamReader.hasName() should return false for ENTITY_REFERENCE */ @Test public void testHasNameOnEntityEvent() throws Exception { XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false); XMLStreamReader r = xif.createXMLStreamReader( this.getClass().getResourceAsStream("ExternalDTD.xml")); while (r.next() != XMLStreamConstants.ENTITY_REFERENCE) { System.out.println("event type: " + r.getEventType()); continue; } if (r.hasName()) { System.out.println("hasName returned true on ENTITY_REFERENCE event."); } Assert.assertFalse(r.hasName()); // fails }
/** * Creates a new {@link javax.xml.transform.Source} for the given * {@link XMLStreamReader}. * * The XMLStreamReader must be pointing at either a * {@link javax.xml.stream.XMLStreamConstants#START_DOCUMENT} or * {@link javax.xml.stream.XMLStreamConstants#START_ELEMENT} event. * * @param reader XMLStreamReader that will be exposed as a Source * @param eagerQuit if true, when the conversion is completed, leave the cursor to the last * event that was fired (such as end element) * @param inscope inscope Namespaces * array of the even length of the form { prefix0, uri0, prefix1, uri1, ... } * @throws IllegalArgumentException iff the reader is null * @throws IllegalStateException iff the reader is not pointing at either a * START_DOCUMENT or START_ELEMENT event */ public StAXSource(XMLStreamReader reader, boolean eagerQuit, @NotNull String[] inscope) { if( reader == null ) throw new IllegalArgumentException(); this.staxReader = reader; int eventType = reader.getEventType(); if (!(eventType == XMLStreamConstants.START_DOCUMENT) && !(eventType == XMLStreamConstants.START_ELEMENT)) { throw new IllegalStateException(); } this.reader = new XMLStreamReaderToContentHandler(reader,repeater,eagerQuit,false,inscope); super.setXMLReader(pseudoParser); // pass a dummy InputSource. We don't care super.setInputSource(new InputSource()); }
@Test public void testReadingNamespace() { is = new java.io.ByteArrayInputStream(getXML().getBytes()); try { XMLStreamReader sr = factory.createFilteredReader(factory.createXMLStreamReader(is), (StreamFilter) filter); while (sr.hasNext()) { int eventType = sr.getEventType(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (sr.getLocalName().equals(rootElement)) { Assert.assertTrue(sr.getNamespacePrefix(0).equals(prefixApple) && sr.getNamespaceURI(0).equals(namespaceURIApple)); } } eventType = sr.next(); } } catch (Exception ex) { Assert.fail("Exception: " + ex.getMessage()); } }
protected List getNotationDecls(){ if(fEventType == XMLStreamConstants.DTD){ if(fScanner.fDTDScanner == null) return null; DTDGrammar grammar = ((XMLDTDScannerImpl)(fScanner.fDTDScanner)).getGrammar(); if(grammar == null) return null; List notations = grammar.getNotationDecls(); Iterator it = notations.iterator(); ArrayList list = new ArrayList(); while(it.hasNext()){ XMLNotationDecl ni = (XMLNotationDecl)it.next(); if(ni!= null){ list.add(new NotationDeclarationImpl(ni)); } } return list; } return null; }
/** * @bug 8152530 * Verifies that StAXSource handles empty namespace properly. NPE was thrown * before the fix. * @throws Exception if the test fails */ @Test public final void testStAXSourceWEmptyNS() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<EntityList>\n" + " <Entity xmlns=\"\">\n" + " </Entity>\n" + " <Entity xmlns=\"\">\n" + " </Entity>\n" + "</EntityList> "; XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml)); xsr.nextTag(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT && xsr.getLocalName().equals("Entity")) { StringWriter stringResult = new StringWriter(); t.transform(new StAXSource(xsr), new StreamResult(stringResult)); System.out.println("result: \n" + stringResult.toString()); } }
/** * Returns the text contents of the current element being parsed. * * @return The text contents of the current element being parsed. */ public String readText() throws XMLStreamException { if (isInsideResponseHeader()) { return getHeader(currentHeader); } if (currentEvent.isAttribute()) { Attribute attribute = (Attribute) currentEvent; return attribute.getValue(); } StringBuilder sb = new StringBuilder(); while (true) { XMLEvent event = eventReader.peek(); if (event.getEventType() == XMLStreamConstants.CHARACTERS) { eventReader.nextEvent(); sb.append(event.asCharacters().getData()); } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) { return sb.toString(); } else { throw new RuntimeException("Encountered unexpected event: " + event.toString()); } } }
@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 testChildElementNamespace() { is = new java.io.ByteArrayInputStream(getXML().getBytes()); try { XMLStreamReader sr = factory.createFilteredReader(factory.createXMLStreamReader(is), (StreamFilter) filter); while (sr.hasNext()) { int eventType = sr.next(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (sr.getLocalName().equals(childElement)) { QName qname = sr.getName(); Assert.assertTrue(qname.getPrefix().equals(prefixApple) && qname.getNamespaceURI().equals(namespaceURIApple) && qname.getLocalPart().equals(childElement)); } } } } catch (Exception ex) { Assert.fail("Exception: " + ex.getMessage()); } }
@Test public void testNamespaceCount() { try { XMLInputFactory xif = XMLInputFactory.newInstance(); xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); InputStream is = new java.io.ByteArrayInputStream(getXML().getBytes()); XMLStreamReader sr = xif.createXMLStreamReader(is); while (sr.hasNext()) { int eventType = sr.next(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (sr.getLocalName().equals(rootElement)) { int count = sr.getNamespaceCount(); Assert.assertTrue(count == 1); } } } } catch (Exception ex) { ex.printStackTrace(); } }
@Test public void testStreamReader() { XMLInputFactory ifac = XMLInputFactory.newInstance(); XMLOutputFactory ofac = XMLOutputFactory.newInstance(); try { ifac.setProperty(ifac.IS_REPLACING_ENTITY_REFERENCES, new Boolean(false)); XMLStreamReader re = ifac.createXMLStreamReader(this.getClass().getResource(INPUT_FILE).toExternalForm(), this.getClass().getResourceAsStream(INPUT_FILE)); while (re.hasNext()) { int event = re.next(); if (event == XMLStreamConstants.START_ELEMENT && re.getLocalName().equals("bookurn")) { Assert.assertTrue(re.getAttributeCount() == 0, "No attributes are expected for <bookurn> "); Assert.assertTrue(re.getNamespaceCount() == 2, "Two namespaces are expected for <bookurn> "); } } } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception occured: " + e.getMessage()); } }
/** * Verifies that after switching to a different XML Version (1.1), the parser * is initialized properly (the listener was not registered in this case). * * @param path the path to XML source * @throws Exception */ @Test(dataProvider = "getPaths") public void testSwitchXMLVersions(String path) throws Exception { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty("javax.xml.stream.isCoalescing", true); XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader( this.getClass().getResourceAsStream(path)); while (xmlStreamReader.hasNext()) { int event = xmlStreamReader.next(); if (event == XMLStreamConstants.START_ELEMENT) { if (xmlStreamReader.getLocalName().equals("body")) { String elementText = xmlStreamReader.getElementText(); Assert.assertTrue(!elementText.contains("</body>"), "Fail: elementText contains </body>"); } } } }
@Test public void testDefaultAttrNS() { XMLInputFactory ifac = XMLInputFactory.newInstance(); try { XMLStreamReader re = ifac.createXMLStreamReader(getClass().getResource(INPUT_FILE1).toExternalForm(), this.getClass().getResourceAsStream(INPUT_FILE1)); while (re.hasNext()) { int event = re.next(); if (event == XMLStreamConstants.START_ELEMENT) { // System.out.println("#attrs = " + re.getAttributeCount()); Assert.assertTrue(re.getAttributeCount() == 2); // This works if "" is replaced by null too // System.out.println("attr1 = " + re.getAttributeValue("", // "attr1")); Assert.assertTrue(re.getAttributeValue("", "attr1").equals("pass")); } } re.close(); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception occured: " + e.getMessage()); } }
@Test public void testAttributeCountNS() { XMLInputFactory ifac = XMLInputFactory.newInstance(); try { // Turn on NS awareness to not count xmlns as attributes ifac.setProperty("javax.xml.stream.isNamespaceAware", Boolean.TRUE); XMLStreamReader re = ifac.createXMLStreamReader(getClass().getResource(INPUT_FILE1).toExternalForm(), this.getClass().getResourceAsStream(INPUT_FILE1)); while (re.hasNext()) { int event = re.next(); if (event == XMLStreamConstants.START_ELEMENT) { // System.out.println("#attrs = " + re.getAttributeCount()); Assert.assertTrue(re.getAttributeCount() == 1); } } re.close(); } catch (Exception e) { e.printStackTrace(); Assert.fail("Exception occured: " + e.getMessage()); } }
protected List<NotationDeclaration> getNotationDecls() { if (fEventType == XMLStreamConstants.DTD) { if (fScanner.fDTDScanner == null) { return null; } DTDGrammar grammar = ((XMLDTDScannerImpl) (fScanner.fDTDScanner)).getGrammar(); if (grammar == null) { return null; } List<XMLNotationDecl> notations = grammar.getNotationDecls(); ArrayList<NotationDeclaration> list = new ArrayList<>(); for (XMLNotationDecl notation : notations) { if (notation != null) { list.add(new NotationDeclarationImpl(notation)); } } return list; } return null; }
@Test(dataProvider = "xml-data") public void testStAX(String xml, int chunkSize, int expectedNumOfChunks, boolean withinLimit) throws Exception { XMLInputFactory xifactory = XMLInputFactory.newInstance(); xifactory.setProperty("http://java.sun.com/xml/stream/properties/report-cdata-event", true); if (chunkSize > 0) { xifactory.setProperty(CDATA_CHUNK_SIZE, chunkSize); } XMLStreamReader streamReader = xifactory.createXMLStreamReader(new StringReader(xml)); StringBuilder cdata = new StringBuilder(); int numOfChunks = 0; boolean isWithinLimit = true; while (streamReader.hasNext()) { int eventType = streamReader.next(); switch (eventType) { case XMLStreamConstants.START_ELEMENT: debugPrint("\nElement: " + streamReader.getLocalName()); break; case XMLStreamConstants.CDATA: String text = streamReader.getText(); numOfChunks++; if (text.length() > chunkSize) { isWithinLimit = false; } debugPrint("\nCDATA: " + text.length()); cdata.append(text); break; case XMLStreamConstants.CHARACTERS: debugPrint("\nCharacters: " + streamReader.getText().length()); break; } } debugPrint("CData in single chunk:" + cdata.toString().length()); Assert.assertEquals(numOfChunks, expectedNumOfChunks); Assert.assertEquals(isWithinLimit, withinLimit); }
/** * Method for parsing orders XML. * @param is input stream for parsing. * @return SortedMap of OrderBook's mapping key name. * @throws FileNotFoundException if there is no such file. * @throws XMLStreamException The base exception for unexpected processing errors. This Exception * class is used to report well-formedness errors as well as unexpected * processing conditions. */ public SortedMap<String, OrderBook> parse(InputStream is) throws FileNotFoundException, XMLStreamException { SortedMap<String, OrderBook> orders = new TreeMap<>(String::compareTo); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader reader = factory.createXMLStreamReader(is); OrderBook orderBook; String book; reader.next(); while (reader.hasNext()) { if (reader.next() == XMLStreamConstants.START_ELEMENT) { if (reader.isStartElement()) { book = reader.getAttributeValue(null, "book"); if ("AddOrder".equals(reader.getLocalName())) { if (!orders.containsKey(book)) { orderBook = new OrderBook(book); orders.put(book, orderBook); } else { orderBook = orders.get(book); } orderBook.addOrder(OrderBook.OPERATION.valueOf(reader.getAttributeValue(null, "operation")), Integer.parseInt(reader.getAttributeValue(null, "orderId")), Integer.parseInt(reader.getAttributeValue(null, "volume")), Float.parseFloat(reader.getAttributeValue(null, "price"))); } else { orders.get(book).delOrder(Integer.parseInt(reader.getAttributeValue(null, "orderId"))); } } } } return orders; }
/** * Get the human readable event name for the numeric event id */ public static String getEventName(int eventId) { switch (eventId) { case XMLStreamConstants.START_ELEMENT: return "StartElementEvent"; case XMLStreamConstants.END_ELEMENT: return "EndElementEvent"; case XMLStreamConstants.PROCESSING_INSTRUCTION: return "ProcessingInstructionEvent"; case XMLStreamConstants.CHARACTERS: return "CharacterEvent"; case XMLStreamConstants.COMMENT: return "CommentEvent"; case XMLStreamConstants.START_DOCUMENT: return "StartDocumentEvent"; case XMLStreamConstants.END_DOCUMENT: return "EndDocumentEvent"; case XMLStreamConstants.ENTITY_REFERENCE: return "EntityReferenceEvent"; case XMLStreamConstants.ATTRIBUTE: return "AttributeBase"; case XMLStreamConstants.DTD: return "DTDEvent"; case XMLStreamConstants.CDATA: return "CDATA"; } return "UNKNOWN_EVENT_TYPE"; }
/** * Close the current tag, but accept some alternative elements first. * * @param tag The expected tag to close. * @param others Alternate elements to accept. * @exception XMLStreamException if a closing tag is not found. */ public void closeTag(String tag, String... others) throws XMLStreamException { for (int next = nextTag(); next != XMLStreamConstants.END_ELEMENT; next = nextTag()) { String at = find(others, s -> atTag(s)); if (at == null) { throw new XMLStreamException("Parse error, END_ELEMENT(" + tag + " or alternatives) expected, not: " + getLocalName()); } closeTag(at); } expectTag(tag); }
/** * Get the attributes associated with the given START_ELEMENT or ATTRIBUTE * StAXevent. * * @return the StAX attributes converted to an org.xml.sax.Attributes */ private Attributes getAttributes() { AttributesImpl attrs = new AttributesImpl(); int eventType = staxStreamReader.getEventType(); if (eventType != XMLStreamConstants.ATTRIBUTE && eventType != XMLStreamConstants.START_ELEMENT) { throw new InternalError( "getAttributes() attempting to process: " + eventType); } // in SAX, namespace declarations are not part of attributes by default. // (there's a property to control that, but as far as we are concerned // we don't use it.) So don't add xmlns:* to attributes. // gather non-namespace attrs for (int i = 0; i < staxStreamReader.getAttributeCount(); i++) { String uri = staxStreamReader.getAttributeNamespace(i); if(uri==null) uri=""; String localName = staxStreamReader.getAttributeLocalName(i); String prefix = staxStreamReader.getAttributePrefix(i); String qName; if(prefix==null || prefix.length()==0) qName = localName; else qName = prefix + ':' + localName; String type = staxStreamReader.getAttributeType(i); String value = staxStreamReader.getAttributeValue(i); attrs.addAttribute(uri, localName, qName, type, value); } return attrs; }
public StartDocumentEvent(String encoding, String version){ if (encoding != null) { _encoding = encoding; _encodingSet = true; } if (version != null) _version = version; setEventType(XMLStreamConstants.START_DOCUMENT); }
@Nullable public String getAttribute(@NotNull String nsUri, @NotNull String localName) { try { XMLStreamReader sr = epr.read("EndpointReference"/*doesn't matter*/); while(sr.getEventType()!= XMLStreamConstants.START_ELEMENT) sr.next(); return sr.getAttributeValue(nsUri,localName); } catch (XMLStreamException e) { // since we are reading from buffer, this can't happen. throw new AssertionError(e); } }
@Test public void testSkippingExternalDTD() throws Exception { XMLInputFactory xif = XMLInputFactory.newInstance(); try( InputStream is= getClass().getResourceAsStream("XMLSchema.xsd"); ) { XMLStreamReader reader = xif.createXMLStreamReader(getClass().getResource("XMLSchema.xsd").getFile(), is); int e; while ((e = reader.next()) == XMLStreamConstants.COMMENT); Assert.assertEquals(e, XMLStreamConstants.DTD, "should be DTD"); reader.nextTag(); Assert.assertEquals(reader.getLocalName(), "schema", "next tag should be schema"); } }
protected void init(String encoding, String version, boolean standalone,Location loc) { setEventType(XMLStreamConstants.START_DOCUMENT); this.fEncodingScheam = encoding; this.fVersion = version; this.fStandalone = standalone; if (encoding != null && !encoding.equals("")) this.fEncodingSchemeSet = true; else { this.fEncodingSchemeSet = false; this.fEncodingScheam = "UTF-8"; } this.fLocation = loc; }
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(); }
/** * <p>Creates a new instance of a <code>StAXSource</code> * by supplying an {@link XMLEventReader}.</p> * * <p><code>XMLEventReader</code> must be a * non-<code>null</code> reference.</p> * * <p><code>XMLEventReader</code> must be in * {@link XMLStreamConstants#START_DOCUMENT} or * {@link XMLStreamConstants#START_ELEMENT} state.</p> * * @param xmlEventReader <code>XMLEventReader</code> used to create * this <code>StAXSource</code>. * * @throws XMLStreamException If <code>xmlEventReader</code> access * throws an <code>Exception</code>. * @throws IllegalArgumentException If <code>xmlEventReader</code> == * <code>null</code>. * @throws IllegalStateException If <code>xmlEventReader</code> * is not in <code>XMLStreamConstants.START_DOCUMENT</code> or * <code>XMLStreamConstants.START_ELEMENT</code> state. */ public StAXSource(final XMLEventReader xmlEventReader) throws XMLStreamException { if (xmlEventReader == null) { throw new IllegalArgumentException( "StAXSource(XMLEventReader) with XMLEventReader == null"); } // TODO: This is ugly ... // there is no way to know the current position(event) of // XMLEventReader. peek() is the only way to know the next event. // The next event on the input stream should be // XMLStreamConstants.START_DOCUMENT or // XMLStreamConstants.START_ELEMENT. XMLEvent event = xmlEventReader.peek(); int eventType = event.getEventType(); if (eventType != XMLStreamConstants.START_DOCUMENT && eventType != XMLStreamConstants.START_ELEMENT) { throw new IllegalStateException( "StAXSource(XMLEventReader) with XMLEventReader " + "not in XMLStreamConstants.START_DOCUMENT or " + "XMLStreamConstants.START_ELEMENT state"); } this.xmlEventReader = xmlEventReader; systemId = event.getLocation().getSystemId(); }
public static void toNextTag(XMLStreamReader reader, QName name) { // skip any whitespace if (reader.getEventType() != XMLStreamConstants.START_ELEMENT && reader.getEventType() != XMLStreamConstants.END_ELEMENT) { XMLStreamReaderUtil.nextElementContent(reader); } if(reader.getEventType() == XMLStreamConstants.END_ELEMENT && name.equals(reader.getName())) { XMLStreamReaderUtil.nextElementContent(reader); } }
private boolean post(QName tagName, XMLStreamReader xsr, boolean result) { if(!tagName.equals(xsr.getName())) return foundFool(); if(result) { if(xsr.getEventType()!=XMLStreamConstants.END_ELEMENT) foundFool(); } else { if(xsr.getEventType()!=XMLStreamConstants.START_ELEMENT) foundFool(); } return result; }