public InputStream addAtomInlinecount(final InputStream feed, final int count) throws Exception { final XMLEventReader reader = getEventReader(feed); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); try { final XMLElement feedElement = extractElement(reader, writer, Collections.<String>singletonList("feed"), 0, 1, 1) .getValue(); writer.add(feedElement.getStart()); addAtomElement( IOUtils.toInputStream(String.format("<m:count>%d</m:count>", count), Constants.ENCODING), writer); writer.add(feedElement.getContentReader()); writer.add(feedElement.getEnd()); while (reader.hasNext()) { writer.add(reader.nextEvent()); } } finally { writer.flush(); writer.close(); reader.close(); IOUtils.closeQuietly(feed); } return new ByteArrayInputStream(bos.toByteArray()); }
private static void eventWriter(OutputStream out) throws XMLStreamException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); // factory.setProperty(name, value); XMLEventWriter writer = factory.createXMLEventWriter(out); XMLEventFactory ef = XMLEventFactory2.newInstance(); StartDocument startDocument = ef.createStartDocument("UTF-8", "1.0"); writer.add(startDocument); StartElement booksStartElement = ef.createStartElement("bk", Const.NSURI_BOOK, "books"); writer.add(booksStartElement); writer.add(ef.createNamespace("bk", Const.NSURI_BOOK)); for (int i = 0; i < Const.NODE_COUNTS_L; ++i) { writer.add(ef.createStartElement("bk", Const.NSURI_BOOK, "book")); writer.add(ef.createAttribute("id", String.valueOf(i + 1))); writer.add(ef.createStartElement("bk", Const.NSURI_BOOK, "name")); writer.add(ef.createCharacters("Name" + (i + 1))); writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "name")); writer.add(ef.createStartElement("bk", Const.NSURI_BOOK, "author")); writer.add(ef.createCharacters("author" + (i + 1))); writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "author")); writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "book")); } writer.add(ef.createEndElement("bk", Const.NSURI_BOOK, "books")); writer.add(ef.createEndDocument()); writer.close(); }
@Override public InputStream addEditLink(final InputStream content, final String title, final String href) throws Exception { final ByteArrayOutputStream copy = new ByteArrayOutputStream(); IOUtils.copy(content, copy); IOUtils.closeQuietly(content); XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLEventWriter writer = getEventWriter(bos); final String editLinkElement = String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href); try { // check edit link existence extractElement( reader, writer, Collections.<String>singletonList(Constants.get(ConstantKey.LINK)), Collections.<Map.Entry<String, String>>singletonList( new AbstractMap.SimpleEntry<String, String>("rel", "edit")), false, 0, -1, -1); addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer); writer.add(reader); } catch (Exception e) { reader.close(); reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); bos = new ByteArrayOutputStream(); writer = getEventWriter(bos); final XMLElement entryElement = extractElement(reader, writer, Collections.<String>singletonList("entry"), 0, 1, 1) .getValue(); writer.add(entryElement.getStart()); addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer); writer.add(entryElement.getContentReader()); writer.add(entryElement.getEnd()); writer.add(reader); writer.flush(); writer.close(); } finally { reader.close(); } return new ByteArrayInputStream(bos.toByteArray()); }
@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); changesReader.close(); writer.add(reader); reader.close(); IOUtils.closeQuietly(src); writer.flush(); writer.close(); return new ByteArrayInputStream(bos.toByteArray()); }
public static String xmlToJson(String xml, boolean formatted) throws XMLStreamException { InputStream input = new ByteArrayInputStream(xml.getBytes()); ByteArrayOutputStream output = new ByteArrayOutputStream(); JsonXMLConfig config = new JsonXMLConfigBuilder() .autoArray(true) .autoPrimitive(true) .prettyPrint(formatted) .build(); try { XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input); XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output); writer.add(reader); reader.close(); writer.close(); try { return output.toString("UTF-8"); } catch (UnsupportedEncodingException e) { throw new XMLStreamException(e.getMessage()); } } finally { // dp nothing } }
/** {@inheritDoc } */ @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()); }
@Override public InputStream replaceProperty( final InputStream src, final InputStream replacement, final List<String> path, final boolean justValue) throws Exception { final List<String> pathElements = new ArrayList<String>(); for (String element : path) { pathElements.add(Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + element); } final XMLEventReader reader = getEventReader(src); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); final Map.Entry<Integer, XMLElement> element = extractElement(reader, writer, pathElements, 0, 3, 4); if (justValue) { writer.add(element.getValue().getStart()); } final XMLEventReader changesReader = new XMLEventReaderWrapper(replacement); while (changesReader.hasNext()) { final XMLEvent event = changesReader.nextEvent(); if (event.isStartElement() && event.asStartElement().getName().equals(element.getValue().getStart().getName())) { writer.add(element.getValue().getStart()); writer.add(changesReader); } else { writer.add(event); } } changesReader.close(); IOUtils.closeQuietly(replacement); if (justValue) { writer.add(element.getValue().getEnd()); } writer.add(reader); reader.close(); IOUtils.closeQuietly(src); writer.flush(); writer.close(); return new ByteArrayInputStream(bos.toByteArray()); }
@Override public void close() throws WriterException { try { eventWriter.add(eventFactory.createEndElement("", "", DOC_ELEMENT_NAME)); eventWriter.add(end); eventWriter.add(eventFactory.createEndDocument()); eventWriter.close(); } catch (XMLStreamException e) { throw new WriterException("unable to close stream for file: " + xmlFile, e); } }
protected byte[] object2WbXml( Object o, WbXmlDefinition def, WbXmlVersion version, WbXmlEncoder.StrtblType encoderType, boolean skipSpaces, boolean event) throws Exception { XMLStreamWriter xmlStreamWriter = null; XMLEventWriter xmlEventWriter = null; ByteArrayOutputStream out = null; try { out = new ByteArrayOutputStream(); outFact.setProperty(WbXmlOutputFactory.ENCODING_TYPE_PROPERTY, encoderType); outFact.setProperty(WbXmlOutputFactory.SKIP_SPACES_PROPERTY, skipSpaces); outFact.setProperty(WbXmlOutputFactory.VERSION_PROPERTY, version); outFact.setProperty(WbXmlOutputFactory.DEFINITION_PROPERTY, def); if (event) { xmlEventWriter = outFact.createXMLEventWriter(out); } else { xmlStreamWriter = outFact.createXMLStreamWriter(out); } JAXBContext jc = JAXBContext.newInstance(o.getClass()); Marshaller marshaller = jc.createMarshaller(); if (event) { marshaller.marshal(o, xmlEventWriter); } else { marshaller.marshal(o, xmlStreamWriter); } return out.toByteArray(); } finally { if (out != null) { try { out.close(); } catch (Exception e) { } } if (xmlStreamWriter != null) { try { xmlStreamWriter.close(); } catch (Exception e) { } } if (xmlEventWriter != null) { try { xmlEventWriter.close(); } catch (Exception e) { } } } }
@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 { 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()); }
protected byte[] doc2WbXml( Document doc, WbXmlDefinition def, WbXmlVersion version, WbXmlEncoder.StrtblType encoderType, boolean skipSpaces, boolean event) throws Exception { XMLStreamWriter xmlStreamWriter = null; XMLEventWriter xmlEventWriter = null; ByteArrayOutputStream out = null; try { out = new ByteArrayOutputStream(); outFact.setProperty(WbXmlOutputFactory.ENCODING_TYPE_PROPERTY, encoderType); outFact.setProperty(WbXmlOutputFactory.SKIP_SPACES_PROPERTY, skipSpaces); outFact.setProperty(WbXmlOutputFactory.VERSION_PROPERTY, version); outFact.setProperty(WbXmlOutputFactory.DEFINITION_PROPERTY, def); if (event) { xmlEventWriter = outFact.createXMLEventWriter(out); } else { xmlStreamWriter = outFact.createXMLStreamWriter(out); } Transformer xformer = TransformerFactory.newInstance().newTransformer(); Source domSource = new DOMSource(doc); StAXResult staxResult = (event) ? new StAXResult(xmlEventWriter) : new StAXResult(xmlStreamWriter); xformer.transform(domSource, staxResult); return out.toByteArray(); } finally { if (out != null) { try { out.close(); } catch (Exception e) { } } if (xmlStreamWriter != null) { try { xmlStreamWriter.close(); } catch (Exception e) { } } if (xmlEventWriter != null) { try { xmlEventWriter.close(); } catch (Exception e) { } } } }
private void read(Source source) throws IOException, XMLStreamException { // Read in XML, extracting and removing the updates list in the process StringWriter buffer = new StringWriter(BUFFER_SIZE); XMLEventWriter eventWriter = this.xmlOutputFactory.createXMLEventWriter(buffer); XMLEventReader eventReader = this.xmlInputFactory.createXMLEventReader(source); UpdatesXMLEventReader updatesReader = new UpdatesXMLEventReader(eventReader); eventWriter.add(updatesReader); eventWriter.close(); eventReader.close(); // Was the update list found? List<String> updateNames = updatesReader.getUpdates(); if (updateNames == null) throw new PersistentObjectException("XML file does not contain an updates list"); // Save current content (without updates) and updates list this.current = buffer.toString(); this.updates.clear(); this.updates.addAll(updateNames); }
public void testEncodingXmlEventReader() throws Exception { TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM.reset(); XMLEventReader reader = null; XMLEventWriter writer = null; ByteArrayOutputStream output = null; try { // enter text encoded with Latin1 reader = context .getTypeConverter() .mandatoryConvertTo( XMLEventReader.class, TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM); output = new ByteArrayOutputStream(); // ensure UTF-8 encoding Exchange exchange = new DefaultExchange(context); exchange.setProperty(Exchange.CHARSET_NAME, UTF_8.name()); writer = context.getTypeConverter().mandatoryConvertTo(XMLEventWriter.class, exchange, output); while (reader.hasNext()) { writer.add(reader.nextEvent()); } } finally { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } assertNotNull(output); String result = new String(output.toByteArray(), UTF_8.name()); boolean equals = TEST_XML_WITH_XML_HEADER.equals(result) || TEST_XML_WITH_XML_HEADER_ISO_8859_1.equals(result); assertTrue("Should match header", equals); }
/** * Write to xml. * * @param d the d * @return the string * @throws XMLStreamException the xML stream exception */ public final String writeToXML(final DatatypeDesc d) throws XMLStreamException { // Create a XMLOutputFactory XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); // Create XMLEventWriter ByteArrayOutputStream bout = new ByteArrayOutputStream(); XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(bout); // Create a EventFactory XMLEventFactory eventFactory = XMLEventFactory.newInstance(); // end = eventFactory.createDTD("\n"); XMLEvent end = eventFactory.createCharacters("\n"); // XMLEvent tab = eventFactory.createCharacters("\t"); // Create and write Start Tag StartDocument startDocument = eventFactory.createStartDocument(); eventWriter.add(startDocument); // Create config open tag StartElement startElement = eventFactory.createStartElement(PREFIX, URI, "datatypeDesc"); eventWriter.add(startElement); eventWriter.add(eventFactory.createNamespace(PREFIX, URI)); // TODO namespace und schema einkommentieren // eventWriter.add(eventFactory.createAttribute("xmlns:xsi", // "http://www.w3.org/2001/XMLSchema-instance")); // eventWriter.add(eventFactory.createAttribute("xsi:schemaLocation", // "http://pdr.bbaw.de/namespaces/dtdl/ http://pdr.bbaw.de/schema/dtdl.xsd")); eventWriter.add(eventFactory.createAttribute("provider", d.getProvider())); eventWriter.add(end); // Write the different nodes if (d.getDocumentation() != null) { createNode(eventWriter, "documentation", d.getDocumentation(), PREFIX, URI); } if (d.getUsage() != null) { startElement = eventFactory.createStartElement(PREFIX, URI, "usage"); eventWriter.add(startElement); eventWriter.add(end); if (d.getUsage().getDocumentation() != null) { createNode(eventWriter, "documentation", d.getUsage().getDocumentation(), PREFIX, URI); } if (d.getUsage().getUsageDisplay() != null) { startElement = eventFactory.createStartElement(PREFIX, URI, "display"); eventWriter.add(startElement); eventWriter.add(end); if (d.getUsage().getUsageDisplay().getDocumentation() != null) { createNode( eventWriter, "documentation", d.getUsage().getUsageDisplay().getDocumentation(), PREFIX, URI); } if (d.getUsage().getUsageDisplay().getPersonNameTag() != null) { for (String s : d.getUsage().getUsageDisplay().getPersonNameTag()) { createNode(eventWriter, "nameTag", s, PREFIX, URI); } } if (d.getUsage().getUsageDisplay().getPersonNormNameTag() != null) { for (String s : d.getUsage().getUsageDisplay().getPersonNormNameTag()) { createNode(eventWriter, "displayNameTag", s, PREFIX, URI); } } eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "display")); eventWriter.add(end); } if (d.getUsage().getTemplates() != null) { startElement = eventFactory.createStartElement(PREFIX, URI, "templates"); eventWriter.add(startElement); eventWriter.add(end); if (d.getUsage().getTemplates() != null && !d.getUsage().getTemplates().getChildren().isEmpty()) { for (String key : d.getUsage().getTemplates().getChildren().keySet()) { ConfigData cd = d.getUsage().getTemplates().getChildren().get(key); // aspectTemplates startElement = eventFactory.createStartElement(PREFIX, URI, key); eventWriter.add(startElement); eventWriter.add(end); if (cd.getChildren() != null) { for (String key2 : cd.getChildren().keySet()) { ConfigData cd2 = cd.getChildren().get(key2); startElement = eventFactory.createStartElement(PREFIX, URI, key2); // semanticTemplates // and // complexTemplates eventWriter.add(startElement); eventWriter.add( eventFactory.createAttribute("ignore", new Boolean(cd2.isIgnore()).toString())); eventWriter.add(end); if (cd2.getChildren() != null) { for (String key3 : cd2.getChildren().keySet()) { ConfigData cd3 = cd2.getChildren().get(key3); if (cd3 instanceof SemanticTemplate) { SemanticTemplate semanticTemplate = (SemanticTemplate) cd3; createNode(eventWriter, semanticTemplate); } else { if (cd3 instanceof ComplexSemanticTemplate) // complexTemplate { ComplexSemanticTemplate complexTemplate = (ComplexSemanticTemplate) cd3; startElement = eventFactory.createStartElement( PREFIX, URI, "complexTemplate"); // semanticTemplates eventWriter.add(startElement); eventWriter.add( eventFactory.createAttribute("value", complexTemplate.getValue())); eventWriter.add( eventFactory.createAttribute("label", complexTemplate.getLabel())); eventWriter.add( eventFactory.createAttribute( "priority", new Integer(complexTemplate.getPriority()).toString())); eventWriter.add(end); if (cd3.getChildren() != null) { for (String key4 : cd3.getChildren().keySet()) { ConfigData cd4 = cd3.getChildren().get(key4); if (cd4 instanceof SemanticTemplate) { SemanticTemplate semanticTemplate = (SemanticTemplate) cd4; createNode(eventWriter, semanticTemplate); } else { } } } if (complexTemplate.getDocumentation() != null) { createNode( eventWriter, "documentation", complexTemplate.getDocumentation(), PREFIX, URI); } eventWriter.add( eventFactory.createEndElement(PREFIX, URI, "complexTemplate")); eventWriter.add(end); } else { startElement = eventFactory.createStartElement(PREFIX, URI, key3); // semanticTemplates eventWriter.add(startElement); eventWriter.add(end); if (cd3.getChildren() != null) { for (String key4 : cd3.getChildren().keySet()) { ConfigData cd4 = cd3.getChildren().get(key4); if (cd4 instanceof SemanticTemplate) { SemanticTemplate semanticTemplate = (SemanticTemplate) cd4; createNode(eventWriter, semanticTemplate); } else { } } } eventWriter.add(eventFactory.createEndElement(PREFIX, URI, key3)); eventWriter.add(end); } } } } eventWriter.add(eventFactory.createEndElement(PREFIX, URI, key2)); eventWriter.add(end); } } eventWriter.add(eventFactory.createEndElement(PREFIX, URI, key)); eventWriter.add(end); } } eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "templates")); eventWriter.add(end); } if (d.getUsage().getIdentifiers() != null && d.getUsage().getIdentifiers().getChildren().size() > 0) { startElement = eventFactory.createStartElement( PREFIX, URI, "personIdentifiers"); // "personIdentifiers" eventWriter.add(startElement); eventWriter.add(end); for (String key : d.getUsage().getIdentifiers().getChildren().keySet()) { ConfigData ci = (ConfigData) d.getUsage().getIdentifiers().getChildren().get(key); if (ci != null && ci instanceof IdentifierConfig) { IdentifierConfig ic = (IdentifierConfig) ci; startElement = eventFactory.createStartElement(PREFIX, URI, "identifier"); // "identifier" eventWriter.add(startElement); if (ic.getValue() != null) { eventWriter.add(eventFactory.createAttribute("value", ic.getValue())); } if (ic.getLabel() != null) { eventWriter.add(eventFactory.createAttribute("label", ic.getLabel())); } eventWriter.add( eventFactory.createAttribute("ignore", new Boolean(ic.isIgnore()).toString())); eventWriter.add( eventFactory.createAttribute( "mandatory", new Boolean(ic.isMandatory()).toString())); eventWriter.add( eventFactory.createAttribute("priority", String.format("%03d", ic.getPriority()))); if (ic.getUrl() != null) { eventWriter.add(eventFactory.createAttribute("url", ic.getUrl())); } if (ic.getPrefix() != null) { eventWriter.add(eventFactory.createAttribute("prefix", ic.getPrefix())); } if (ic.getSuffix() != null) { eventWriter.add(eventFactory.createAttribute("suffix", ic.getSuffix())); } if (ic.getRegex() != null) { eventWriter.add(eventFactory.createAttribute("regex", ic.getRegex())); } eventWriter.add(end); if (ic.getDocumentation() != null) { createNode(eventWriter, "documentation", ic.getDocumentation(), PREFIX, URI); } if (ic.getChildren() != null) { for (String str2 : ic.getChildren().keySet()) { createNode(eventWriter, "item", ic.getChildren().get(str2)); } } eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "identifier")); eventWriter.add(end); } } eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "personIdentifiers")); eventWriter.add(end); } eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "usage")); eventWriter.add(end); } if (d.getChildren() != null) { for (String str : d.getChildren().keySet()) { DataType dt = (DataType) d.getChildren().get(str); startElement = eventFactory.createStartElement(PREFIX, URI, "datatype"); eventWriter.add(startElement); eventWriter.add(eventFactory.createAttribute("element", dt.getValue())); if (dt.getLabel() != null) { eventWriter.add(eventFactory.createAttribute("label", dt.getLabel())); } // if (d.getChildren().get(str).isMyHaveChildren()) // { if (dt.getPos() != null) { eventWriter.add(eventFactory.createAttribute("type", dt.getPos())); } else { // System.out.println("dt pos = null " + dt.getValue()); } // } // else // { // eventWriter.add(eventFactory.createAttribute("type", "list")); // } eventWriter.add(end); if (dt.getDocumentation() != null) { createNode(eventWriter, "documentation", dt.getDocumentation(), PREFIX, URI); } if (dt.getChildren() != null) { for (String str2 : dt.getChildren().keySet()) { createNode(eventWriter, "item", dt.getChildren().get(str2)); } } eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "datatype")); eventWriter.add(end); } eventWriter.add(eventFactory.createEndElement(PREFIX, URI, "datatypeDesc")); eventWriter.add(end); eventWriter.add(eventFactory.createEndDocument()); eventWriter.close(); } // System.out.println(bout.toString()); return bout.toString(); }
/** {@inheritDoc } */ @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 XMLEventWriter writer = getEventWriter(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 = extractElement( reader, writer, Collections.<String>singletonList(Constants.get(ConstantKey.LINK)), filter, true, linkInfo == null ? 0 : linkInfo.getKey(), 2, 2); 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, Constants.ENCODING), writer); } } } catch (Exception ignore) { // ignore } finally { writer.close(); reader.close(); } // ----------------------------------------- // ----------------------------------------- // 2. Add/replace edit link // ----------------------------------------- final InputStream content = addEditLink( new ByteArrayInputStream(tmpBos.toByteArray()), entitySetName, Constants.get(ConstantKey.DEFAULT_SERVICE_URL) + entitySetName + "(" + entityKey + ")"); // ----------------------------------------- // ----------------------------------------- // 3. Add content element if missing // ----------------------------------------- return addAtomContent( content, entitySetName, Constants.get(ConstantKey.DEFAULT_SERVICE_URL) + entitySetName + "(" + entityKey + ")"); // ----------------------------------------- }
private InputStream addAtomContent( final InputStream content, final String title, final String href) throws Exception { final ByteArrayOutputStream copy = new ByteArrayOutputStream(); IOUtils.copy(content, copy); IOUtils.closeQuietly(content); XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray())); ByteArrayOutputStream bos = new ByteArrayOutputStream(); XMLEventWriter writer = getEventWriter(bos); try { // check edit link existence XMLElement contentElement = extractElement(reader, writer, Collections.<String>singletonList("content"), 0, 2, 2) .getValue(); 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 = getEventWriter(bos); if (isMediaContent(title)) { final XMLElement entryElement = extractElement(reader, writer, Collections.<String>singletonList("entry"), 0, 1, 1) .getValue(); 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 = extractElement( reader, writer, Collections.<String>singletonList(Constants.get(ConstantKey.PROPERTIES)), 0, 2, 3) .getValue(); 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 = getEventWriter(bos); final XMLElement entryElement = extractElement(reader, writer, Collections.<String>singletonList("entry"), 0, 1, 1) .getValue(); 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()); }
/** * Can annotate SVG heatmap.plus charts made by R. Reads and writes using StAX, adding row and col * attributes to <path> elements corresponding to data points in the heatmap. All indexes can be * calculated using nRow, nCol, nRowAnnotations and nColAnnotations. * * @param chart * @throws FactoryConfigurationError * @throws XMLStreamException * @throws FileNotFoundException */ public void annotateHeatMap(HeatMapChart chart) throws XMLStreamException, FactoryConfigurationError, FileNotFoundException { XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(new FileInputStream(inFile)); OutputStream os = new FileOutputStream(outFile); XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(os); // get values from HeatMapChart int nRow = chart.getData().getRowTargets().size(); int nCol = chart.getData().getColumnTargets().size(); // TODO get from HeatMapChart: int nRowAnnotations = 0; int nColAnnotations = 0; // skip the headers and <def> bit until we reach <g id=""> while (true) { XMLEvent event = (XMLEvent) reader.next(); if (event.isStartElement()) { StartElement se = event.asStartElement(); if (se.getName().getLocalPart().equals(G) && se.getAttributeByName(ID) != null) { LOG.info("<g id=\"\"> reached"); writer.add(event); break; } } writer.add(event); } // annotation begins here // ROW ANNOTATIONS if (nRowAnnotations > 0) { LOG.info("parsing " + nRowAnnotations + " row annotations"); annotateHeatMapBlock(nRow, nRowAnnotations, "rowAnnotation", writer, reader); } // COLUMN ANNOTATIONS if (nColAnnotations > 0) { LOG.info("parsing " + nColAnnotations + " col annotations"); annotateHeatMapBlock(nColAnnotations, nCol, "colAnnotatation", writer, reader); } // MATRIX ANNOTATIONS LOG.info("parsing " + (nRow * nCol) + " matrix values"); annotateHeatMapBlock(nRow, nCol, "matrix", writer, reader); // COLUMN NAMES LOG.info("parsing " + nCol + " column names"); int counter = 0; while (counter < nCol) { XMLEvent event = (XMLEvent) reader.next(); if (event.isStartElement() && event.asStartElement().getName().getLocalPart().equals(G)) { @SuppressWarnings("unchecked") Iterator<Attribute> attributes = event.asStartElement().getAttributes(); StartElement newSe = eventFactory.createStartElement(new QName(G), attributes, null); writer.add(newSe); writer.add(eventFactory.createAttribute(ID, "colName")); writer.add(eventFactory.createAttribute(new QName("col"), Integer.toString(counter + 1))); counter++; } else { writer.add(event); } } // ROW NAMES LOG.info("parsing " + nRow + " row names"); counter = 0; while (counter < nRow) { XMLEvent event = (XMLEvent) reader.next(); if (event.isStartElement() && event.asStartElement().getName().getLocalPart().equals(G)) { @SuppressWarnings("unchecked") Iterator<Attribute> attributes = event.asStartElement().getAttributes(); StartElement newSe = eventFactory.createStartElement(new QName(G), attributes, null); writer.add(newSe); writer.add(eventFactory.createAttribute(ID, "rowName")); writer.add( eventFactory.createAttribute(new QName("row"), Integer.toString(nRow - counter))); counter++; } else { writer.add(event); } } // finish rest of file while (reader.hasNext()) { XMLEvent event = (XMLEvent) reader.next(); if (event.isEndElement()) { // close the <g id=""> tag, right before the </svg> end element if (event.asEndElement().getName().getLocalPart().equals("svg")) { EndElement newEe = eventFactory.createEndElement(new QName(G), null); writer.add(newEe); } } writer.add(event); } writer.close(); }
@Override public InputStream selectEntity(final InputStream entity, final String[] propertyNames) throws Exception { final XMLEventReader reader = getEventReader(entity); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final XMLEventWriter writer = getEventWriter(bos); final List<String> found = new ArrayList<String>(Arrays.asList(propertyNames)); boolean inProperties = false; boolean writeCurrent = true; Boolean writeNext = null; 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 && Constants.get(ConstantKey.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 && Constants.get(ConstantKey.LINK) .equals(event.asEndElement().getName().getLocalPart())) { writeNext = true; } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT && (Constants.get(ConstantKey.PROPERTIES)) .equals(event.asStartElement().getName().getLocalPart())) { writeCurrent = true; writeNext = false; inProperties = true; } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && (Constants.get(ConstantKey.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 ((Constants.get(ConstantKey.ATOM_PROPERTY_PREFIX) + propertyName.trim()) .equals(elementName)) { writeCurrent = true; found.remove(propertyName); currentName = propertyName; } } } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT && StringUtils.isNotBlank(currentName) && (Constants.get(ConstantKey.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()); }
public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; RequestURIParts parts = parseParts(request); if (parts != null) { String realBaseAddress = parts.getBaseAddress(); String idlPath = parts.getFilePath(); InputStream idl = this.servletContext.getResourceAsStream(idlPath); if (idl != null) { servletResponse.setContentType("text/xml"); String assumedBaseAddress = null; try { XMLEventReader eventReader = this.inputFactory.createXMLEventReader(idl); XMLEventWriter eventWriter = this.outputFactory.createXMLEventWriter(servletResponse.getWriter()); while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isProcessingInstruction()) { String target = ((ProcessingInstruction) event).getTarget(); if ("enunciate-assumed-base-uri".equals(target)) { assumedBaseAddress = ((ProcessingInstruction) event).getData(); if (assumedBaseAddress.endsWith("/")) { assumedBaseAddress = assumedBaseAddress.substring(0, assumedBaseAddress.length() - 1); } } continue; } else if (event.getEventType() == XMLStreamConstants.CDATA || event.getEventType() == XMLStreamConstants.CHARACTERS) { String data = ((Characters) event).getData(); if (assumedBaseAddress != null && data.contains(assumedBaseAddress)) { data = data.replace(assumedBaseAddress, realBaseAddress); event = new DelegatingCharacters(((Characters) event), data); } } else if (event.getEventType() == XMLStreamConstants.START_ELEMENT) { List<Attribute> attributes = new ArrayList<Attribute>(); Iterator attributesIt = ((StartElement) event).getAttributes(); while (attributesIt.hasNext()) { Attribute attribute = (Attribute) attributesIt.next(); String value = attribute.getValue(); if (assumedBaseAddress != null && value.contains(assumedBaseAddress)) { value = value.replace(assumedBaseAddress, realBaseAddress); attribute = new DelegatingAttribute(attribute, value); event = new DelegatingStartElement(((StartElement) event), attributes); } attributes.add(attribute); } } eventWriter.add(event); } eventReader.close(); eventWriter.flush(); eventWriter.close(); return; } catch (XMLStreamException e) { throw new ServletException(e); } } } chain.doFilter(servletRequest, servletResponse); }
private void scramble(EFile input) throws XMLStreamException, IOException { File output = new File( input.getParentFile(), input.getNameMinusExtension() + ".scrambled." + input.getExtension()); Map<String, Object> xifProperties = null; Map<String, Object> xofProperties = null; XMLInputFactory xif = null; XMLOutputFactory xof = null; XMLEventWriter writer = null; XMLEventFactory xef = null; FileInputStream fis = null; FileOutputStream fos = null; try { xifProperties = StAXInputFactoryPool.getInstance().getDefaultPropertyMap(false); xofProperties = StAXOutputFactoryPool.getInstance().getDefaultPropertyMap(); xif = StAXInputFactoryPool.getInstance().acquire(xifProperties); xif.setXMLResolver(new StaxEntityResolver(CatalogEntityResolver.getInstance())); xof = StAXOutputFactoryPool.getInstance().acquire(xofProperties); xef = StAXEventFactoryPool.getInstance().acquire(); fis = new FileInputStream(input); fos = new FileOutputStream(output); XMLEventReader baseReader = xif.createXMLEventReader(fis); writer = xof.createXMLEventWriter(fos); BookmarkedXMLEventReader reader = new BookmarkedXMLEventReader(baseReader); ContextStack context = new ContextStack(true); boolean skipElemTextScrambling = false; int c = 0; while (reader.hasNext()) { XMLEvent xe = reader.nextEvent(); context.addEvent(xe); if (xe.isStartElement()) { skipElemTextScrambling = shouldSkip(xe.asStartElement()); if (isMetaElement(xe.asStartElement())) { xe = handleMetaElement(xe.asStartElement(), xef); } else if (isImageElement(xe.asStartElement())) { xe = handleImageElement(xe.asStartElement(), xef); } else if (isAcronymElement(xe.asStartElement())) { xe = handleAcronymElement(xe.asStartElement(), xef); } else if (isLinkElement(xe.asStartElement())) { xe = handleLinkElement(xe.asStartElement(), xef); } else if (isAnchorElement(xe.asStartElement())) { xe = handleAnchorElement(xe.asStartElement(), xef); } } else if (xe.isCharacters() && !skipElemTextScrambling && !CharUtils.isXMLWhiteSpace(xe.asCharacters().getData())) { xe = xef.createCharacters( "[" + Integer.toString(++c) + "] " + context.getContextXPath( ContextStack.XPATH_SELECT_ELEMENTS_ONLY, ContextStack.XPATH_PREDICATES_NONE)); } else if (xe.getEventType() == XMLEvent.PROCESSING_INSTRUCTION) { xe = handleProcessingInstruction((ProcessingInstruction) xe, xef); } else if (xe.isEndElement()) { skipElemTextScrambling = false; } if (xe != null) writer.add(xe); } } catch (CatalogExceptionNotRecoverable e) { e.printStackTrace(); } finally { fis.close(); fos.close(); writer.flush(); writer.close(); StAXInputFactoryPool.getInstance().release(xif, xifProperties); StAXOutputFactoryPool.getInstance().release(xof, xofProperties); StAXEventFactoryPool.getInstance().release(xef); } }
public void testClose() throws XMLStreamException { xmlEventWriter.close(); eventWriterWrapper.close(); }
public void process(SlingHttpServletResponse response, ProxyResponse proxyResponse) throws IOException { 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 > MAX_RSS_LENGTH) { response.sendError( HttpServletResponse.SC_FORBIDDEN, "This RSS feed is too big. The maximum for a feed is: " + MAX_RSS_LENGTH); 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_FORBIDDEN, "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(); Map<String, Boolean> checkedElements = new HashMap<String, Boolean>(); checkedElements.put("rss", false); checkedElements.put("channel", false); checkedElements.put("title", false); checkedElements.put("link", false); checkedElements.put("item", false); checkedElements.put("title", false); checkedElements.put("link", false); 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().toString().toLowerCase(); if (checkedElements.containsKey(name)) { checkedElements.put(name, true); } boolean all = true; for (Entry<String, Boolean> es : checkedElements.entrySet()) { if (!checkedElements.get(es.getKey())) { all = false; break; } } if (all) isValid = true; } if (i > 100) { response.sendError( HttpServletResponse.SC_FORBIDDEN, "This file does not match an RSS formatted XML file.."); break; } i++; } } if (!isValid) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid RSS file."); return; } // Check if we are not streaming a gigantic file.. if (out.size() > MAX_RSS_LENGTH) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "This file is to 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", "" + out.size()); // Write the cached stream to the output. out.writeTo(response.getOutputStream()); } catch (XMLStreamException e) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "This is not a valid XML file."); } catch (Exception e) { logger.warn("Exception reading RSS feed."); response.sendError(HttpServletResponse.SC_FORBIDDEN, "General exception caught."); } finally { out.close(); reader.close(); try { writer.close(); } catch (XMLStreamException e) { // Not much we can do? e.printStackTrace(); } } }
public File transform(boolean keepPorts) { FileInputStream fis = null; FileOutputStream fos = null; XMLEventReader parser = null; XMLEventWriter writer = null; XMLInputFactory xif = (XMLInputFactory.class.getClassLoader() == null) ? XMLInputFactory.newInstance() : XMLInputFactory.newInstance( XMLInputFactory.class.getName(), XMLInputFactory.class.getClassLoader()); Set<String> empty_elements = (keepPorts) ? EMPTY_ELEMENTS_KEEP_PORTS : EMPTY_ELEMENTS; Set<String> skip_elements = (keepPorts) ? SKIP_ELEMENTS_KEEP_PORTS : SKIP_ELEMENTS; try { fis = new FileInputStream(in); out = File.createTempFile("domain", "xml"); if (_logger.isLoggable(Level.FINE)) { _logger.fine("[DomainXmlTransformer] Creating temp domain file: " + out); } if (System.getProperty(EJBContainerProviderImpl.KEEP_TEMPORARY_FILES) == null) { out.deleteOnExit(); } fos = new FileOutputStream(out); parser = xif.createXMLEventReader(fis); writer = xof.createXMLEventWriter(fos); boolean fixedDasConfig = false; while (parser.hasNext()) { XMLEvent event = parser.nextEvent(); if (event.isStartElement()) { String name = event.asStartElement().getName().getLocalPart(); if (skip_elements.contains(name)) { if (_logger.isLoggable(Level.FINE)) { _logger.fine("[DomainXmlTransformer] Skipping all of: " + name); } getEndEventFor(parser, name); continue; } boolean skip_to_end = false; if (empty_elements.contains(name)) { if (_logger.isLoggable(Level.FINE)) { _logger.fine("[DomainXmlTransformer] Skipping details of: " + name); } skip_to_end = true; } else if (SKIP_SETTINGS_ELEMENTS.contains(name)) { // Make sure lazy init is not enabled by creating a new start element // based on the original but that never includes the lazy init attribute event = getSkippedElementStartEvent(event); skip_to_end = true; } else if (DISABLE_ELEMENTS.contains(name)) { // Disable this element event = getReplaceAttributeInStartEvent(event, ENABLED, FALSE); skip_to_end = true; } else if (JMS_HOST.equals(name)) { // Set lazy-init to false event = getReplaceAttributeInStartEvent(event, LAZY_INIT_ATTR, FALSE); skip_to_end = true; } else if (DAS_CONFIG.equals(name)) { // Set dynamic-reload-enabled to false event = getReplaceAttributeInStartEvent(event, DYNAMIC_RELOAD_ENABLED, FALSE); fixedDasConfig = true; skip_to_end = true; } else if (JAVA_CONFIG.equals(name)) { // Add jvm-options writer.add(event); event = getAddedEvent(event, writer, JVM_OPTIONS, INITIALIZE_ON_DEMAND); } if (skip_to_end) { writer.add(event); event = getEndEventFor(parser, name); } } else if (event.isEndElement()) { String name = event.asEndElement().getName().getLocalPart(); if (ADMIN_SERVICE.equals(name)) { if (!fixedDasConfig) { writer.add( getAddedEventBeforeEndElement( event, writer, DAS_CONFIG, DYNAMIC_RELOAD_ENABLED, FALSE)); } fixedDasConfig = false; // for the next config } } if (_logger.isLoggable(Level.FINEST)) { _logger.finest("[DomainXmlTransformer] Processing: " + event); } writer.add(event); } writer.flush(); writer.close(); } catch (Exception e) { _logger.log(Level.SEVERE, "ejb.embedded.tmp_file_create_error", e.getMessage()); _logger.log(Level.FINE, e.getMessage(), e); return null; } finally { try { if (parser != null) { parser.close(); } } catch (Exception e) { } try { if (fis != null) { fis.close(); } } catch (Exception e) { } try { if (writer != null) { writer.close(); } } catch (Exception e) { } try { if (fos != null) { fos.close(); } } catch (Exception e) { } } if (_logger.isLoggable(Level.FINE)) { _logger.fine("[DomainXmlTransformer] Created temp domain file: " + out); } return out; }