List of usage examples for javax.xml.stream XMLStreamReader getLocation
public Location getLocation();
From source file:MainClass.java
public static void main(String[] args) throws Exception { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader reader = inputFactory.createXMLStreamReader(new FileInputStream(new File("test.xml"))); int eventTypeID = reader.nextTag(); reader.require(XMLStreamConstants.START_ELEMENT, null, "person"); eventTypeID = reader.nextTag();/* ww w.ja v a 2 s . c o m*/ try { reader.require(XMLStreamConstants.START_ELEMENT, null, "first_name"); } catch (XMLStreamException e) { System.out.println("Assertion failed. " + e.getMessage() + " at " + reader.getLocation().getLineNumber() + ":" + reader.getLocation().getColumnNumber()); } System.out.println(reader.getElementText()); }
From source file:Main.java
/** * Skip current element, including all its content. * Precondition: the current event is START_ELEMENT. * Postcondition: the current event is the corresponding END_ELEMENT. * Similar to {@link XMLStreamReader#nextTag()}, but also skips text content. * @param reader must not be {@code null} * @throws XMLStreamException if the current event is not START_ELEMENT or there is an error processing the underlying XML source *//*w w w.j a v a2s . com*/ public static void skipElement(XMLStreamReader reader) throws XMLStreamException { if (reader.getEventType() != START_ELEMENT) throw new XMLStreamException("expected start of element", reader.getLocation()); int depth = 0; while (reader.hasNext()) { int event = reader.next(); if (event == START_ELEMENT) { ++depth; } else if (event == END_ELEMENT) { --depth; if (depth == -1) break; } } }
From source file:Main.java
/** * Test if the current event is an element tag with the given namespace and name. * If the namespace URI is null it is not checked for equality, * if the local name is null it is not checked for equality. * @param reader must not be {@code null} * @param event START_ELEMENT or END_ELEMENT * @param uri the namespace URI of the element, may be null * @param name the local name of the element, may be null * @param slash "" or "/", for error message * @throws XMLStreamException if the required values are not matched. *//*from w w w.j a va 2s . com*/ private static void requireElement(XMLStreamReader reader, int event, String uri, String name, String slash) throws XMLStreamException { // Note: reader.require(event, uri, name) has a lousy error message if (reader.getEventType() != event) throw new XMLStreamException("expected <" + slash + name + ">", reader.getLocation()); if (uri != null) { String found = reader.getNamespaceURI(); if (!found.equals(uri)) throw new XMLStreamException( "expected <" + slash + name + "> with namespace [" + uri + "], found [" + found + "]", reader.getLocation()); } if (name != null) { String found = reader.getLocalName(); if (!found.equals(name)) throw new XMLStreamException("expected <" + slash + name + ">, found <" + slash + found + ">", reader.getLocation()); } }
From source file:XmlStreamUtils.java
public static String printEvent(XMLStreamReader xmlr) { StringBuffer b = new StringBuffer(); b.append("EVENT:[" + xmlr.getLocation().getLineNumber() + "][" + xmlr.getLocation().getColumnNumber() + "] "); b.append(getName(xmlr.getEventType())); b.append(" ["); switch (xmlr.getEventType()) { case XMLStreamReader.START_ELEMENT: b.append("<"); printName(xmlr, b);/*from w w w . ja va 2 s . co m*/ for (int i = 0; i < xmlr.getNamespaceCount(); i++) { b.append(" "); String n = xmlr.getNamespacePrefix(i); if ("xmlns".equals(n)) { b.append("xmlns=\"" + xmlr.getNamespaceURI(i) + "\""); } else { b.append("xmlns:" + n); b.append("=\""); b.append(xmlr.getNamespaceURI(i)); b.append("\""); } } for (int i = 0; i < xmlr.getAttributeCount(); i++) { b.append(" "); printName(xmlr.getAttributePrefix(i), xmlr.getAttributeNamespace(i), xmlr.getAttributeLocalName(i), b); b.append("=\""); b.append(xmlr.getAttributeValue(i)); b.append("\""); } b.append(">"); break; case XMLStreamReader.END_ELEMENT: b.append("</"); printName(xmlr, b); for (int i = 0; i < xmlr.getNamespaceCount(); i++) { b.append(" "); String n = xmlr.getNamespacePrefix(i); if ("xmlns".equals(n)) { b.append("xmlns=\"" + xmlr.getNamespaceURI(i) + "\""); } else { b.append("xmlns:" + n); b.append("=\""); b.append(xmlr.getNamespaceURI(i)); b.append("\""); } } b.append(">"); break; case XMLStreamReader.SPACE: case XMLStreamReader.CHARACTERS: // b.append(xmlr.getText()); int start = xmlr.getTextStart(); int length = xmlr.getTextLength(); b.append(new String(xmlr.getTextCharacters(), start, length)); break; case XMLStreamReader.PROCESSING_INSTRUCTION: String target = xmlr.getPITarget(); if (target == null) target = ""; String data = xmlr.getPIData(); if (data == null) data = ""; b.append("<?"); b.append(target + " " + data); b.append("?>"); break; case XMLStreamReader.CDATA: b.append("<![CDATA["); if (xmlr.hasText()) b.append(xmlr.getText()); b.append("]]>"); break; case XMLStreamReader.COMMENT: b.append("<!--"); if (xmlr.hasText()) b.append(xmlr.getText()); b.append("-->"); break; case XMLStreamReader.ENTITY_REFERENCE: b.append(xmlr.getLocalName() + "="); if (xmlr.hasText()) b.append("[" + xmlr.getText() + "]"); break; case XMLStreamReader.START_DOCUMENT: b.append("<?xml"); b.append(" version='" + xmlr.getVersion() + "'"); b.append(" encoding='" + xmlr.getCharacterEncodingScheme() + "'"); if (xmlr.isStandalone()) b.append(" standalone='yes'"); else b.append(" standalone='no'"); b.append("?>"); break; } b.append("]"); return b.toString(); }
From source file:com.evolveum.midpoint.common.validator.Validator.java
private EventResult readFromStreamAndValidate(XMLStreamReader stream, OperationResult objectResult, Map<String, String> rootNamespaceDeclarations, OperationResult validatorResult) { objectResult.addContext(START_LINE_NUMBER, stream.getLocation().getLineNumber()); Document objectDoc;//from ww w . j a va2 s.c o m try { // Parse the object from stream to DOM objectDoc = domConverter.buildDocument(stream); } catch (XMLStreamException ex) { validatorResult.recordFatalError("XML parsing error: " + ex.getMessage(), ex); if (handler != null) { handler.handleGlobalError(validatorResult); } objectResult.recordFatalError(ex); return EventResult.skipObject(); } objectResult.addContext(END_LINE_NUMBER, stream.getLocation().getLineNumber()); // This element may not have complete namespace definitions for a // stand-alone // processing, therefore copy namespace definitions from the root // element Element objectElement = DOMUtil.getFirstChildElement(objectDoc); DOMUtil.setNamespaceDeclarations(objectElement, rootNamespaceDeclarations); return validateObjectInternal(objectElement, objectResult, validatorResult); }
From source file:de.codesourcery.eve.skills.util.XMLMapper.java
public <T> Collection<T> read(Class<T> clasz, IFieldConverters converters, InputStream instream) throws XMLStreamException, IOException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException { final Collection<T> result = new ArrayList<T>(); try {//from ww w.j av a2 s . c o m final BeanDescription desc = createBeanDescription(clasz); /* * Create inverse mapping attribute name -> field. */ final Map<String, Field> inverseMapping = new HashMap<String, Field>(); if (!this.propertyNameMappings.isEmpty()) { // key = property name / value = attribute name for (Map.Entry<String, String> propToAttribute : this.propertyNameMappings.entrySet()) { inverseMapping.put(propToAttribute.getValue(), desc.getFieldByName(propToAttribute.getKey())); } } else { // create default mappings for (Field f : desc.getFields()) { inverseMapping.put(f.getName(), f); } } final int fieldCount = desc.getFields().size(); final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader parser = factory.createXMLStreamReader(instream); boolean inRow = false; final Constructor<T> constructor = clasz.getConstructor(new Class<?>[0]); for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) { switch (event) { case XMLStreamConstants.START_ELEMENT: if ("row".equals(parser.getLocalName())) { // parse row if (inRow) { throw new XMLStreamException("Found nested <row> tag ?", parser.getLocation()); } inRow = true; final T bean = constructor.newInstance(new Object[0]); for (int i = 0; i < fieldCount; i++) { final String attrName = parser.getAttributeLocalName(i); final String attrValue = parser.getAttributeValue(i); final Field field = inverseMapping.get(attrName); if (!NIL.equals(attrValue)) { final Object fieldValue = converters.getConverter(field) .toObject(fromAttributeValue(attrValue), field.getType()); field.set(bean, fieldValue); } else { field.set(bean, null); } } result.add(bean); } break; case XMLStreamConstants.END_ELEMENT: if ("row".equals(parser.getLocalName())) { // parse row if (!inRow) { throw new XMLStreamException("Found </row> tag without start tag at ", parser.getLocation()); } inRow = false; } break; } } } finally { instream.close(); } return result; }
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.ddi.DDIFileReader.java
private String getElementText(XMLStreamReader xmlr) throws XMLStreamException { if (xmlr.getEventType() != XMLStreamConstants.START_ELEMENT) { throw new XMLStreamException("parser must be on START_ELEMENT to read next text", xmlr.getLocation()); }/* www .j a va2 s .co m*/ int eventType = xmlr.next(); StringBuffer content = new StringBuffer(); while (eventType != XMLStreamConstants.END_ELEMENT) { if (eventType == XMLStreamConstants.CHARACTERS || eventType == XMLStreamConstants.CDATA || eventType == XMLStreamConstants.SPACE /* || eventType == XMLStreamConstants.ENTITY_REFERENCE*/) { content.append(xmlr.getText()); } else if (eventType == XMLStreamConstants.PROCESSING_INSTRUCTION || eventType == XMLStreamConstants.COMMENT || eventType == XMLStreamConstants.ENTITY_REFERENCE) { // skipping } else if (eventType == XMLStreamConstants.END_DOCUMENT) { throw new XMLStreamException("unexpected end of document when reading element text content"); } else if (eventType == XMLStreamConstants.START_ELEMENT) { throw new XMLStreamException("element text content may not contain START_ELEMENT", xmlr.getLocation()); } else { throw new XMLStreamException("Unexpected event type " + eventType, xmlr.getLocation()); } eventType = xmlr.next(); } return content.toString(); }
From source file:com.widowcrawler.exo.parse.Parser.java
public Sitemap parse(InputStream inputStream) throws XMLStreamException, SitemapParseException { final XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream, "utf-8"); final Sitemap retval = new Sitemap(new HashSet<>()); final Set<SitemapURL> sitemapURLs = new HashSet<>(); SitemapURL.Builder urlBuilder = null; String urlContent;//from w w w. j a va2 s.co m reader.getEventType(); while (reader.hasNext()) { switch (state) { case START: reader.nextTag(); if (StringUtils.equalsIgnoreCase(reader.getLocalName(), URLSET_TAG_NAME)) { state = State.URLSET; } else if (StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAPINDEX_TAG_NAME)) { state = State.SITEMAPINDEX; } else { String message = "Invalid root element. Must be either urlset or sitemapindex"; logger.error(message); throw new SitemapParseException(message); } break; case END: // consume all end tags if (reader.getEventType() != XMLStreamConstants.END_ELEMENT) { String message = decorate("There should be only one root element in each sitemap.xml", reader.getLocation()); logger.error(message); throw new SitemapParseException(message); } reader.next(); break; ///////////////////// // URLSET Hierarchy ///////////////////// case URLSET: // If we're done with the URLs, we're done overall if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) { state = State.END; break; } // Check that we're entering into a <url> element if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), URL_TAG_NAME)) { String message = "A <urlset> element can only contain <url> elements. Found: " + reader.getLocalName(); logger.error(message); throw new SitemapParseException(message); } urlBuilder = new SitemapURL.Builder(); state = State.URL; break; case URL: reader.nextTag(); if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) { //logger.info("reader.getLocalName(): " + reader.getLocalName()); switch (StringUtils.lowerCase(reader.getLocalName())) { case LOC_TAG_NAME: state = State.URL_PROP_LOC; break; case LASTMOD_TAG_NAME: state = State.URL_PROP_LASTMOD; break; case CHANGEFREQ_TAG_NAME: state = State.URL_PROP_CHANGEFREQ; break; case PRIORITY_TAG_NAME: state = State.URL_PROP_PRIORITY; break; case MOBILE_TAG_NAME: state = State.URL_PROP_MOBILE; break; default: String message = "Unexpected tag in url: " + reader.getLocalName(); logger.error(message); throw new SitemapParseException(message); } } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) { // we're done collecting the data for this URL assert urlBuilder != null; sitemapURLs.add(urlBuilder.build()); urlBuilder = new SitemapURL.Builder(); state = State.URLSET; } break; case URL_PROP_LOC: urlContent = reader.getElementText(); try { assert urlBuilder != null; urlBuilder.withLocation(new URL(StringUtils.trimToNull(urlContent))); } catch (MalformedURLException ex) { String message = String.format("Malformed URL found: %s", urlContent); logger.error(message); throw new SitemapParseException(message); } state = State.URL; break; case URL_PROP_LASTMOD: assert urlBuilder != null; urlBuilder.withLastModified(DateTime.parse(reader.getElementText())); state = State.URL; break; case URL_PROP_CHANGEFREQ: assert urlBuilder != null; urlBuilder.withChangeFrequency(ChangeFreq.valueOf(StringUtils.upperCase(reader.getElementText()))); state = State.URL; break; case URL_PROP_PRIORITY: assert urlBuilder != null; urlBuilder.withPriority(Double.valueOf(reader.getElementText())); state = State.URL; break; case URL_PROP_MOBILE: assert urlBuilder != null; urlBuilder.withIsMobileContent(true); // consume until "end tag" of self-closing tag // Also works if someone puts content in reader.getElementText(); state = State.URL; break; /////////////////////////// // SITEMAPINDEX Hierarchy /////////////////////////// case SITEMAPINDEX: // If we're done with all the Sitemaps, we're done overall if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) { state = State.END; break; } state = State.SITEMAP; break; case SITEMAP: if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAP_TAG_NAME)) { throw new SitemapParseException("A <sitemapindex> element can only contain <sitemap> elements"); } reader.nextTag(); if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) { switch (StringUtils.lowerCase(reader.getLocalName())) { case LOC_TAG_NAME: state = State.URL_PROP_LOC; break; case LASTMOD_TAG_NAME: state = State.URL_PROP_LASTMOD; break; default: throw new SitemapParseException("Unexpected tag in sitemap: " + reader.getLocalName()); } } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) { // we're done collecting the data for this URL assert urlBuilder != null; sitemapURLs.add(urlBuilder.build()); urlBuilder = new SitemapURL.Builder(); state = State.URLSET; } case SITEMAP_PROP_LOC: urlContent = reader.getElementText(); try { URL sitemapURL = new URL(StringUtils.trimToNull(urlContent)); Sitemap temp = Retry.retry(() -> { try { return Exo.parse(sitemapURL.toString()); } catch (Exception ex) { throw new RuntimeException(ex); } }); retval.merge(temp); } catch (MalformedURLException ex) { String message = String.format("Malformed URL found: %s", urlContent); logger.error(message); throw new SitemapParseException(message); } catch (InterruptedException e) { logger.warn("Thread interrupted while (re)trying"); Thread.currentThread().interrupt(); } catch (RetryFailedException e) { String message = String.format("Failed to retrieve sitemap of sitemap index at %s", urlContent); logger.error(message); throw new SitemapParseException(message); } state = State.URL; break; case SITEMAP_PROP_LASTMOD: // Do nothing with this data for now reader.getElementText(); break; } //System.out.println(state); } return retval.merge(new Sitemap(sitemapURLs)); }
From source file:com.evolveum.midpoint.prism.lex.dom.DomLexicalProcessor.java
@Override public void readObjectsIteratively(@NotNull ParserSource source, @NotNull ParsingContext parsingContext, RootXNodeHandler handler) throws SchemaException, IOException { InputStream is = source.getInputStream(); XMLStreamReader stream = null; try {//from w w w. jav a2 s. c o m stream = XMLInputFactory.newInstance().createXMLStreamReader(is); int eventType = stream.nextTag(); if (eventType != XMLStreamConstants.START_ELEMENT) { throw new SystemException("StAX Malfunction?"); } DOMConverter domConverter = new DOMConverter(); Map<String, String> rootNamespaceDeclarations = new HashMap<>(); QName objectsMarker = schemaRegistry.getPrismContext().getObjectsElementName(); if (objectsMarker != null && !QNameUtil.match(stream.getName(), objectsMarker)) { readSingleObjectIteratively(stream, rootNamespaceDeclarations, domConverter, handler); } for (int i = 0; i < stream.getNamespaceCount(); i++) { rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i)); } while (stream.hasNext()) { eventType = stream.next(); if (eventType == XMLStreamConstants.START_ELEMENT) { if (!readSingleObjectIteratively(stream, rootNamespaceDeclarations, domConverter, handler)) { return; } } } } catch (XMLStreamException ex) { String lineInfo = stream != null ? " on line " + stream.getLocation().getLineNumber() : ""; throw new SchemaException("Exception while parsing XML" + lineInfo + ": " + ex.getMessage(), ex); } finally { if (source.closeStreamAfterParsing()) { IOUtils.closeQuietly(is); } } }
From source file:net.xy.jcms.controller.configurations.parser.UsecaseParser.java
/** * parses usecases out from an xml file/*w ww . j av a 2 s . c om*/ * * @param in * @param loader * used for retrieving configuration included resources and also * for retrieving the controllers * @return value * @throws XMLStreamException * @throws ClassNotFoundException */ public static Usecase[] parse(final InputStream in, final ClassLoader loader) throws XMLStreamException, ClassNotFoundException { final XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty("javax.xml.stream.isCoalescing", true); // not supported by the reference implementation // factory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.TRUE); final XMLStreamReader parser = factory.createXMLStreamReader(in); while (parser.hasNext()) { final int event = parser.next(); if (event == XMLStreamConstants.START_ELEMENT && parser.getName().getLocalPart().equals("usecases")) { return parseUsecases(parser, loader); } } throw new IllegalArgumentException("No usecases section found. [" + parser.getLocation() + "]"); }