Example usage for javax.xml.stream XMLOutputFactory createXMLEventWriter

List of usage examples for javax.xml.stream XMLOutputFactory createXMLEventWriter

Introduction

In this page you can find the example usage for javax.xml.stream XMLOutputFactory createXMLEventWriter.

Prototype

public abstract XMLEventWriter createXMLEventWriter(java.io.Writer stream) throws XMLStreamException;

Source Link

Document

Create a new XMLEventWriter that writes to a writer

Usage

From source file:ca.uhn.fhir.util.XmlUtil.java

public static XMLEventWriter createXmlWriter(Writer theWriter)
        throws FactoryConfigurationError, XMLStreamException {
    XMLOutputFactory outputFactory = getOrCreateOutputFactory();
    XMLEventWriter retVal = outputFactory.createXMLEventWriter(theWriter);
    return retVal;
}

From source file:ca.uhn.fhir.util.XmlUtil.java

public static XMLEventWriter createXmlFragmentWriter(Writer theWriter)
        throws FactoryConfigurationError, XMLStreamException {
    XMLOutputFactory outputFactory = getOrCreateFragmentOutputFactory();
    XMLEventWriter retVal = outputFactory.createXMLEventWriter(theWriter);
    return retVal;
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Tests the {@link CastorMarshaller#marshal(Object, XMLEventWriter)} method when jaxbElement is null. </p> {@link
 * IllegalArgumentException} is expected.
 *
 * @throws Exception if any error occurs during test
 *///  w w  w .  j  ava 2s  .co  m
@Test(expected = IllegalArgumentException.class)
public void testMarshallXMLEventWriterNull1() throws Exception {

    StringWriter writer = new StringWriter();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    marshaller.marshal(null, outputFactory.createXMLEventWriter(writer));
}

From source file:org.castor.jaxb.CastorMarshallerTest.java

/**
 * Marshals the object into a {@link XMLEventWriter}.
 *
 * @param entity the object to marshall/*w ww  .  j  a  v  a 2  s .c  o  m*/
 *
 * @throws Exception if any error occurs during marshalling
 */
private void marshallXMLEventWriter(Object entity) throws Exception {
    StringWriter writer = new StringWriter();
    XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
    XMLEventWriter xmlEventWriter = outputFactory.createXMLEventWriter(writer);
    marshaller.marshal(entity, xmlEventWriter);

    assertXMLEqual("Marshaller written invalid result.", EXPECTED_XML, writer.toString());
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.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 XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

    try {/*from   ww  w  .j a  v  a2s .  c  o m*/

        final XmlElement feedElement = getAtomElement(reader, writer, "feed");

        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:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

private InputStream writeFromStartToEndElement(final StartElement element, final XMLEventReader reader,
        final boolean document) throws XMLStreamException {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLOutputFactory xof = XMLOutputFactory.newInstance();
    final XMLEventWriter writer = xof.createXMLEventWriter(bos);

    final QName name = element.getName();

    if (document) {
        final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        writer.add(eventFactory.createStartDocument("UTF-8", "1.0"));
        writer.add(element);/*from   www.  jav a  2  s.co  m*/

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

    XMLEvent event = element;

    while (reader.hasNext() && !(event.isEndElement() && name.equals(event.asEndElement().getName()))) {
        event = reader.nextEvent();
        writer.add(event);
    }

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

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

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

@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  ww . ja  v  a 2s  . co m*/
        final XmlElement linkElement = getAtomElement(reader, writer, LINK,
                Collections.<Map.Entry<String, String>>singletonList(
                        new SimpleEntry<String, String>("title", linkName)));
        writer.add(linkElement.getStart());

        // ------------------------------------------
        // write inline ...
        // ------------------------------------------
        writer.add(newLine);
        writer.add(eventFactory.createStartElement("m", null, "inline"));

        addAtomElement(replacement, writer);

        writer.add(eventFactory.createEndElement("m", null, "inline"));
        writer.add(newLine);
        // ------------------------------------------

        writer.add(linkElement.getEnd());

        writer.add(reader);
        writer.flush();
        writer.close();
    } finally {
        reader.close();
        IOUtils.closeQuietly(toBeChanged);
    }

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

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

/**
 * {@inheritDoc }/*from  w  ww .jav a  2  s . c o  m*/
 */
@Override
protected InputStream addLinks(final String entitySetName, final String entitykey, final InputStream is,
        final Set<String> links) throws Exception {

    // -----------------------------------------
    // 0. Build reader and writer
    // -----------------------------------------
    final XMLEventReader reader = getEventReader(is);
    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final 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 }/* www . j a  v a 2s .c  o  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: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 w w . j  av a  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());
}