List of usage examples for javax.xml.stream XMLEventWriter close
public void close() throws XMLStreamException;
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);/* w ww .j a v a2 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.aionemu.gameserver.dataholders.loadingutils.XmlMerger.java
/** * This method processes the source file, replacing all of the 'import' tags * by the data from the relevant files.//w ww .j a v a2 s . com * * @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 */ 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: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.jav a 2s.c o 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.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);// w w w .j av a 2 s . com 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
/** * {@inheritDoc }//from w w w.j a v a 2 s.co 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 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
/** * {@inheritDoc }/* w w w . j av a2s.co m*/ */ @Override protected InputStream normalizeLinks(final String entitySetName, final String entityKey, final InputStream is, final NavigationLinks links) throws Exception { // ----------------------------------------- // 0. Build reader and writer // ----------------------------------------- final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(is, bos); is.close(); final ByteArrayOutputStream tmpBos = new ByteArrayOutputStream(); final XMLOutputFactory xof = XMLOutputFactory.newInstance(); final XMLEventWriter writer = xof.createXMLEventWriter(tmpBos); final XMLEventReader reader = getEventReader(new ByteArrayInputStream(bos.toByteArray())); // ----------------------------------------- // ----------------------------------------- // 1. Normalize links // ----------------------------------------- final Set<String> added = new HashSet<String>(); try { final List<Map.Entry<String, String>> filter = new ArrayList<Map.Entry<String, String>>(); filter.add(new AbstractMap.SimpleEntry<String, String>("type", "application/atom+xml;type=entry")); filter.add(new AbstractMap.SimpleEntry<String, String>("type", "application/atom+xml;type=feed")); Map.Entry<Integer, XmlElement> linkInfo = null; while (true) { // a. search for link with type attribute equals to "application/atom+xml;type=entry/feed" linkInfo = getAtomElement(reader, writer, LINK, filter, linkInfo == null ? 0 : linkInfo.getKey(), 2, 2, true); final XmlElement link = linkInfo.getValue(); final String title = link.getStart().getAttributeByName(new QName("title")).getValue(); if (!added.contains(title)) { added.add(title); final String normalizedLink = String.format( "<link href=\"%s(%s)/%s\" rel=\"%s\" title=\"%s\" type=\"%s\"/>", entitySetName, entityKey, title, link.getStart().getAttributeByName(new QName("rel")).getValue(), title, link.getStart().getAttributeByName(new QName("type")).getValue()); addAtomElement(IOUtils.toInputStream(normalizedLink), writer); } } } catch (Exception ignore) { // ignore } finally { writer.close(); reader.close(); } // ----------------------------------------- // ----------------------------------------- // 2. Add edit link if missing // ----------------------------------------- final InputStream content = addAtomEditLink(new ByteArrayInputStream(tmpBos.toByteArray()), entitySetName, Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")"); // ----------------------------------------- // ----------------------------------------- // 3. Add content element if missing // ----------------------------------------- return addAtomContent(content, entitySetName, Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")"); // ----------------------------------------- }
From source file:WpRDFFunctionLibrary.java
public static void mergeGpmltoSingleFile(String gpmlLocation) throws IOException, XMLStreamException, ParserConfigurationException, SAXException, TransformerException { // Based on: http://stackoverflow.com/questions/10759775/how-to-merge-1000-xml-files-into-one-in-java //for (int i = 1; i < 8 ; i++) { Writer outputWriter = new FileWriter("/tmp/WpGPML.xml"); XMLOutputFactory xmlOutFactory = XMLOutputFactory.newFactory(); XMLEventWriter xmlEventWriter = xmlOutFactory.createXMLEventWriter(outputWriter); XMLEventFactory xmlEventFactory = XMLEventFactory.newFactory(); xmlEventWriter.add(xmlEventFactory.createStartDocument("ISO-8859-1", "1.0")); xmlEventWriter.add(xmlEventFactory.createStartElement("", null, "PathwaySet")); xmlEventWriter.add(xmlEventFactory.createAttribute("creationData", basicCalls.now())); XMLInputFactory xmlInFactory = XMLInputFactory.newFactory(); File dir = new File(gpmlLocation); File[] rootFiles = dir.listFiles(); //the section below is only in case of analysis sets for (File rootFile : rootFiles) { String fileName = FilenameUtils.removeExtension(rootFile.getName()); System.out.println(fileName); String[] identifiers = fileName.split("_"); System.out.println(fileName); String wpIdentifier = identifiers[identifiers.length - 2]; String wpRevision = identifiers[identifiers.length - 1]; //Pattern pattern = Pattern.compile("_(WP[0-9]+)_([0-9]+).gpml"); //Matcher matcher = pattern.matcher(fileName); //System.out.println(matcher.find()); //String wpIdentifier = matcher.group(1); File tempFile = new File(constants.localAllGPMLCacheDir() + wpIdentifier + "_" + wpRevision + ".gpml"); //System.out.println(matcher.group(1)); //String wpRevision = matcher.group(2); //System.out.println(matcher.group(2)); if (!(tempFile.exists())) { System.out.println(tempFile.getName()); Document currentGPML = basicCalls.openXmlFile(rootFile.getPath()); basicCalls.saveDOMasXML(WpRDFFunctionLibrary.addWpProvenance(currentGPML, wpIdentifier, wpRevision), constants.localCurrentGPMLCache() + tempFile.getName()); }//from w w w . j a va2 s . c om } dir = new File("/tmp/GPML"); rootFiles = dir.listFiles(); for (File rootFile : rootFiles) { System.out.println(rootFile); XMLEventReader xmlEventReader = xmlInFactory.createXMLEventReader(new StreamSource(rootFile)); XMLEvent event = xmlEventReader.nextEvent(); // Skip ahead in the input to the opening document element try { while (event.getEventType() != XMLEvent.START_ELEMENT) { event = xmlEventReader.nextEvent(); } do { xmlEventWriter.add(event); event = xmlEventReader.nextEvent(); } while (event.getEventType() != XMLEvent.END_DOCUMENT); xmlEventReader.close(); } catch (Exception e) { System.out.println("Malformed gpml file"); } } xmlEventWriter.add(xmlEventFactory.createEndElement("", null, "PathwaySet")); xmlEventWriter.add(xmlEventFactory.createEndDocument()); xmlEventWriter.close(); outputWriter.close(); }
From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java
@Override public InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties) throws Exception { XMLEventReader reader = getEventReader(toBeChanged); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLEventWriter writer = xof.createXMLEventWriter(bos); // --------------------------------- // add property changes // --------------------------------- Map.Entry<Integer, XmlElement> propertyElement = getAtomElement(reader, writer, PROPERTIES, null, 0, 2, 3, false);//from w w w . j a v a 2 s. com writer.flush(); ByteArrayOutputStream pbos = new ByteArrayOutputStream(); OutputStreamWriter pwriter = new OutputStreamWriter(pbos); final XMLEventReader propertyReader = propertyElement.getValue().getContentReader(); try { while (true) { final XmlElement property = getAtomElement(propertyReader, null, null); final String name = property.getStart().getName().getLocalPart(); if (properties.containsKey(name)) { // replace final InputStream replacement = properties.get(name); properties.remove(property.getStart().getName().getLocalPart()); pwriter.append(IOUtils.toString(replacement)); IOUtils.closeQuietly(replacement); } else { pwriter.append(IOUtils.toString(property.toStream())); } } } catch (Exception ignore) { // end } for (Map.Entry<String, InputStream> remains : properties.entrySet()) { if (!remains.getKey().startsWith("[LINK]")) { pwriter.append(IOUtils.toString(remains.getValue())); IOUtils.closeQuietly(remains.getValue()); } } pwriter.flush(); pwriter.close(); writer.add(propertyElement.getValue().getStart()); writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray()))); writer.add(propertyElement.getValue().getEnd()); IOUtils.closeQuietly(pbos); writer.add(reader); reader.close(); writer.flush(); writer.close(); // --------------------------------- // --------------------------------- // add navigationm changes // --------------------------------- // remove existent links for (Map.Entry<String, InputStream> remains : properties.entrySet()) { if (remains.getKey().startsWith("[LINK]")) { reader = getEventReader(new ByteArrayInputStream(bos.toByteArray())); bos.reset(); writer = xof.createXMLEventWriter(bos); try { final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1); getAtomElement(reader, writer, LINK, Collections.<Map.Entry<String, String>>singleton( new SimpleEntry<String, String>("title", linkName)), 0, 2, 2, false); writer.add(reader); } catch (Exception ignore) { // ignore } writer.flush(); writer.close(); } } reader = getEventReader(new ByteArrayInputStream(bos.toByteArray())); bos.reset(); writer = xof.createXMLEventWriter(bos); propertyElement = getAtomElement(reader, writer, CONTENT, null, 0, 2, 2, false); writer.flush(); pbos.reset(); pwriter = new OutputStreamWriter(pbos); for (Map.Entry<String, InputStream> remains : properties.entrySet()) { if (remains.getKey().startsWith("[LINK]")) { pwriter.append(IOUtils.toString(remains.getValue())); IOUtils.closeQuietly(remains.getValue()); } } pwriter.flush(); pwriter.close(); writer.add(new XMLEventReaderWrapper(new ByteArrayInputStream(pbos.toByteArray()))); IOUtils.closeQuietly(pbos); writer.add(propertyElement.getValue().getStart()); writer.add(propertyElement.getValue().getContentReader()); writer.add(propertyElement.getValue().getEnd()); writer.add(reader); reader.close(); 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 ww w. j ava 2 s. c o 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
@Override public InputStream selectEntity(final InputStream entity, final String[] propertyNames) throws Exception { final XMLEventReader reader = getEventReader(entity); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLOutputFactory xof = XMLOutputFactory.newInstance(); final XMLEventWriter writer = xof.createXMLEventWriter(bos); final List<String> found = new ArrayList<String>(Arrays.asList(propertyNames)); boolean inProperties = false; boolean writeCurrent = true; Boolean writeNext = null;/*from w ww. ja va 2s .c o m*/ String currentName = null; final List<String> fieldToBeSaved = new ArrayList<String>(Arrays.asList(propertyNames)); while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.getEventType() == XMLStreamConstants.START_ELEMENT && LINK.equals(event.asStartElement().getName().getLocalPart()) && !fieldToBeSaved .contains(event.asStartElement().getAttributeByName(new QName("title")).getValue()) && !"edit".equals(event.asStartElement().getAttributeByName(new QName("rel")).getValue())) { writeCurrent = false; } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && LINK.equals(event.asEndElement().getName().getLocalPart())) { writeNext = true; } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT && (PROPERTIES).equals(event.asStartElement().getName().getLocalPart())) { writeCurrent = true; writeNext = false; inProperties = true; } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && (PROPERTIES).equals(event.asEndElement().getName().getLocalPart())) { writeCurrent = true; } else if (inProperties) { if (event.getEventType() == XMLStreamConstants.START_ELEMENT) { final String elementName = event.asStartElement().getName().getLocalPart(); for (String propertyName : propertyNames) { if ((ATOM_PROPERTY_PREFIX + propertyName.trim()).equals(elementName)) { writeCurrent = true; found.remove(propertyName); currentName = propertyName; } } } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && StringUtils.isNotBlank(currentName) && (ATOM_PROPERTY_PREFIX + currentName.trim()) .equals(event.asEndElement().getName().getLocalPart())) { writeNext = false; currentName = null; } } if (writeCurrent) { writer.add(event); } if (writeNext != null) { writeCurrent = writeNext; writeNext = null; } } writer.flush(); writer.close(); reader.close(); IOUtils.closeQuietly(entity); // Do not raise any exception in order to support FC properties as well // if (!found.isEmpty()) { // throw new Exception(String.format("Could not find a properties '%s'", found)); // } return new ByteArrayInputStream(bos.toByteArray()); }