Example usage for javax.xml.stream XMLEventWriter add

List of usage examples for javax.xml.stream XMLEventWriter add

Introduction

In this page you can find the example usage for javax.xml.stream XMLEventWriter add.

Prototype


public void add(XMLEventReader reader) throws XMLStreamException;

Source Link

Document

Adds an entire stream to an output stream, calls next() on the inputStream argument until hasNext() returns false This should be treated as a convenience method that will perform the following loop over all the events in an event reader and call add on each event.

Usage

From source file:org.alex73.osm.converters.bel.Convert.java

public static void main(String[] args) throws Exception {
    loadStreetNamesForHouses();//  www.j  a  v a  2  s. c o m

    InputStream in = new BZip2CompressorInputStream(
            new BufferedInputStream(new FileInputStream("tmp/belarus-latest.osm.bz2"), BUFFER_SIZE));

    // create xml event reader for input stream
    XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent newLine = eventFactory.createCharacters("\n");
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    XMLEventReader reader = xif.createXMLEventReader(in);
    XMLEventWriter wrCyr = xof.createXMLEventWriter(
            new BufferedOutputStream(new FileOutputStream("tmp/belarus-bel.osm"), BUFFER_SIZE));
    XMLEventWriter wrInt = xof.createXMLEventWriter(
            new BufferedOutputStream(new FileOutputStream("tmp/belarus-intl.osm"), BUFFER_SIZE));

    // initialize jaxb
    JAXBContext jaxbCtx = JAXBContext.newInstance(Node.class, Way.class, Relation.class);
    Unmarshaller um = jaxbCtx.createUnmarshaller();
    Marshaller m = jaxbCtx.createMarshaller();
    m.setProperty(Marshaller.JAXB_FRAGMENT, true);
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    XMLEvent e = null;
    while ((e = reader.peek()) != null) {
        boolean processed = false;
        if (e.isStartElement()) {
            StartElement se = (StartElement) e;
            switch (se.getName().getLocalPart()) {
            case "way":
                Way way = um.unmarshal(reader, Way.class).getValue();
                if (way.getId() == 25439425) {
                    System.out.println();
                }
                fixBel(way.getTag(), "name:be", "name");
                String nameBeHouse = houseStreetBe.get(way.getId());
                if (nameBeHouse != null) {
                    setTag(way.getTag(), "addr:street", nameBeHouse);
                }
                m.marshal(way, wrCyr);
                fixInt(way.getTag());
                m.marshal(way, wrInt);
                wrCyr.add(newLine);
                wrInt.add(newLine);
                processed = true;
                break;
            case "node":
                Node node = um.unmarshal(reader, Node.class).getValue();
                fixBel(node.getTag(), "name:be", "name");
                // fixBel(node.getTag(),"addr:street:be","addr:street");
                m.marshal(node, wrCyr);
                fixInt(node.getTag());
                m.marshal(node, wrInt);
                wrCyr.add(newLine);
                wrInt.add(newLine);
                processed = true;
                break;
            case "relation":
                Relation relation = um.unmarshal(reader, Relation.class).getValue();
                fixBel(relation.getTag(), "name:be", "name");
                // fixBel(relation.getTag(),"addr:street:be","addr:street");
                m.marshal(relation, wrCyr);
                fixInt(relation.getTag());
                m.marshal(relation, wrInt);
                wrCyr.add(newLine);
                wrInt.add(newLine);
                processed = true;
                break;
            }
        }
        if (!processed) {
            wrCyr.add(e);
            wrInt.add(e);
        }
        reader.next();
    }

    wrCyr.flush();
    wrCyr.close();
    wrInt.flush();
    wrInt.close();
    System.out.println("UniqueTranslatedTags: " + uniqueTranslatedTags);
}

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

private void writeEvent(final XMLEvent event, final XMLEventWriter writer) {
    if (writer != null) {
        try {/* w  w  w.  jav a2s. c o m*/
            writer.add(event);
        } catch (XMLStreamException e) {
            LOG.error("Error writing event {}", event, e);
        }
    }
}

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

/**
 * {@inheritDoc }/*w  w  w .  j a  v a2s .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 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
public InputStream addEditLink(final InputStream content, final String title, final String href)
        throws Exception {

    final ByteArrayOutputStream copy = new ByteArrayOutputStream();
    IOUtils.copy(content, copy);//from www  .  j  a v  a 2  s  .  c o m

    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(LINK),
                Collections.<Map.Entry<String, String>>singletonList(
                        new AbstractMap.SimpleEntry<String, String>("rel", "edit")),
                false, 0, -1, -1);

        addAtomElement(IOUtils.toInputStream(editLinkElement), 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), 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:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

public InputStream addAtomContent(final InputStream content, final String title, final String href)
        throws Exception {

    final ByteArrayOutputStream copy = new ByteArrayOutputStream();
    IOUtils.copy(content, copy);//w w w  .java 2 s  . c om

    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(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());
}

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

public InputStream addAtomInlinecount(final InputStream feed, final int count, final Accept accept)
        throws Exception {
    final XMLEventReader reader = getEventReader(feed);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    try {/*from  w  ww  .  j ava 2 s .  com*/

        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)), 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());
}

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

@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;/*from  w  w w. j  a  v a  2  s .  co 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());
}

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

@Override
public InputStream setChanges(final InputStream toBeChanged, final Map<String, InputStream> properties)
        throws Exception {
    XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLEventWriter writer = getEventWriter(bos);

    // ---------------------------------
    // add property changes
    // ---------------------------------
    Map.Entry<Integer, XmlElement> propertyElement = extractElement(reader, writer,
            Collections.<String>singletonList(PROPERTIES), 0, 2, 3);

    writer.flush();//from   w  ww .  ja v  a2  s  .  c o  m

    ByteArrayOutputStream pbos = new ByteArrayOutputStream();
    OutputStreamWriter pwriter = new OutputStreamWriter(pbos);

    final XMLEventReader propertyReader = propertyElement.getValue().getContentReader();

    try {
        while (true) {
            final XmlElement property = extractElement(propertyReader, null, null, 0, -1, -1).getValue();
            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 = getEventWriter(bos);

            try {
                final String linkName = remains.getKey().substring(remains.getKey().indexOf("]") + 1);

                extractElement(reader, writer, Collections.<String>singletonList(LINK),
                        Collections.<Map.Entry<String, String>>singleton(
                                new SimpleEntry<String, String>("title", linkName)),
                        false, 0, 2, 2);

                writer.add(reader);

            } catch (Exception ignore) {
                // ignore
            }

            writer.flush();
            writer.close();
        }
    }

    reader = getEventReader(new ByteArrayInputStream(bos.toByteArray()));

    bos.reset();
    writer = getEventWriter(bos);

    propertyElement = extractElement(reader, writer, Collections.<String>singletonList(CONTENT), 0, 2, 2);
    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: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   w w  w  .  ja  v a2  s .  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.AbstractXMLUtilities.java

@Override
public InputStream getProperty(final String entitySetName, final String entityId, final List<String> path,
        final String edmType) throws Exception {
    final List<String> pathElements = new ArrayList<String>();

    for (String element : path) {
        pathElements.add(ATOM_PROPERTY_PREFIX + element);
    }//from  w ww.  j a va  2s.  co  m

    final InputStream src = fsManager.readFile(Commons.getEntityBasePath(entitySetName, entityId) + ENTITY,
            Accept.XML);

    final XMLEventReader reader = getEventReader(src);
    final XmlElement property = extractElement(reader, null, pathElements, 0, 3, 4).getValue();

    reader.close();
    IOUtils.closeQuietly(src);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    writer.add(eventFactory.createStartDocument("UTF-8", "1.0"));
    writer.add(property.getStart());

    if (property.getStart().getAttributeByName(new QName(ATOM_DATASERVICE_NS)) == null) {
        writer.add(eventFactory.createNamespace(ATOM_PROPERTY_PREFIX.substring(0, 1), DATASERVICES_NS));
    }
    if (property.getStart().getAttributeByName(new QName(ATOM_METADATA_NS)) == null) {
        writer.add(eventFactory.createNamespace(ATOM_METADATA_PREFIX.substring(0, 1), METADATA_NS));
    }

    writer.add(property.getContentReader());
    writer.add(property.getEnd());

    writer.flush();
    writer.close();

    return new ByteArrayInputStream(bos.toByteArray());
}