List of usage examples for javax.xml.stream XMLEventReader peek
public XMLEvent peek() throws XMLStreamException;
From source file:Main.java
/** * // ww w .ja va 2 s. c o m * @param is * @param os * @param elementNames * @throws XMLStreamException * @throws FactoryConfigurationError * @throws UnsupportedEncodingException */ public static void stripElements(final InputStream is, final OutputStream os, final Collection<String> elementNames) throws XMLStreamException, UnsupportedEncodingException, FactoryConfigurationError { final XMLEventReader xmlEventReader = XMLInputFactory.newInstance() .createXMLEventReader(new InputStreamReader(is, Charset.defaultCharset().name())); final XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(os); String elementName = null; while (xmlEventReader.peek() != null) { final XMLEvent event = (XMLEvent) xmlEventReader.next(); switch (event.getEventType()) { case XMLStreamConstants.START_DOCUMENT: case XMLStreamConstants.END_DOCUMENT: { // Ignore. break; } case XMLStreamConstants.START_ELEMENT: { final StartElement startElement = event.asStartElement(); final QName name = startElement.getName(); if (elementNames.contains(name.getLocalPart())) { elementName = name.getLocalPart(); } if (elementName == null) { xmlEventWriter.add(event); } break; } case XMLStreamConstants.END_ELEMENT: { final EndElement endElement = event.asEndElement(); final QName name = endElement.getName(); if (elementName == null) { xmlEventWriter.add(event); } else if (elementName.equals(name.getLocalPart())) { elementName = null; } break; } default: { if (elementName == null) { xmlEventWriter.add(event); } } } } xmlEventWriter.flush(); }
From source file:Main.java
/** * // w w w . j ava2 s .c o m * @param elementName * @param is * @param onlyValues * @return Collection * @throws XMLStreamException * @throws UnsupportedEncodingException */ public static Collection<String> getElements(final String elementName, final InputStream is, final boolean onlyValues) throws XMLStreamException, UnsupportedEncodingException { final Collection<String> elements = new ArrayList<>(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); final XMLEventReader reader = XMLInputFactory.newInstance() .createXMLEventReader(new InputStreamReader(is, Charset.defaultCharset().name())); final XMLEventWriter writer = XMLOutputFactory.newInstance() .createXMLEventWriter(new OutputStreamWriter(os, Charset.defaultCharset().name())); boolean read = false; String characters = null; while (reader.peek() != null) { final XMLEvent event = (XMLEvent) reader.next(); switch (event.getEventType()) { case XMLStreamConstants.START_DOCUMENT: case XMLStreamConstants.END_DOCUMENT: { // Ignore. break; } case XMLStreamConstants.START_ELEMENT: { read = read || elementName.equals(event.asStartElement().getName().getLocalPart()); if (read && !onlyValues) { writer.add(event); } break; } case XMLStreamConstants.ATTRIBUTE: { if (read && !onlyValues) { writer.add(event); } break; } case XMLStreamConstants.CHARACTERS: { if (read && !onlyValues) { writer.add(event); } characters = event.asCharacters().getData(); break; } case XMLStreamConstants.END_ELEMENT: { if (read && !onlyValues) { writer.add(event); } if (elementName.equals(event.asEndElement().getName().getLocalPart())) { writer.flush(); if (characters != null) { elements.add(characters); } os.reset(); read = false; } break; } default: { // Ignore break; } } } return elements; }
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 * /*w w w . jav a2s . c om*/ * @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:org.psikeds.knowledgebase.xml.impl.XMLParser.java
/** * Helper for parsing big XML files using JAXB in combination with StAX.<br> * All classes in the specified package can be parsed.<br> * <b>Note:</b> The XML reader will not be closed. This must be invoked by * the caller afterwards!<br>// w w w .j a v a 2 s .com * * @param xml * Reader for XML-Data * @param packageName * Name of the package containing the JAXB-Classes, * e.g. org.psikeds.knowledgebase.jaxb * @param handler * Callback handler used to process every single found * XML-Element (@see * org.psikeds.knowledgebase.xml.KBParserCallback#handleElement * (java.lang.Object)) * @param filter * EventFilter used for StAX-Parsing * @param numSkipped * Number of Elements to be skipped, * e.g. numSkipped = 1 for skipping the XML-Root-Element. * @return Total number of unmarshalled XML-Elements * @throws XMLStreamException * @throws JAXBException */ public static long parseXmlElements(final Reader xml, final String packageName, final KBParserCallback handler, final EventFilter filter, final int numSkipped) throws XMLStreamException, JAXBException { // init stream reader final XMLInputFactory staxFactory = XMLInputFactory.newInstance(); final XMLEventReader staxReader = staxFactory.createXMLEventReader(xml); final XMLEventReader filteredReader = filter == null ? staxReader : staxFactory.createFilteredReader(staxReader, filter); skipXmlElements(filteredReader, numSkipped); // JAXB with specific package final JAXBContext jaxbCtx = JAXBContext.newInstance(packageName); final Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); // parsing und unmarshalling long counter = 0; while (filteredReader.peek() != null) { final Object element = unmarshaller.unmarshal(staxReader); handleElement(handler, element); counter++; } return counter; }
From source file:org.psikeds.knowledgebase.xml.impl.XMLParser.java
/** * Helper for parsing big XML files using JAXB in combination with StAX.<br> * Only XML-Elements of the specified Top-Level-Class will be parsed.<br> * <b>Note:</b> The XML reader will not be closed. This must be invoked by * the caller afterwards!<br>//from w w w. j av a 2 s.com * * @param xml * Reader for XML-Data * @param elementClass * Top-Level-Class used for JAXB-Unmarshalling * @param handler * Callback handler used to process every single found XML * element (@see * org.psikeds.knowledgebase.xml.KBParserCallback#handleElement * (java.lang.Object)) * @param filter * EventFilter used for StAX-Parsing * @param numSkipped * Number of Elements to be skipped, * e.g. numSkipped = 1 for skipping the XML-Root-Element. * @return Total number of unmarshalled XML-Elements * @throws XMLStreamException * @throws JAXBException */ public static long parseXmlElements(final Reader xml, final Class<?> elemClazz, final KBParserCallback handler, final EventFilter filter, final int numSkipped) throws XMLStreamException, JAXBException { // init stream reader final XMLInputFactory staxFactory = XMLInputFactory.newInstance(); final XMLEventReader staxReader = staxFactory.createXMLEventReader(xml); final XMLEventReader filteredReader = filter == null ? staxReader : staxFactory.createFilteredReader(staxReader, filter); skipXmlElements(filteredReader, numSkipped); // JAXB with specific top-level-class final JAXBContext jaxbCtx = JAXBContext.newInstance(elemClazz); final Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); // parsing und unmarshalling long counter = 0; while (filteredReader.peek() != null) { final Object element = unmarshaller.unmarshal(staxReader, elemClazz); handleElement(handler, element); counter++; } return counter; }
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. *///from w w w. ja v a 2s .c o m 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:org.javelin.sws.ext.bind.internal.model.ComplexTypePattern.java
/** * Called when nested {@link XMLStreamConstants#START_ELEMENT} is found in the consumed content model * /* w w w .j a v a2 s .c o m*/ * @param eventReader * @param context * @return * @throws XMLStreamException */ private PropertyMetadataValue<T, ?> consumeNestedElement(XMLEventReader eventReader, UnmarshallingContext context) throws XMLStreamException { StartElement startElement = eventReader.peek().asStartElement(); QName qName = startElement.getName(); return this.consumeNestedProperty(this.elements.get(qName), eventReader, context); }
From source file:org.javelin.sws.ext.bind.internal.model.ComplexTypePattern.java
/** * @param eventReader/*from w w w. j av a2 s . c o m*/ * @param context * @return */ private PropertyMetadataValue<T, ?> consumeNestedAttribute(XMLEventReader eventReader, UnmarshallingContext context) throws XMLStreamException { Attribute attr = (Attribute) eventReader.peek(); QName qName = attr.getName(); return this.consumeNestedProperty(this.attributes.get(qName), eventReader, context); }
From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java
@Override protected Collection<Throwable> call(String inputName) throws Exception { final CompiledScript compiledScript; Unmarshaller unmarshaller;/*from w ww. ja v a 2 s . c o m*/ Marshaller marshaller; try { compiledScript = super.compileJavascript(); JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast"); unmarshaller = jc.createUnmarshaller(); marshaller = jc.createMarshaller(); XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory(); xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); PrintWriter pw = openFileOrStdoutAsPrintWriter(); XMLOutputFactory xof = XMLOutputFactory.newFactory(); xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE); XMLEventWriter w = xof.createXMLEventWriter(pw); StreamSource src = null; if (inputName == null) { LOG.info("Reading stdin"); src = new StreamSource(stdin()); } else { LOG.info("Reading file " + inputName); src = new StreamSource(new File(inputName)); } XMLEventReader r = xmlInputFactory.createXMLEventReader(src); XMLEventFactory eventFactory = XMLEventFactory.newFactory(); SimpleBindings bindings = new SimpleBindings(); while (r.hasNext()) { XMLEvent evt = r.peek(); switch (evt.getEventType()) { case XMLEvent.START_ELEMENT: { StartElement sE = evt.asStartElement(); Hit hit = null; JAXBElement<Hit> jaxbElement = null; if (sE.getName().getLocalPart().equals("Hit")) { jaxbElement = unmarshaller.unmarshal(r, Hit.class); hit = jaxbElement.getValue(); } else { w.add(r.nextEvent()); break; } if (hit != null) { bindings.put("hit", hit); boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings); if (accept) { marshaller.marshal(jaxbElement, w); w.add(eventFactory.createCharacters("\n")); } } break; } case XMLEvent.SPACE: break; default: { w.add(r.nextEvent()); break; } } r.close(); } w.flush(); w.close(); pw.flush(); pw.close(); return RETURN_OK; } catch (Exception err) { return wrapException(err); } finally { } }
From source file:com.streamsets.pipeline.lib.xml.StreamingXmlParser.java
XMLEvent peek(XMLEventReader reader) throws XMLStreamException { skipIgnorable(reader); return reader.peek(); }