List of usage examples for javax.xml.stream XMLEventWriter add
public void add(XMLEventReader reader) throws XMLStreamException;
From source file:org.mule.transport.sap.transformer.JcoFunctionToXmlTransformer.java
private void writeCharacters(XMLEventWriter writer, String characters) throws XMLStreamException { XMLEvent event = eventFactory.createCharacters(characters); writer.add(event); }
From source file:org.mule.transport.sap.transformer.JcoFunctionToXmlTransformer.java
private void writeStartDocument(XMLEventWriter writer) throws XMLStreamException { XMLEvent event = eventFactory.createStartDocument(); writer.add(event); }
From source file:org.mule.transport.sap.transformer.JcoFunctionToXmlTransformer.java
private void writeEndDocument(XMLEventWriter writer) throws XMLStreamException { XMLEvent event = eventFactory.createEndDocument(); writer.add(event); }
From source file:org.omnaest.utils.xml.XMLNestedMapConverter.java
/** * @param nestedMap//www.java 2 s .c o m * {@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 . co 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
protected void processXMLEvent(XMLEventWriter out, XMLEvent event) throws XMLStreamException { out.add(event); }
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 w w .j a va 2 s .co m } 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.StaxEventItemWriter.java
/** * Writes simple XML header containing:/*from ww w . j av a 2 s .c o m*/ * <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 */ protected void startDocument(XMLEventWriter writer) throws XMLStreamException { XMLEventFactory factory = createXmlEventFactory(); // 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.springframework.batch.item.xml.StaxEventItemWriterTests.java
/** * Item is written to the output file only after flush. *//* w w w .j av a2s.co m*/ @Test public void testWriteWithHeader() 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.open(executionContext); writer.write(items); String content = getOutputFileContent(); assertTrue("Wrong content: " + content, content.contains(("<header/>"))); assertTrue("Wrong content: " + content, content.contains(TEST_STRING)); }
From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java
/** * Open method writes the root tag, close method adds corresponding end tag. *//*from w w w.j ava 2 s . c om*/ @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>")); }