List of usage examples for javax.xml.stream XMLEventFactory createStartElement
public abstract StartElement createStartElement(String prefix, String namespaceUri, String localName);
From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java
/** * {@inheritDoc }// ww w .j av a2 s . c om */ @Override protected InputStream addLinks(final String entitySetName, final String entitykey, final InputStream is, final Set<String> links) throws Exception { // ----------------------------------------- // 0. Build reader and writer // ----------------------------------------- final XMLEventReader reader = getEventReader(is); final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); // ----------------------------------------- final Map.Entry<Integer, XmlElement> entry = extractElement(reader, writer, Collections.singletonList("entry"), 0, 1, 1); writer.add(entry.getValue().getStart()); // add for links for (String link : links) { final Set<Attribute> attributes = new HashSet<Attribute>(); attributes.add(eventFactory.createAttribute(new QName("title"), link)); attributes.add(eventFactory.createAttribute(new QName("href"), Commons.getLinksURI(version, entitySetName, entitykey, link))); attributes.add(eventFactory.createAttribute(new QName("rel"), Constants.ATOM_LINK_REL + link)); attributes.add(eventFactory.createAttribute(new QName("type"), Commons.linkInfo.get(version).isFeed(entitySetName, link) ? Constants.ATOM_LINK_FEED : Constants.ATOM_LINK_ENTRY)); writer.add(eventFactory.createStartElement(new QName(LINK), attributes.iterator(), null)); writer.add(eventFactory.createEndElement(new QName(LINK), null)); } writer.add(entry.getValue().getContentReader()); writer.add(entry.getValue().getEnd()); writer.add(reader); IOUtils.closeQuietly(is); writer.flush(); writer.close(); reader.close(); return new ByteArrayInputStream(bos.toByteArray()); }
From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java
@Override protected InputStream replaceLink(final InputStream toBeChanged, final String linkName, final InputStream replacement) throws Exception { final XMLEventReader reader = getEventReader(toBeChanged); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent newLine = eventFactory.createSpace("\n"); try {/*from ww w. j a v a 2s .co m*/ final XmlElement linkElement = extractElement(reader, writer, Collections.<String>singletonList(LINK), Collections.<Map.Entry<String, String>>singletonList( new SimpleEntry<String, String>("title", linkName)), false, 0, -1, -1).getValue(); writer.add(linkElement.getStart()); // ------------------------------------------ // write inline ... // ------------------------------------------ writer.add(newLine); writer.add(eventFactory.createStartElement("m", null, "inline")); addAtomElement(replacement, writer); writer.add(eventFactory.createEndElement("m", null, "inline")); writer.add(newLine); // ------------------------------------------ writer.add(linkElement.getEnd()); writer.add(reader); writer.flush(); writer.close(); } finally { reader.close(); IOUtils.closeQuietly(toBeChanged); } return new ByteArrayInputStream(bos.toByteArray()); }
From source file:org.apache.olingo.fit.utils.XMLUtilities.java
/** * {@inheritDoc }// www . jav a 2s . c o m */ @Override protected InputStream addLinks(final String entitySetName, final String entitykey, final InputStream is, final Set<String> links) throws Exception { // ----------------------------------------- // 0. Build reader and writer // ----------------------------------------- final XMLEventReader reader = getEventReader(is); final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); // ----------------------------------------- final Map.Entry<Integer, XMLElement> entry = extractElement(reader, writer, Collections.singletonList("entry"), 0, 1, 1); writer.add(entry.getValue().getStart()); final Map<String, NavigationProperty> navigationProperties = metadata .getNavigationProperties(entitySetName); // add for links for (String link : links) { final Set<Attribute> attributes = new HashSet<Attribute>(); attributes.add(eventFactory.createAttribute(new QName("title"), link)); attributes.add(eventFactory.createAttribute(new QName("href"), Commons.getLinksURI(entitySetName, entitykey, link))); attributes.add(eventFactory.createAttribute(new QName("rel"), Constants.get(ConstantKey.ATOM_LINK_REL) + link)); attributes.add(eventFactory.createAttribute(new QName("type"), navigationProperties.get(link).isEntitySet() ? Constants.get(ConstantKey.ATOM_LINK_FEED) : Constants.get(ConstantKey.ATOM_LINK_ENTRY))); writer.add(eventFactory.createStartElement(new QName(Constants.get(ConstantKey.LINK)), attributes.iterator(), null)); writer.add(eventFactory.createEndElement(new QName(Constants.get(ConstantKey.LINK)), null)); } writer.add(entry.getValue().getContentReader()); writer.add(entry.getValue().getEnd()); writer.add(reader); IOUtils.closeQuietly(is); writer.flush(); writer.close(); reader.close(); return new ByteArrayInputStream(bos.toByteArray()); }
From source file:org.apache.olingo.fit.utils.XMLUtilities.java
@Override protected InputStream replaceLink(final InputStream toBeChanged, final String linkName, final InputStream replacement) throws Exception { final XMLEventReader reader = getEventReader(toBeChanged); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent newLine = eventFactory.createSpace("\n"); try {/* w w w . ja va 2 s.c om*/ final XMLElement linkElement = extractElement(reader, writer, Collections.<String>singletonList(Constants.get(ConstantKey.LINK)), Collections.<Map.Entry<String, String>>singletonList( new SimpleEntry<String, String>("title", linkName)), false, 0, -1, -1).getValue(); writer.add(linkElement.getStart()); // ------------------------------------------ // write inline ... // ------------------------------------------ writer.add(newLine); writer.add(eventFactory.createStartElement("m", null, "inline")); addAtomElement(replacement, writer); writer.add(eventFactory.createEndElement("m", null, "inline")); writer.add(newLine); // ------------------------------------------ writer.add(linkElement.getEnd()); writer.add(reader); writer.flush(); writer.close(); } finally { reader.close(); IOUtils.closeQuietly(toBeChanged); } return new ByteArrayInputStream(bos.toByteArray()); }
From source file:org.callimachusproject.behaviours.ZipArchiveSupport.java
public XMLEventReader createAtomFeedFromArchive(final String id, final String entryPattern) throws IOException { final FileObject file = this; final XMLEventFactory ef = XMLEventFactory.newInstance(); final byte[] buf = new byte[1024]; final ZipArchiveInputStream zip = new ZipArchiveInputStream(file.openInputStream()); return new XMLEventReaderBase() { private boolean started; private boolean ended; public void close() throws XMLStreamException { try { zip.close();/*from w w w.j a va 2 s . c o m*/ } catch (IOException e) { throw new XMLStreamException(e); } } protected boolean more() throws XMLStreamException { try { ZipArchiveEntry entry; if (!started) { Namespace atom = ef.createNamespace(FEED.getPrefix(), FEED.getNamespaceURI()); add(ef.createStartDocument()); add(ef.createStartElement(FEED, null, Arrays.asList(atom).iterator())); add(ef.createStartElement(TITLE, null, null)); add(ef.createCharacters(file.getName())); add(ef.createEndElement(TITLE, null)); add(ef.createStartElement(ID, null, null)); add(ef.createCharacters(id)); add(ef.createEndElement(ID, null)); Attribute href = ef.createAttribute("href", file.toUri().toASCIIString()); List<Attribute> attrs = Arrays.asList(href, ef.createAttribute("type", "application/zip")); add(ef.createStartElement(LINK, attrs.iterator(), null)); add(ef.createEndElement(LINK, null)); add(ef.createStartElement(UPDATED, null, null)); add(ef.createCharacters(format(new Date(file.getLastModified())))); add(ef.createEndElement(UPDATED, null)); started = true; return true; } else if (started && !ended && (entry = zip.getNextZipEntry()) != null) { String name = entry.getName(); String link = entryPattern.replace("{entry}", PercentCodec.encode(name)); MimetypesFileTypeMap mimetypes = new javax.activation.MimetypesFileTypeMap(); String type = mimetypes.getContentType(name); if (type == null || type.length() == 0) { type = "application/octet-stream"; } add(ef.createStartElement(ENTRY, null, null)); add(ef.createStartElement(TITLE, null, null)); add(ef.createCharacters(name)); add(ef.createEndElement(TITLE, null)); Attribute href = ef.createAttribute("href", link); List<Attribute> attrs = Arrays.asList(href, ef.createAttribute("type", type)); add(ef.createStartElement(LINK, attrs.iterator(), null)); add(ef.createEndElement(LINK, null)); long size = entry.getSize(); if (size > 0) { zip.skip(size); } else { while (zip.read(buf, 0, buf.length) >= 0) ; } add(ef.createEndElement(ENTRY, null)); return true; } else if (!ended) { add(ef.createEndElement(FEED, null)); add(ef.createEndDocument()); ended = true; return true; } else { return false; } } catch (IOException e) { throw new XMLStreamException(e); } } }; }
From source file:org.dkpro.core.io.xces.XcesBasicXmlWriter.java
@Override public void process(JCas aJCas) throws AnalysisEngineProcessException { OutputStream docOS = null;/* www. j av a2 s. c om*/ 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 v a 2 s .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.emonocot.job.io.StaxEventItemWriter.java
/** * Writes simple XML header containing:/*from w w w . ja v 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 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.omnaest.utils.xml.XMLNestedMapConverter.java
/** * @param nestedMap/*from w w w . j a v a 2 s .co 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.springframework.batch.item.xml.builder.StaxEventItemWriterBuilderTests.java
@Test public void testConfiguration() throws Exception { Map<String, String> rootElementAttributes = new HashMap<>(); rootElementAttributes.put("baz", "quix"); StaxEventItemWriter<Foo> staxEventItemWriter = new StaxEventItemWriterBuilder<Foo>().name("fooWriter") .marshaller(marshaller).encoding("UTF-16").footerCallback(writer -> { XMLEventFactory factory = XMLEventFactory.newInstance(); try { writer.add(factory.createEndElement("ns", "http://www.springframework.org/test", "group")); } catch (XMLStreamException e) { throw new RuntimeException(e); }//from w w w.j a v a 2s. co m }).headerCallback(writer -> { XMLEventFactory factory = XMLEventFactory.newInstance(); try { writer.add( factory.createStartElement("ns", "http://www.springframework.org/test", "group")); } catch (XMLStreamException e) { throw new RuntimeException(e); } }).resource(this.resource).rootTagName("foobarred").rootElementAttributes(rootElementAttributes) .saveState(false).version("1.1").build(); staxEventItemWriter.afterPropertiesSet(); ExecutionContext executionContext = new ExecutionContext(); staxEventItemWriter.open(executionContext); staxEventItemWriter.write(this.items); staxEventItemWriter.update(executionContext); staxEventItemWriter.close(); assertEquals(FULL_OUTPUT, getOutputFileContent("UTF-16")); assertEquals(0, executionContext.size()); }