List of usage examples for javax.xml.stream XMLEventWriter add
public void add(XMLEventReader reader) throws XMLStreamException;
From source file:org.apache.synapse.commons.json.JsonUtil.java
/** * Converts an XML element to its JSON representation and writes it to an output stream.<br/> * Note that this method removes all existing namespace declarations and namespace prefixes of the provided XML element<br/> * * @param element XML element of which JSON representation is expected. * @param outputStream Output Stream to write the JSON representation.<br/> * At the end of a successful conversion, its flush method will be called. * @throws AxisFault/*from w w w.ja v a2s . c o m*/ */ public static void writeAsJson(OMElement element, OutputStream outputStream) throws AxisFault { XMLEventReader xmlEventReader = null; XMLEventWriter jsonWriter = null; if (element == null) { logger.error("#writeAsJson. OMElement is null. Cannot convert to JSON."); throw new AxisFault("OMElement is null. Cannot convert to JSON."); } if (outputStream == null) { return; } transformElement(element, true); try { org.apache.commons.io.output.ByteArrayOutputStream xmlStream = new org.apache.commons.io.output.ByteArrayOutputStream(); element.serialize(xmlStream); xmlStream.flush(); xmlEventReader = xmlInputFactory.createXMLEventReader(new XmlReaderDelegate( xmlInputFactory.createXMLStreamReader(new ByteArrayInputStream(xmlStream.toByteArray())), processNCNames)); jsonWriter = jsonOutputFactory.createXMLEventWriter(outputStream); jsonWriter.add(xmlEventReader); outputStream.flush(); } catch (XMLStreamException e) { logger.error("#writeAsJson. Could not convert OMElement to JSON. Invalid XML payload. Error>>> " + e.getLocalizedMessage()); throw new AxisFault("Could not convert OMElement to JSON. Invalid XML payload.", e); } catch (IOException e) { logger.error("#writeAsJson. Could not convert OMElement to JSON. Error>>> " + e.getLocalizedMessage()); throw new AxisFault("Could not convert OMElement to JSON.", e); } finally { if (xmlEventReader != null) { try { xmlEventReader.close(); } catch (XMLStreamException ex) { //ignore } } if (jsonWriter != null) { try { jsonWriter.close(); } catch (XMLStreamException ex) { //ignore } } } }
From source file:org.codice.ddf.spatial.ogc.wfs.transformer.handlebars.HandlebarsWfsFeatureTransformer.java
private void readGmlData(XMLEventReader xmlEventReader, String elementName, Map<String, String> contextMap) throws XMLStreamException { if (!xmlEventReader.peek().isStartElement()) { LOGGER.debug("Problem reading gml data for element: {}. Invalid xml element provided.", elementName); return;//w w w. j a v a2 s . c om } StringWriter stringWriter = new StringWriter(); XMLEventWriter eventWriter = XML_OUTPUT_FACTORY.createXMLEventWriter(stringWriter); if (eventWriter == null) { LOGGER.debug("Problem reading gml data for element: {}. Event writer is null", elementName); return; } int count = 0; boolean addEvent = true; try { while (addEvent) { XMLEvent xmlEvent = xmlEventReader.nextEvent(); // populate the start element with the namespaces if (xmlEvent.isStartElement()) { xmlEvent = addNamespacesToStartElement(xmlEvent.asStartElement()); count++; } else if (xmlEvent.isEndElement()) { if (count == 0) { addEvent = false; eventWriter.flush(); LOGGER.debug("String writer: {}", stringWriter); contextMap.put(elementName, stringWriter.toString()); } count--; } if (addEvent) { eventWriter.add(xmlEvent); } } } finally { eventWriter.close(); } }
From source file:org.dkpro.core.io.xces.XcesBasicXmlWriter.java
@Override public void process(JCas aJCas) throws AnalysisEngineProcessException { OutputStream docOS = null;/*from w w w .j a v a2s .co m*/ try { docOS = getOutputStream(aJCas, filenameSuffix); XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); XMLEventWriter xmlEventWriter = new IndentingXMLEventWriter( xmlOutputFactory.createXMLEventWriter(docOS)); JAXBContext context = JAXBContext.newInstance(XcesBodyBasic.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); XMLEventFactory xmlef = XMLEventFactory.newInstance(); xmlEventWriter.add(xmlef.createStartDocument()); // Begin cesDoc xmlEventWriter.add(xmlef.createStartElement("", "", "cesDoc")); // Begin and End cesHeader xmlEventWriter.add(xmlef.createStartElement("", "", "cesHeader")); xmlEventWriter.add(xmlef.createEndElement("", "", "cesHeader")); // Begin text and body xmlEventWriter.add(xmlef.createStartElement("", "", "text")); // xmlEventWriter.add(xmlef.createStartElement("", "", "body")); // Begin body of all the paragraphs Collection<Paragraph> parasInCas = JCasUtil.select(aJCas, Paragraph.class); XcesBodyBasic xb = convertToXcesBasicPara(parasInCas); marshaller.marshal(new JAXBElement<XcesBodyBasic>(new QName("body"), XcesBodyBasic.class, xb), xmlEventWriter); // End body of all the paragraphs // xmlEventWriter.add(xmlef.createEndElement("", "", "body")); xmlEventWriter.add(xmlef.createEndElement("", "", "text")); xmlEventWriter.add(xmlef.createEndElement("", "", "cesDoc")); xmlEventWriter.add(xmlef.createEndDocument()); } catch (Exception e) { throw new AnalysisEngineProcessException(e); } finally { closeQuietly(docOS); } }
From source file:org.dkpro.core.io.xces.XcesXmlWriter.java
@Override public void process(JCas aJCas) throws AnalysisEngineProcessException { OutputStream docOS = null;//from w w w. j a va 2s.c o m try { docOS = getOutputStream(aJCas, filenameSuffix); XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance(); XMLEventWriter xmlEventWriter = new IndentingXMLEventWriter( xmlOutputFactory.createXMLEventWriter(docOS)); JAXBContext context = JAXBContext.newInstance(XcesBody.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); XMLEventFactory xmlef = XMLEventFactory.newInstance(); xmlEventWriter.add(xmlef.createStartDocument()); // Begin cesDoc xmlEventWriter.add(xmlef.createStartElement("", "", "cesDoc")); // Begin and End cesHeader xmlEventWriter.add(xmlef.createStartElement("", "", "cesHeader")); xmlEventWriter.add(xmlef.createEndElement("", "", "cesHeader")); // Begin text and body xmlEventWriter.add(xmlef.createStartElement("", "", "text")); // xmlEventWriter.add(xmlef.createStartElement("", "", "body")); // Begin body of all the paragraphs Collection<Paragraph> parasInCas = JCasUtil.select(aJCas, Paragraph.class); XcesBody xb = convertToXcesPara(parasInCas); marshaller.marshal(new JAXBElement<XcesBody>(new QName("body"), XcesBody.class, xb), xmlEventWriter); // End body of all the paragraphs // xmlEventWriter.add(xmlef.createEndElement("", "", "body")); xmlEventWriter.add(xmlef.createEndElement("", "", "text")); xmlEventWriter.add(xmlef.createEndElement("", "", "cesDoc")); xmlEventWriter.add(xmlef.createEndDocument()); } catch (Exception e) { throw new AnalysisEngineProcessException(e); } finally { closeQuietly(docOS); } }
From source file:org.eclipse.smila.utils.xml.stax.XmlSnippetSplitter.java
/** * Parse for xml snippets. If a snippet is found the registered XmlSnippethandler is called. * /*from w w w. j a v a2 s . c o m*/ * @param eventReader * the XMLEventReader * @throws XMLStreamException * StAX error. */ private void parse(final XMLEventReader eventReader) throws XMLStreamException { ByteArrayOutputStream outputStream = null; XMLEventWriter eventWriter = null; try { while (eventReader.hasNext()) { final XMLEvent event = eventReader.nextEvent(); if (isSnippetBegin(event)) { // begin of snippet outputStream = new ByteArrayOutputStream(); eventWriter = _outputFactory.createXMLEventWriter(outputStream); eventWriter.add(event); } else if (isSnippetEnd(event)) { // end of snippet if (eventWriter != null) { eventWriter.add(event); eventWriter.close(); _snippetHandler.handleSnippet(outputStream.toByteArray()); // reset eventWriter and outputStream eventWriter = null; outputStream = null; } // if } else if (eventWriter != null) { eventWriter.add(event); } } // while } finally { if (eventWriter != null) { eventWriter.close(); } } }
From source file:org.emonocot.job.io.StaxEventItemWriter.java
/** * Writes simple XML header containing://w w w. j ava 2 s . c om * <ul> * <li>xml declaration - defines encoding and XML version</li> * <li>opening tag of the root element and its attributes</li> * </ul> * If this is not sufficient for you, simply override this method. Encoding, * version and root tag name can be retrieved with corresponding getters. * * @param writer * XML event writer * @throws XMLStreamException if there is a problem starting the document */ protected final void startDocument(final XMLEventWriter writer) throws XMLStreamException { XMLEventFactory factory = XMLEventFactory.newInstance(); // write start document writer.add(factory.createStartDocument(getEncoding(), getVersion())); // write root tag writer.add( factory.createStartElement(getRootTagNamespacePrefix(), getRootTagNamespace(), getRootTagName())); if (StringUtils.hasText(getRootTagNamespace())) { if (StringUtils.hasText(getRootTagNamespacePrefix())) { writer.add(factory.createNamespace(getRootTagNamespacePrefix(), getRootTagNamespace())); } else { writer.add(factory.createNamespace(getRootTagNamespace())); } } // write root tag attributes if (!CollectionUtils.isEmpty(getRootElementAttributes())) { for (Map.Entry<String, String> entry : getRootElementAttributes().entrySet()) { String key = entry.getKey(); if (key.startsWith("xmlns")) { String prefix = ""; if (key.contains(":")) { prefix = key.substring(key.indexOf(":") + 1); } writer.add(factory.createNamespace(prefix, entry.getValue())); } else { writer.add(factory.createAttribute(key, entry.getValue())); } } } /* * This forces the flush to write the end of the root element and avoids * an off-by-one error on restart. */ writer.add(factory.createIgnorableSpace("")); writer.flush(); }
From source file:org.mcisb.subliminal.SubliminalUtils.java
/** * //from w ww .ja v a 2 s . co m * @param elementName * @param is * @param onlyValues * @return Collection * @throws XMLStreamException * @throws UnsupportedEncodingException */ private 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:org.mule.transport.sap.transformer.JcoFunctionToXmlTransformer.java
private void writeStartElement(XMLEventWriter writer, String elementName) throws XMLStreamException { XMLEvent event = eventFactory.createStartElement("", "", elementName); writer.add(event); }
From source file:org.mule.transport.sap.transformer.JcoFunctionToXmlTransformer.java
private void writeEndElement(XMLEventWriter writer, String elementName) throws XMLStreamException { XMLEvent event = eventFactory.createEndElement("", "", elementName); writer.add(event); }
From source file:org.mule.transport.sap.transformer.JcoFunctionToXmlTransformer.java
private void writeAttribute(XMLEventWriter writer, String key, String value) throws XMLStreamException { XMLEvent event = eventFactory.createAttribute(key, value); writer.add(event); }