List of usage examples for javax.xml.stream XMLEventWriter close
public void close() throws XMLStreamException;
From source file:org.apache.olingo.fit.utils.XMLUtilities.java
@Override public InputStream deleteProperty(final InputStream src, final List<String> path) throws Exception { final XMLEventReader reader = getEventReader(src); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); final XMLEventReader changesReader = new XMLEventReaderWrapper(IOUtils.toInputStream( String.format("<%s m:null=\"true\" />", path.get(path.size() - 1)), Constants.ENCODING)); writer.add(changesReader);/*from www .ja v a2s . co m*/ changesReader.close(); writer.add(reader); reader.close(); IOUtils.closeQuietly(src); writer.flush(); writer.close(); return new ByteArrayInputStream(bos.toByteArray()); }
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/*ww w.j a va2 s.com*/ */ 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;/*from www . j av a 2 s .c o m*/ } 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.eclipse.smila.utils.xml.stax.XmlSnippetSplitter.java
/** * Parse for xml snippets. If a snippet is found the registered XmlSnippethandler is called. * /*w w w. j a v a 2s . 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.omnaest.utils.xml.XMLNestedMapConverter.java
/** * @param nestedMap// ww w . j a v a 2 s . c om * {@link Map} * @param outputStream * {@link OutputStream} * @param includeDocumentHeader * if true a xml document header is written out additionally */ private <K> void toXML(Map<K, Object> nestedMap, OutputStream outputStream, final ElementConverter<K, QName> keyElementConverter, boolean includeDocumentHeader) { // if (nestedMap != null && keyElementConverter != null && outputStream != null) { // try { // final XMLOutputFactory xmlOutputFactory = this.xmlInstanceContextFactory.newXmlOutputFactory(); final XMLEventFactory xmlEventFactory = this.xmlInstanceContextFactory.newXmlEventFactory(); Assert.isNotNull(xmlOutputFactory, "xmlOutputFactory must not be null"); Assert.isNotNull(xmlEventFactory, "xmlEventFactory must not be null"); // final XMLEventWriter xmlEventWriter = xmlOutputFactory.createXMLEventWriter(outputStream, this.encoding); final ExceptionHandler exceptionHandler = this.exceptionHandler; // try { // class Helper { /* ********************************************** Variables ********************************************** */ private List<String> namespaceStack = new ArrayList<String>(); /* ********************************************** Methods ********************************************** */ @SuppressWarnings("unchecked") public void write(Map<K, Object> map) { if (map != null) { for (K key : map.keySet()) { // final QName tagName = keyElementConverter.convert(key); final Object value = map.get(key); // if (value instanceof String) { // this.writeStartTag(tagName); // final String text = (String) value; this.writeText(text); // this.writeEndTag(tagName); } else if (value instanceof Map) { // this.writeStartTag(tagName); // final Map<K, Object> subMap = (Map<K, Object>) value; this.write(subMap); // this.writeEndTag(tagName); } else if (value instanceof List) { // final List<Object> valueList = (List<Object>) value; this.write(tagName, valueList); } } } } /** * @param tagName */ private void writeStartTag(QName tagName) { // try { // final String namespaceURI = tagName.getNamespaceURI(); // final Iterator<?> attributes = null; final Iterator<?> namespaces = StringUtils.isNotBlank(namespaceURI) && !StringUtils .equals(namespaceURI, ListUtils.lastElement(this.namespaceStack)) ? IteratorUtils.valueOf( xmlEventFactory.createNamespace(namespaceURI)) : null; StartElement startElement = xmlEventFactory.createStartElement(tagName, attributes, namespaces); xmlEventWriter.add(startElement); // this.namespaceStack.add(namespaceURI); } catch (Exception e) { exceptionHandler.handleException(e); } } /** * @param tagName */ private void writeEndTag(QName tagName) { // try { // final Iterator<?> namespaces = null; EndElement endElement = xmlEventFactory.createEndElement(tagName, namespaces); xmlEventWriter.add(endElement); // ListUtils.removeLast(this.namespaceStack); } catch (Exception e) { exceptionHandler.handleException(e); } } /** * @param text */ private void writeText(String text) { // try { // final Characters characters = xmlEventFactory.createCharacters(text); xmlEventWriter.add(characters); } catch (Exception e) { exceptionHandler.handleException(e); } } /** * @param tagName * @param valueList */ @SuppressWarnings("unchecked") private void write(QName tagName, List<Object> valueList) { if (valueList != null) { for (Object value : valueList) { // if (value != null) { // this.writeStartTag(tagName); // if (value instanceof Map) { // final Map<K, Object> map = (Map<K, Object>) value; this.write(map); } else if (value instanceof String) { // final String text = (String) value; this.writeText(text); } // this.writeEndTag(tagName); } } } } } // if (includeDocumentHeader) { xmlEventWriter.add(xmlEventFactory.createStartDocument()); } // new Helper().write(nestedMap); // xmlEventWriter.add(xmlEventFactory.createEndDocument()); } finally { xmlEventWriter.close(); outputStream.flush(); } } catch (Exception e) { if (this.exceptionHandler != null) { this.exceptionHandler.handleException(e); } } } }
From source file:org.openhim.mediator.denormalization.EnrichRegistryStoredQueryActor.java
private String enrichStoredQueryXML(Identifier id, InputStream xml) throws XMLStreamException { XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(xml); StringWriter output = new StringWriter(); XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output); XMLEventFactory eventFactory = XMLEventFactory.newFactory(); String curSlot = null;//from ww w . j a v a2 s.c o m boolean patientIdSlot = false; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.getEventType() == XMLEvent.START_ELEMENT) { StartElement elem = event.asStartElement(); if ("Slot".equals(elem.getName().getLocalPart())) { curSlot = elem.getAttributeByName(new QName("name")).getValue(); } else if ("Value".equals(elem.getName().getLocalPart()) && ParseRegistryStoredQueryActor.PATIENT_ID_SLOT_TYPE.equals(curSlot)) { patientIdSlot = true; writer.add(event); } } else if (event.getEventType() == XMLEvent.END_ELEMENT) { EndElement elem = event.asEndElement(); if (patientIdSlot && "Value".equals(elem.getName().getLocalPart())) { XMLEvent ecidEvent = eventFactory.createCharacters("'" + id.toString() + "'"); writer.add(ecidEvent); patientIdSlot = false; } } if (!patientIdSlot) { writer.add(event); } } writer.close(); return output.toString(); }
From source file:org.openhim.mediator.enrichers.IdentityEnricher.java
public String enrich(String xml) throws XMLStreamException { InputStream in = IOUtils.toInputStream(xml); XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(in); StringWriter output = new StringWriter(); XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output); while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); processXMLEvent(writer, event);/* w w w. ja va2s . co m*/ } writer.close(); return output.toString(); }
From source file:org.sakaiproject.nakamura.proxy.RSSProxyPostProcessor.java
public void process(Map<String, Object> templateParams, SlingHttpServletResponse response, ProxyResponse proxyResponse) throws IOException { if (proxyResponse.getResultCode() == HttpServletResponse.SC_PRECONDITION_FAILED) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This RSS feed is too big "); return;//from w ww . j a va2 s .com } Map<String, String[]> headers = proxyResponse.getResponseHeaders(); // Check if the content-length is smaller than the maximum (if any). String[] contentLengthHeader = headers.get("Content-Length"); if (contentLengthHeader != null) { int length = Integer.parseInt(contentLengthHeader[0]); if (length > maxLength) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This RSS feed is too big. The maximum for a feed is: " + maxLength); return; } } // Check if the Content-Type we get is valid (if any). String[] contentTypeHeader = headers.get("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader[0]; if (contentType.contains(";")) { contentType = contentType.substring(0, contentType.indexOf(';')); } if (!contentTypes.contains(contentType)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This URL doesn't send a proper Content-Type back"); return; } } boolean isValid = false; InputStream in = proxyResponse.getResponseBodyAsInputStream(); InputStreamReader reader = new InputStreamReader(in); // XMLStreamWriter writer = null; XMLEventWriter writer = null; ByteArrayOutputStream out = null; int i = 0; try { XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(reader); // Create a temporary outputstream where we can write to. out = new ByteArrayOutputStream(); Set<String> checkedElements = null; XMLOutputFactory outputFactory = new WstxOutputFactory(); writer = outputFactory.createXMLEventWriter(out); while (eventReader.hasNext()) { XMLEvent e = eventReader.nextEvent(); // Stream it to an output stream. writer.add(e); if (!isValid) { if (e.getEventType() == XMLEvent.START_ELEMENT) { StartElement el = e.asStartElement(); String name = el.getName().getLocalPart().toLowerCase(); if (checkedElements == null) { // get the right format to validate against String formatKey = name; Attribute attr = el.getAttributeByName(new QName("version")); if (attr != null) { formatKey += "-" + attr.getValue(); } Set<String> format = formats.get(formatKey); if (format != null) { checkedElements = new HashSet<String>(format); } } else { checkedElements.remove(name); if (checkedElements.isEmpty()) { isValid = true; } } } if (i > eventsThreshold) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This file is too complex."); return; } i++; } } if (!isValid) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid RSS file."); return; } // Check if we are not streaming a gigantic file.. if (out.size() > maxLength) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This file is too big."); return; } for (Entry<String, String[]> h : proxyResponse.getResponseHeaders().entrySet()) { for (String v : h.getValue()) { response.setHeader(h.getKey(), v); } } // We always return 200 when we get to this point. response.setStatus(200); response.setHeader("Content-Length", Integer.toString(out.size())); // Write the cached stream to the output. out.writeTo(response.getOutputStream()); } catch (XMLStreamException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "This is not a valid XML file."); } catch (Exception e) { logger.warn("Exception reading RSS feed.", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "General exception caught."); } finally { if (out != null) { out.close(); } reader.close(); try { if (writer != null) writer.close(); } catch (XMLStreamException e) { // Not much we can do? e.printStackTrace(); } } }
From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java
/** * Open method writes the root tag, close method adds corresponding end tag. *//*w w w . ja va 2s. com*/ @Test public void testOpenAndClose() throws Exception { writer.setHeaderCallback(new StaxWriterCallback() { @Override public void write(XMLEventWriter writer) throws IOException { XMLEventFactory factory = XMLEventFactory.newInstance(); try { writer.add(factory.createStartElement("", "", "header")); writer.add(factory.createEndElement("", "", "header")); } catch (XMLStreamException e) { throw new RuntimeException(e); } } }); writer.setFooterCallback(new StaxWriterCallback() { @Override public void write(XMLEventWriter writer) throws IOException { XMLEventFactory factory = XMLEventFactory.newInstance(); try { writer.add(factory.createStartElement("", "", "footer")); writer.add(factory.createEndElement("", "", "footer")); } catch (XMLStreamException e) { throw new RuntimeException(e); } } }); writer.setRootTagName("testroot"); writer.setRootElementAttributes(Collections.<String, String>singletonMap("attribute", "value")); writer.open(executionContext); writer.close(); String content = getOutputFileContent(); assertTrue(content.contains("<testroot attribute=\"value\">")); assertTrue(content.contains("<header/>")); assertTrue(content.contains("<footer/>")); assertTrue(content.endsWith("</testroot>")); }
From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java
/** * Resource is deleted when items have not been written and shouldDeleteIfEmpty flag is set. *///w w w .j a v a2s. co m @Test public void testDeleteIfEmptyNoRecordsWrittenHeaderAndFooter() throws Exception { writer.setShouldDeleteIfEmpty(true); writer.setHeaderCallback(new StaxWriterCallback() { @Override public void write(XMLEventWriter writer) throws IOException { XMLEventFactory factory = XMLEventFactory.newInstance(); try { writer.add(factory.createStartElement("", "", "header")); writer.add(factory.createEndElement("", "", "header")); } catch (XMLStreamException e) { throw new RuntimeException(e); } } }); writer.setFooterCallback(new StaxWriterCallback() { @Override public void write(XMLEventWriter writer) throws IOException { XMLEventFactory factory = XMLEventFactory.newInstance(); try { writer.add(factory.createStartElement("", "", "footer")); writer.add(factory.createEndElement("", "", "footer")); } catch (XMLStreamException e) { throw new RuntimeException(e); } } }); writer.open(executionContext); writer.close(); assertFalse("file should be deleted" + resource, resource.getFile().exists()); }