List of usage examples for javax.xml.stream XMLEventWriter add
public void add(XMLEventReader reader) throws XMLStreamException;
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
/** * {@inheritDoc }/*w w w . j av a 2 s . com*/ */ @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 XMLOutputFactory xof = XMLOutputFactory.newInstance(); final XMLEventWriter writer = xof.createXMLEventWriter(bos); // ----------------------------------------- final XmlElement entry = getAtomElement(reader, writer, "entry"); writer.add(entry.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.getContentReader()); writer.add(entry.getEnd()); writer.add(reader); IOUtils.closeQuietly(is); writer.flush(); writer.close(); reader.close(); return new ByteArrayInputStream(bos.toByteArray()); }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
private InputStream writeFromStartToEndElement(final StartElement element, final XMLEventReader reader, final boolean document) throws XMLStreamException { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLOutputFactory xof = XMLOutputFactory.newInstance(); final XMLEventWriter writer = xof.createXMLEventWriter(bos); final QName name = element.getName(); if (document) { final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); writer.add(eventFactory.createStartDocument("UTF-8", "1.0")); writer.add(element);/*from ww w . java 2 s. c om*/ if (element.getAttributeByName(new QName(ATOM_DATASERVICE_NS)) == null) { writer.add(eventFactory.createNamespace(ATOM_PROPERTY_PREFIX.substring(0, 1), DATASERVICES_NS)); } if (element.getAttributeByName(new QName(ATOM_METADATA_NS)) == null) { writer.add(eventFactory.createNamespace(ATOM_METADATA_PREFIX.substring(0, 1), METADATA_NS)); } } else { writer.add(element); } XMLEvent event = element; while (reader.hasNext() && !(event.isEndElement() && name.equals(event.asEndElement().getName()))) { event = reader.nextEvent(); writer.add(event); } writer.flush(); writer.close(); return new ByteArrayInputStream(bos.toByteArray()); }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
public InputStream addAtomContent(final InputStream content, final String title, final String href) throws Exception { final XMLOutputFactory xof = XMLOutputFactory.newInstance(); final ByteArrayOutputStream copy = new ByteArrayOutputStream(); IOUtils.copy(content, copy);//from w w w. j a va 2s .co m IOUtils.closeQuietly(content); XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLEventWriter writer = xof.createXMLEventWriter(bos); try { // check edit link existence XmlElement contentElement = getAtomElement(reader, writer, "content"); writer.add(contentElement.getStart()); writer.add(contentElement.getContentReader()); writer.add(contentElement.getEnd()); writer.add(reader); } catch (Exception e) { reader.close(); reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); bos = new ByteArrayOutputStream(); writer = xof.createXMLEventWriter(bos); if (isMediaContent(title)) { final XmlElement entryElement = getAtomElement(reader, writer, "entry"); writer.add(entryElement.getStart()); writer.add(entryElement.getContentReader()); addAtomElement( IOUtils.toInputStream(String.format("<content type=\"*/*\" src=\"%s/$value\" />", href)), writer); writer.add(entryElement.getEnd()); } else { try { final XmlElement entryElement = getAtomElement(reader, writer, PROPERTIES); addAtomElement(IOUtils.toInputStream("<content type=\"application/xml\">"), writer); writer.add(entryElement.getStart()); writer.add(entryElement.getContentReader()); writer.add(entryElement.getEnd()); addAtomElement(IOUtils.toInputStream("</content>"), writer); } catch (Exception nf) { reader.close(); reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); bos = new ByteArrayOutputStream(); writer = xof.createXMLEventWriter(bos); final XmlElement entryElement = getAtomElement(reader, writer, "entry"); writer.add(entryElement.getStart()); writer.add(entryElement.getContentReader()); addAtomElement(IOUtils.toInputStream("<content type=\"application/xml\"/>"), writer); writer.add(entryElement.getEnd()); } } writer.add(reader); writer.flush(); writer.close(); } finally { reader.close(); } return new ByteArrayInputStream(bos.toByteArray()); }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
private void addAtomElement(final InputStream content, final XMLEventWriter writer) throws Exception { final XMLEventReader reader = getEventReader(content); final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent newLine = eventFactory.createSpace("\n"); try {/*from w ww .ja v a 2 s. c om*/ writer.add(newLine); while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.getEventType() != XMLStreamConstants.START_DOCUMENT && event.getEventType() != XMLStreamConstants.END_DOCUMENT && event.getEventType() != XMLStreamConstants.COMMENT) { writer.add(event); } } writer.add(newLine); } finally { reader.close(); IOUtils.closeQuietly(content); } }
From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java
/** * If the reference is more then a simple attribute, we have to add new XML (subtree) to the stream. We transform * the reference into an InputStream and invoke another SAX parsing process for it. But the parsed events are added * to the main XMLEventWriter. //from www . jav a 2 s . c o m * * @param w * @param string * @throws XMLStreamException * @throws XMLStreamException */ private void createEventsForElement(XMLEventWriter w, Reference ref) throws XMLStreamException { XMLEventReader r = null; try { StringBuilder target = new StringBuilder(ref.getTarget().toString()); NamespaceContext c = w.getNamespaceContext(); // process namespaces //processNamespace(target, w.getNamespaceContext()); ByteArrayInputStream bais = new ByteArrayInputStream(target.toString().getBytes()); this.inFac.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); r = this.inFac.createXMLEventReader(bais); // start a new line while (r.hasNext()) { XMLEvent e = r.nextEvent(); switch (e.getEventType()) { case XMLEvent.START_DOCUMENT: break; case XMLEvent.END_DOCUMENT: break; default: w.add(e); break; } } } finally { ; if (r != null) r.close(); } }
From source file:eu.delving.sip.base.Harvestor.java
private String saveRecords(HttpEntity fetchedRecords, XMLEventWriter out) throws IOException, XMLStreamException { InputStream inputStream = fetchedRecords.getContent(); XMLEventReader in = inputFactory.createXMLEventReader(new StreamSource(inputStream, "UTF-8")); Path path = Path.create(); StringBuilder tokenBuilder = null; StringBuilder errorBuilder = null; String tokenValue = null;// w w w . ja v a2 s . c o m List<XMLEvent> recordEvents = new ArrayList<XMLEvent>(); boolean finished = false; while (!finished) { XMLEvent event = in.nextEvent(); switch (event.getEventType()) { case XMLEvent.START_ELEMENT: StartElement start = event.asStartElement(); path = path.child(Tag.element(start.getName().getLocalPart())); if (!recordEvents.isEmpty()) { recordEvents.add(event); } else if (path.equals(RECORD_ROOT)) { if (namespaceCollector != null) { namespaceCollector.gatherFrom(start); out.add(eventFactory.createStartElement("", "", HARVEST_TAG, null, namespaceCollector.iterator())); out.add(eventFactory.createCharacters("\n")); namespaceCollector = null; } recordEvents.add(eventFactory.createCharacters("\n")); // flag that record has started } else if (path.equals(RESUMPTION_TOKEN)) { tokenBuilder = new StringBuilder(); tokenValue = null; } else if (path.equals(ERROR)) { errorBuilder = new StringBuilder(); } else if (namespaceCollector != null) { namespaceCollector.gatherFrom(start); } break; case XMLEvent.END_ELEMENT: if (!recordEvents.isEmpty()) { if (path.equals(RECORD_ROOT)) { out.add(eventFactory.createStartElement("", "", RECORD_TAG, null, null)); for (XMLEvent saved : recordEvents) { out.add(saved); } out.add(eventFactory.createEndElement("", "", RECORD_TAG)); out.add(eventFactory.createCharacters("\n")); recordEvents.clear(); tokenBuilder = null; recordCount++; } else { recordEvents.add(event); recordEvents.add(eventFactory.createCharacters("\n")); } } else if (path.equals(RESUMPTION_TOKEN) && tokenBuilder != null) { tokenValue = tokenBuilder.toString(); tokenBuilder = null; } else if (path.equals(ERROR) && errorBuilder != null) { throw new IOException("OAI-PMH Error: " + errorBuilder); } path = path.parent(); break; case XMLEvent.END_DOCUMENT: finished = true; break; case XMLEvent.CHARACTERS: case XMLEvent.CDATA: if (!recordEvents.isEmpty()) { String string = event.asCharacters().getData().trim(); if (!string.isEmpty()) { recordEvents.add(eventFactory.createCharacters(string)); } } else if (tokenBuilder != null) { tokenBuilder.append(event.asCharacters().getData()); } else if (errorBuilder != null) { errorBuilder.append(event.asCharacters().getData()); } break; default: if (!recordEvents.isEmpty()) { recordEvents.add(event); } break; } } return tokenValue; }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
private InputStream addAtomEditLink(final InputStream content, final String title, final String href) throws Exception { final XMLOutputFactory xof = XMLOutputFactory.newInstance(); final ByteArrayOutputStream copy = new ByteArrayOutputStream(); IOUtils.copy(content, copy);//from w ww . j a va 2s.co m IOUtils.closeQuietly(content); XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLEventWriter writer = xof.createXMLEventWriter(bos); try { // check edit link existence final XmlElement editLink = getAtomElement(reader, writer, LINK, Collections.<Map.Entry<String, String>>singletonList( new AbstractMap.SimpleEntry<String, String>("rel", "edit"))); writer.add(editLink.getStart()); writer.add(editLink.getContentReader()); writer.add(editLink.getEnd()); writer.add(reader); } catch (Exception e) { reader.close(); reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); bos = new ByteArrayOutputStream(); writer = xof.createXMLEventWriter(bos); final XmlElement entryElement = getAtomElement(reader, writer, "entry"); writer.add(entryElement.getStart()); addAtomElement(IOUtils.toInputStream( String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href)), writer); writer.add(entryElement.getContentReader()); writer.add(entryElement.getEnd()); writer.add(reader); writer.flush(); writer.close(); } finally { reader.close(); } return new ByteArrayInputStream(bos.toByteArray()); }
From source file:com.msopentech.odatajclient.testservice.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 XMLOutputFactory xof = XMLOutputFactory.newInstance(); final XMLEventWriter writer = xof.createXMLEventWriter(bos); final XMLEventFactory eventFactory = XMLEventFactory.newInstance(); XMLEvent newLine = eventFactory.createSpace("\n"); try {/*from w w w . ja v a 2 s. co m*/ final XmlElement linkElement = getAtomElement(reader, writer, LINK, Collections.<Map.Entry<String, String>>singletonList( new SimpleEntry<String, String>("title", linkName))); 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:com.aionengine.gameserver.dataholders.loadingutils.XmlMerger.java
/** * This method processes the source file, replacing all of * the 'import' tags by the data from the relevant files. * * @throws XMLStreamException on event writing error. * @throws IOException if the destination file exists but is a directory rather than * a regular file, does not exist but cannot be created, * or cannot be opened for any other reason *///from w w w . ja v a 2 s . c o m private void doUpdate() throws XMLStreamException, IOException { XMLEventReader reader = null; XMLEventWriter writer = null; Properties metadata = new Properties(); try { writer = outputFactory.createXMLEventWriter(new BufferedWriter(new FileWriter(destFile, false))); reader = inputFactory.createXMLEventReader(new FileReader(sourceFile)); while (reader.hasNext()) { final XMLEvent xmlEvent = reader.nextEvent(); if (xmlEvent.isStartElement() && isImportQName(xmlEvent.asStartElement().getName())) { processImportElement(xmlEvent.asStartElement(), writer, metadata); continue; } if (xmlEvent.isEndElement() && isImportQName(xmlEvent.asEndElement().getName())) continue; if (xmlEvent instanceof Comment)// skip comments. continue; if (xmlEvent.isCharacters())// skip whitespaces. if (xmlEvent.asCharacters().isWhiteSpace() || xmlEvent.asCharacters().isIgnorableWhiteSpace())// skip whitespaces. continue; writer.add(xmlEvent); if (xmlEvent.isStartDocument()) { writer.add(eventFactory.createComment("\nThis file is machine-generated. DO NOT MODIFY IT!\n")); } } storeFileModifications(metadata, metaDataFile); } finally { if (writer != null) try { writer.close(); } catch (Exception ignored) { } if (reader != null) try { reader.close(); } catch (Exception ignored) { } } }
From source file:eu.peppol.document.PayloadParserTest.java
/** * Takes a file holding an SBD/SBDH with an ASiC archive in base64 as payload and extracts the ASiC archive in binary format, while * calculating the message digest./* ww w. j a va 2 s. co m*/ * * @throws Exception */ @Test public void parseSampleSbdWithAsic() throws Exception { InputStream resourceAsStream = PayloadParserTest.class.getClassLoader() .getResourceAsStream("sample-sbd-with-asic.xml"); assertNotNull(resourceAsStream); Path xmlFile = Files.createTempFile("unit-test", ".xml"); XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(resourceAsStream, "UTF-8"); FileOutputStream outputStream = new FileOutputStream(xmlFile.toFile()); XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(outputStream, "UTF-8"); Path asicFile = Files.createTempFile("unit-test", ".asice"); OutputStream asicOutputStream = Files.newOutputStream(asicFile); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); DigestOutputStream digestOutputStream = new DigestOutputStream(asicOutputStream, messageDigest); Base64OutputStream base64OutputStream = new Base64OutputStream(digestOutputStream, false); boolean insideAsicElement = false; while (xmlEventReader.hasNext()) { XMLEvent xmlEvent = xmlEventReader.nextEvent(); switch (xmlEvent.getEventType()) { case XMLEvent.START_ELEMENT: String localPart = xmlEvent.asStartElement().getName().getLocalPart(); if ("asic".equals(localPart)) { insideAsicElement = true; } break; case XMLEvent.END_ELEMENT: localPart = xmlEvent.asEndElement().getName().getLocalPart(); if ("asic".equals(localPart)) { insideAsicElement = false; } break; case XMLEvent.CHARACTERS: // Whenever we are inside the ASiC XML element, spit // out the base64 encoded data into the base64 decoding output stream. if (insideAsicElement) { Characters characters = xmlEvent.asCharacters(); base64OutputStream.write(characters.getData().getBytes("UTF-8")); } break; } xmlEventWriter.add(xmlEvent); } asicOutputStream.close(); outputStream.close(); log.debug("Wrote xml output to: " + xmlFile); log.debug("Wrote ASiC to:" + asicFile); log.debug("Digest: " + new String(Base64.getEncoder().encode(messageDigest.digest()))); }