List of usage examples for javax.xml.stream XMLEventReader hasNext
@Override public boolean hasNext();
From source file:com.hazelcast.simulator.probes.probes.ProbesResultXmlReader.java
private static Result parseOperationsPerSecResult(XMLEventReader reader) throws XMLStreamException { Long invocations = null;// w w w . j ava 2s . c o m Double operationsPerSecond = null; while (reader.hasNext()) { XMLEvent xmlEvent = reader.nextEvent(); if (xmlEvent.isStartElement()) { StartElement startElement = xmlEvent.asStartElement(); if (INVOCATIONS.matches(startElement.getName().getLocalPart())) { if (invocations != null) { throw new XMLStreamException( "Unexpected element " + INVOCATIONS.getName() + " (has been already defined)"); } invocations = Long.parseLong(parseCharsAndEndCurrentElement(reader)); } else if (OPERATIONS_PER_SECOND.matches(startElement.getName().getLocalPart())) { if (operationsPerSecond != null) { throw new XMLStreamException("Unexpected element " + OPERATIONS_PER_SECOND.getName() + " (has been already defined)"); } operationsPerSecond = Double.parseDouble(parseCharsAndEndCurrentElement(reader)); } if (invocations != null && operationsPerSecond != null) { return new OperationsPerSecResult(invocations, operationsPerSecond); } } } throw new XMLStreamException("Unexpected end of stream"); }
From source file:com.predic8.membrane.core.interceptor.rest.XML2HTTP.java
private static String slurpCharacterData(XMLEventReader parser, StartElement sevent) throws XMLStreamException, XML2HTTPException { String name = sevent.getName().getLocalPart(); StringBuilder value = new StringBuilder(); while (parser.hasNext()) { XMLEvent event = parser.nextEvent(); if (event.isCharacters()) { value.append(event.asCharacters().getData()); } else if (event.isEndElement()) { break; } else {//from www. j a v a2 s . c o m throw new XML2HTTPException("XML-HTTP doc <" + name + "> element contains non-character data."); } } return value.toString(); }
From source file:Main.java
public static String getXMLContent(XMLEventReader reader, StartElement element, boolean decodeCharacters) throws XMLStreamException { String rootElementName = getLocalName(element); StringWriter buffer = new StringWriter(1024); StartElement pendingElement = null; String pendingElementName = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (pendingElement != null) { boolean skip = false; if (event.isEndElement() && pendingElementName.equals(getLocalName(event.asEndElement()))) { writeAsEncodedUnicode(pendingElement, buffer, true); // empty tag skip = true; // skip this end tag } else { writeAsEncodedUnicode(pendingElement, buffer, false); }//from ww w. j a va 2s.c om pendingElement = null; pendingElementName = null; if (skip) continue; } if (event.isEndElement()) { EndElement endElement = event.asEndElement(); String name = getLocalName(endElement); if (rootElementName.equals(name)) return buffer.toString(); writeAsEncodedUnicode(endElement, buffer); } else if (event.isStartElement()) { pendingElement = event.asStartElement(); pendingElementName = getLocalName(pendingElement); } else if (event.isCharacters() && decodeCharacters) { buffer.append(event.asCharacters().getData()); } else { event.writeAsEncodedUnicode(buffer); } } throw new XMLStreamException(format("Missing closing tag for '" + rootElementName + "' element", element)); }
From source file:com.hazelcast.simulator.probes.probes.ProbesResultXmlReader.java
private static String parseCharsAndEndCurrentElement(XMLEventReader reader) throws XMLStreamException { XMLEvent xmlEvent = reader.nextEvent(); if (!xmlEvent.isCharacters()) { throw new XMLStreamException("Unexpected event " + xmlEvent); }//from w w w . ja v a 2s.c o m String data = xmlEvent.asCharacters().getData(); while (reader.hasNext()) { xmlEvent = reader.nextEvent(); if (xmlEvent.isEndElement()) { return data; } } throw new XMLStreamException("Unexpected end of the document"); }
From source file:com.predic8.membrane.core.interceptor.rest.XML2HTTP.java
private static String slurpXMLData(XMLEventReader parser, StartElement sevent) throws XML2HTTPException, XMLStreamException { StringWriter bodyStringWriter = new StringWriter(); XMLEventWriter bodyWriter = null; int depth = 0; synchronized (xmlOutputFactory) { bodyWriter = xmlOutputFactory.createXMLEventWriter(bodyStringWriter); }//from w ww. j av a2s.c o m while (parser.hasNext()) { XMLEvent event = parser.nextEvent(); if (event.isEndElement() && depth == 0) { bodyWriter.flush(); return bodyStringWriter.toString(); } bodyWriter.add(event); if (event.isStartElement()) depth++; else if (event.isEndElement()) depth--; } throw new XML2HTTPException("Early end of file while reading inner XML document."); }
From source file:ch.njol.skript.Updater.java
/** * Gets the changelogs and release dates of the newest versions * // w w w . java 2 s . c o m * @param sender */ final static void getChangelogs(final CommandSender sender) { InputStream in = null; InputStreamReader r = null; try { final URLConnection conn = new URL(RSSURL).openConnection(); conn.setRequestProperty("User-Agent", "Skript/v" + Skript.getVersion() + " (by Njol)"); // Bukkit returns a 403 (forbidden) if no user agent is set in = conn.getInputStream(); r = new InputStreamReader(in, conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding()); final XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(r); infos.clear(); VersionInfo current = null; outer: while (reader.hasNext()) { XMLEvent e = reader.nextEvent(); if (e.isStartElement()) { final String element = e.asStartElement().getName().getLocalPart(); if (element.equalsIgnoreCase("title")) { final String name = reader.nextEvent().asCharacters().getData().trim(); for (final VersionInfo i : infos) { if (name.equals(i.name)) { current = i; continue outer; } } current = null; } else if (element.equalsIgnoreCase("description")) { if (current == null) continue; final StringBuilder cl = new StringBuilder(); while ((e = reader.nextEvent()).isCharacters()) cl.append(e.asCharacters().getData()); current.changelog = "- " + StringEscapeUtils.unescapeHtml("" + cl).replace("<br>", "") .replace("<p>", "").replace("</p>", "").replaceAll("\n(?!\n)", "\n- "); } else if (element.equalsIgnoreCase("pubDate")) { if (current == null) continue; synchronized (RFC2822) { // to make FindBugs shut up current.date = new Date( RFC2822.parse(reader.nextEvent().asCharacters().getData()).getTime()); } } } } } catch (final IOException e) { stateLock.writeLock().lock(); try { state = UpdateState.CHECK_ERROR; error.set(ExceptionUtils.toString(e)); Skript.error(sender, m_check_error.toString()); } finally { stateLock.writeLock().unlock(); } } catch (final Exception e) { Skript.error(sender, m_internal_error.toString()); Skript.exception(e, "Unexpected error while checking for a new version of Skript"); stateLock.writeLock().lock(); try { state = UpdateState.CHECK_ERROR; error.set(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage()); } finally { stateLock.writeLock().unlock(); } } finally { if (in != null) { try { in.close(); } catch (final IOException e) { } } if (r != null) { try { r.close(); } catch (final IOException e) { } } } }
From source file:com.hazelcast.simulator.probes.probes.ProbesResultXmlReader.java
private static void parseBucket(XMLEventReader reader, StartElement element, LinearHistogram histogram) throws XMLStreamException { String upperBound = element.getAttributeByName(new QName(LATENCY_DIST_UPPER_BOUND.getName())).getValue(); String values = element.getAttributeByName(new QName(LATENCY_DIST_VALUES.getName())).getValue(); histogram.addMultipleValues(Integer.parseInt(upperBound) - 1, Integer.parseInt(values)); while (reader.hasNext()) { XMLEvent xmlEvent = reader.nextEvent(); if (xmlEvent.isEndElement()) { EndElement endElement = xmlEvent.asEndElement(); if (LATENCY_DIST_BUCKET.getName().equals(endElement.getName().getLocalPart())) { return; }/*from w w w. j a va 2 s .com*/ } } throw new XMLStreamException("Unexpected end of the document"); }
From source file:com.predic8.membrane.core.interceptor.rest.XML2HTTP.java
/** * Checks, if the response contains an XML doc with NS {@link Constants#HTTP_NS}. * If it does, the HTTP data (uri, method, status, headers, body) is extracted from the doc * and set as the response.//from w ww .j a v a2 s . c o m * * Reverse of {@link com.predic8.membrane.core.http.xml.Request#write(XMLStreamWriter)} and * {@link com.predic8.membrane.core.http.xml.Response#write(XMLStreamWriter)}. */ public static void unwrapMessageIfNecessary(Message message) { if (MimeType.TEXT_XML_UTF8.equals(message.getHeader().getContentType())) { try { if (message.getBody().getLength() == 0) return; XMLEventReader parser; synchronized (xmlInputFactory) { parser = xmlInputFactory.createXMLEventReader(message.getBodyAsStreamDecoded(), message.getCharset()); } /* States: * 0 = before root element, * 1 = root element has HTTP_NS namespace */ int state = 0; boolean keepSourceHeaders = false, foundHeaders = false, foundBody = false; while (parser.hasNext()) { XMLEvent event = parser.nextEvent(); switch (state) { case 0: if (event.isStartElement()) { QName name = event.asStartElement().getName(); if (Constants.HTTP_NS.equals(name.getNamespaceURI())) { state = 1; if ("request".equals(name.getLocalPart())) { Request req = (Request) message; req.setMethod(requireAttribute(event.asStartElement(), "method")); String httpVersion = getAttribute(event.asStartElement(), "http-version"); if (httpVersion == null) httpVersion = "1.1"; req.setVersion(httpVersion); } } else { return; } } break; case 1: if (event.isStartElement()) { String localName = event.asStartElement().getName().getLocalPart(); if ("status".equals(localName)) { Response res = (Response) message; res.setStatusCode( Integer.parseInt(requireAttribute(event.asStartElement(), "code"))); res.setStatusMessage(slurpCharacterData(parser, event.asStartElement())); } if ("uri".equals(localName)) { Request req = (Request) message; req.setUri(requireAttribute(event.asStartElement(), "value")); // uri/... (port,host,path,query) structure is ignored, as value already contains everything slurpXMLData(parser, event.asStartElement()); } if ("headers".equals(localName)) { foundHeaders = true; keepSourceHeaders = "true" .equals(getAttribute(event.asStartElement(), "keepSourceHeaders")); } if ("header".equals(localName)) { String key = requireAttribute(event.asStartElement(), "name"); boolean remove = getAttribute(event.asStartElement(), "remove") != null; if (remove && !keepSourceHeaders) throw new XML2HTTPException( "<headers keepSourceHeaders=\"false\"><header name=\"...\" remove=\"true\"> does not make sense."); message.getHeader().removeFields(key); if (!remove) message.getHeader().add(key, slurpCharacterData(parser, event.asStartElement())); } if ("body".equals(localName)) { foundBody = true; String type = requireAttribute(event.asStartElement(), "type"); if ("plain".equals(type)) { message.setBodyContent(slurpCharacterData(parser, event.asStartElement()) .getBytes(Constants.UTF_8_CHARSET)); } else if ("xml".equals(type)) { message.setBodyContent(slurpXMLData(parser, event.asStartElement()) .getBytes(Constants.UTF_8_CHARSET)); } else { throw new XML2HTTPException("XML-HTTP doc body type '" + type + "' is not supported (only 'plain' or 'xml')."); } } } break; } } if (!foundHeaders && !keepSourceHeaders) message.getHeader().clear(); if (!foundBody) message.setBodyContent(new byte[0]); } catch (XMLStreamException e) { log.error("", e); } catch (XML2HTTPException e) { log.error("", e); } catch (IOException e) { log.error("", e); } } }
From source file:de.dfki.km.leech.parser.wikipedia.WikipediaDumpParser.java
/** * Reads all next character events from an xmlEventReader and concatenate their data into one String * //from www . java 2s .co m * @param xmlEventReader the xmlEventReader to get the events * * @return the data of the character events, concatenated into one String * * @throws XMLStreamException */ static protected String readNextCharEventsText(XMLEventReader xmlEventReader) throws XMLStreamException { StringBuilder strbText = new StringBuilder(""); while (xmlEventReader.hasNext()) { XMLEvent nextEvent = xmlEventReader.peek(); if (!nextEvent.isCharacters()) break; nextEvent = xmlEventReader.nextEvent(); strbText.append(nextEvent.asCharacters().getData()); } return strbText.toString(); }
From source file:StAXEventTreeViewer.java
public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode current, File file) throws XMLStreamException, FileNotFoundException { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader reader = inputFactory.createXMLEventReader(new FileInputStream(file)); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); switch (event.getEventType()) { case XMLStreamConstants.START_DOCUMENT: StartDocument startDocument = (StartDocument) event; DefaultMutableTreeNode version = new DefaultMutableTreeNode(startDocument.getVersion()); current.add(version);/*from w ww.j a v a 2 s . c o m*/ current.add(new DefaultMutableTreeNode(startDocument.isStandalone())); current.add(new DefaultMutableTreeNode(startDocument.standaloneSet())); current.add(new DefaultMutableTreeNode(startDocument.encodingSet())); current.add(new DefaultMutableTreeNode(startDocument.getCharacterEncodingScheme())); break; case XMLStreamConstants.START_ELEMENT: StartElement startElement = (StartElement) event; QName elementName = startElement.getName(); DefaultMutableTreeNode element = new DefaultMutableTreeNode(elementName.getLocalPart()); current.add(element); current = element; if (!elementName.getNamespaceURI().equals("")) { String prefix = elementName.getPrefix(); if (prefix.equals("")) { prefix = "[None]"; } DefaultMutableTreeNode namespace = new DefaultMutableTreeNode( "prefix=" + prefix + ",URI=" + elementName.getNamespaceURI()); current.add(namespace); } for (Iterator it = startElement.getAttributes(); it.hasNext();) { Attribute attr = (Attribute) it.next(); DefaultMutableTreeNode attribute = new DefaultMutableTreeNode("Attribute (name=" + attr.getName().getLocalPart() + ",value=" + attr.getValue() + "')"); String attURI = attr.getName().getNamespaceURI(); if (!attURI.equals("")) { String attPrefix = attr.getName().getPrefix(); if (attPrefix.equals("")) { attPrefix = "[None]"; } attribute.add(new DefaultMutableTreeNode("prefix = " + attPrefix + ", URI = " + attURI)); } current.add(attribute); } break; case XMLStreamConstants.END_ELEMENT: current = (DefaultMutableTreeNode) current.getParent(); break; case XMLStreamConstants.CHARACTERS: Characters characters = (Characters) event; if (!characters.isIgnorableWhiteSpace() && !characters.isWhiteSpace()) { String data = characters.getData(); if (data.length() != 0) { current.add(new DefaultMutableTreeNode(characters.getData())); } } break; case XMLStreamConstants.DTD: DTD dtde = (DTD) event; current.add(new DefaultMutableTreeNode(dtde.getDocumentTypeDeclaration())); default: System.out.println(event.getClass().getName()); } } }