List of usage examples for javax.xml.stream.events XMLEvent isStartElement
public boolean isStartElement();
From source file:de.tudarmstadt.ukp.dkpro.core.io.tiger.TigerXmlReader.java
public static boolean isStartElement(XMLEvent aEvent, String aElement) { return aEvent.isStartElement() && ((StartElement) aEvent).getName().getLocalPart().equals(aElement); }
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 ww w . j ava2s. co 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: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 ww w.jav a 2 s . 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 .j a v a 2s .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:org.opennms.netmgt.ackd.readers.HypericAckProcessor.java
/** * <p>parseHypericAlerts</p> * * @param reader a {@link java.io.Reader} object. * @return a {@link java.util.List} object. * @throws javax.xml.bind.JAXBException if any. * @throws javax.xml.stream.XMLStreamException if any. *///www. ja v a 2 s . com public static List<HypericAlertStatus> parseHypericAlerts(Reader reader) throws JAXBException, XMLStreamException { List<HypericAlertStatus> retval = new ArrayList<HypericAlertStatus>(); // Instantiate a JAXB context to parse the alert status JAXBContext context = JAXBContext .newInstance(new Class[] { HypericAlertStatuses.class, HypericAlertStatus.class }); XMLInputFactory xmlif = XMLInputFactory.newInstance(); XMLEventReader xmler = xmlif.createXMLEventReader(reader); EventFilter filter = new EventFilter() { @Override public boolean accept(XMLEvent event) { return event.isStartElement(); } }; XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter); // Read up until the beginning of the root element StartElement startElement = (StartElement) xmlfer.nextEvent(); // Fetch the root element name for {@link HypericAlertStatus} objects String rootElementName = context.createJAXBIntrospector().getElementName(new HypericAlertStatuses()) .getLocalPart(); if (rootElementName.equals(startElement.getName().getLocalPart())) { Unmarshaller unmarshaller = context.createUnmarshaller(); // Use StAX to pull parse the incoming alert statuses while (xmlfer.peek() != null) { Object object = unmarshaller.unmarshal(xmler); if (object instanceof HypericAlertStatus) { HypericAlertStatus alertStatus = (HypericAlertStatus) object; retval.add(alertStatus); } } } else { // Try to pull in the HTTP response to give the user a better idea of what went wrong StringBuffer errorContent = new StringBuffer(); LineNumberReader lineReader = new LineNumberReader(reader); try { String line; while (true) { line = lineReader.readLine(); if (line == null) { break; } else { errorContent.append(line.trim()); } } } catch (IOException e) { errorContent.append("Exception while trying to print out message content: " + e.getMessage()); } // Throw an exception and include the erroneous HTTP response in the exception text throw new JAXBException("Found wrong root element in Hyperic XML document, expected: \"" + rootElementName + "\", found \"" + startElement.getName().getLocalPart() + "\"\n" + errorContent.toString()); } return retval; }
From source file:Main.java
public boolean accept(XMLEvent event) { if (event.isStartElement()) { StartElement startElement = event.asStartElement(); String name = startElement.getName().getLocalPart(); if (name.equals("InterestingElement")) { return true; }/*from ww w . j a v a 2 s.com*/ } return false; }
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); }// w w w . j a v a 2 s . co m 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.predic8.membrane.core.interceptor.xmlprotection.XMLProtector.java
public boolean protect(InputStreamReader isr) { try {/*from w ww . jav a 2 s. co m*/ XMLEventReader parser; synchronized (xmlInputFactory) { parser = xmlInputFactory.createXMLEventReader(isr); } while (parser.hasNext()) { XMLEvent event = parser.nextEvent(); if (event.isStartElement()) { StartElement startElement = (StartElement) event; if (maxElementNameLength != -1) if (startElement.getName().getLocalPart().length() > maxElementNameLength) { log.warn("Element name length: Limit exceeded."); return false; } if (maxAttibuteCount != -1) { @SuppressWarnings("rawtypes") Iterator i = startElement.getAttributes(); for (int attributeCount = 0; i.hasNext(); i.next()) if (++attributeCount == maxAttibuteCount) { log.warn("Number of attributes per element: Limit exceeded."); return false; } } } if (event instanceof javax.xml.stream.events.DTD) { if (removeDTD) { log.debug("removed DTD."); continue; } } writer.add(event); } writer.flush(); } catch (XMLStreamException e) { log.warn("Received not-wellformed XML."); return false; } return true; }
From source file:com.amalto.core.load.io.XMLStreamUnwrapper.java
public XMLStreamUnwrapper(InputStream stream) { try {/* ww w .j av a 2 s . c o m*/ reader = XMLInputFactory.newFactory().createXMLEventReader(stream); // Skip to first record while (reader.hasNext() && level < RECORD_LEVEL) { final XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { // Declare root element namespaces (if any) final StartElement startElement = event.asStartElement(); Iterator namespaces = startElement.getNamespaces(); while (namespaces.hasNext()) { rootNamespaceList.add((Namespace) namespaces.next()); } level++; } } xmlOutputFactory = XMLOutputFactory.newFactory(); } catch (XMLStreamException e) { throw new RuntimeException("Unexpected parsing configuration error.", e); } }
From source file:com.predic8.membrane.core.ws.relocator.Relocator.java
private XMLEvent getEvent(XMLEventReader parser) throws XMLStreamException { XMLEvent event = parser.nextEvent(); if (!event.isStartElement()) return event; /*/*from ww w.j a v a2s.c om*/ * if (isAddressElement(event)) { return replace(event, "location"); } * else if (getElementName(event).equals(INCLUDE)) { return * replace(event, "schemaLocation"); } else if * (getElementName(event).equals(IMPORT)) { return replace(event, * "schemaLocation"); } else if * (getElementName(event).equals(WADL_RESOURCES)) { return * replace(event, "base"); } else if * (getElementName(event).equals(WADL_INCLUDE)) { return replace(event, * "href"); } else if (getElementName(event).getNamespaceURI().equals( * Constants.WSDL_SOAP11_NS) || * getElementName(event).getNamespaceURI().equals( * Constants.WSDL_SOAP12_NS)) { wsdlFound = true; } */ if (getElementName(event).getNamespaceURI().equals(Constants.WSDL_SOAP11_NS) || getElementName(event).getNamespaceURI().equals(Constants.WSDL_SOAP12_NS)) { wsdlFound = true; } for (QName qn : relocatingAttributes.keySet()) { if (getElementName(event).equals(qn)) { return replace(event, relocatingAttributes.get(qn)); } } return event; }