Example usage for javax.xml.stream XMLStreamWriter writeEndElement

List of usage examples for javax.xml.stream XMLStreamWriter writeEndElement

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamWriter writeEndElement.

Prototype

public void writeEndElement() throws XMLStreamException;

Source Link

Document

Writes an end tag to the output relying on the internal state of the writer to determine the prefix and local name of the event.

Usage

From source file:org.intermine.api.xml.TagBindingTest.java

public void testMarshal() throws Exception {
    XMLUnit.setIgnoreWhitespace(true);/*from   ww  w.  j  av  a2 s .co m*/
    StringWriter sw = new StringWriter();
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {
        XMLStreamWriter writer = factory.createXMLStreamWriter(sw);
        writer.writeStartElement("tags");
        List<Tag> tags = getTags();
        for (Tag tag : tags) {
            TagBinding.marshal(tag, writer);
        }
        writer.writeEndElement();
        writer.close();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }

    InputStream is = getClass().getClassLoader().getResourceAsStream("TagBindingTest.xml");
    String expectedXml = IOUtils.toString(is);

    String actualXml = sw.toString().trim();
    System.out.println(normalise(actualXml));
    assertEquals("actual and expected XML should be the same", normalise(expectedXml), normalise(actualXml));
}

From source file:org.intermine.pathquery.PathQueryBinding.java

/**
 * Marshal to an XMLStreamWriter./*from  ww w .  j a  va 2 s  .  c  o  m*/
 *
 * @param query the PathQuery
 * @param queryName the name of the query
 * @param modelName the model name
 * @param writer the xml stream writer to write to
 * @param version the version number of the xml format, an attribute of the ProfileManager
 */
public void doMarshal(PathQuery query, String queryName, String modelName, XMLStreamWriter writer,
        int version) {
    try {
        writer.writeStartElement("query");
        writer.writeAttribute("name", queryName);
        writer.writeAttribute("model", modelName);
        writer.writeAttribute("view", StringUtil.join(query.getView(), " "));
        if (query.getDescription() != null) {
            writer.writeAttribute("longDescription", query.getDescription());
        } else {
            writer.writeAttribute("longDescription", "");
        }
        StringBuilder sort = new StringBuilder();
        boolean needComma = false;
        for (OrderElement oe : query.getOrderBy()) {
            if (needComma) {
                sort.append(" ");
            }
            needComma = true;
            sort.append(oe.getOrderPath() + (oe.getDirection().equals(OrderDirection.ASC) ? " asc" : " desc"));
        }
        String sortString = sort.toString();
        if (!"".equals(sortString)) {
            writer.writeAttribute("sortOrder", sortString);
        }
        String logic = query.getConstraintLogic();
        boolean hasMultipleConstraints = false;
        if ((logic != null) && (logic.length() > 1)) {
            writer.writeAttribute("constraintLogic", query.getConstraintLogic());
            hasMultipleConstraints = true;
        }
        marshalPathQueryJoinStyle(query, writer);
        marshalPathQueryDescriptions(query, writer);
        marshalPathQueryConstraints(query, writer, hasMultipleConstraints);
        writer.writeEndElement();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.intermine.pathquery.PathQueryBinding.java

/**
 * Create XML for the constraints in a PathQuery.
 *///from   www .  ja  v  a2 s . com
private void marshalPathQueryConstraints(PathQuery query, XMLStreamWriter writer,
        boolean hasMultipleConstraints) throws XMLStreamException {
    for (Map.Entry<PathConstraint, String> constraint : query.getConstraints().entrySet()) {
        boolean emptyElement = true;
        if (constraint.getKey() instanceof PathConstraintMultiValue) {
            emptyElement = false;
        }

        if (emptyElement) {
            writer.writeEmptyElement("constraint");
        } else {
            writer.writeStartElement("constraint");
        }
        writer.writeAttribute("path", constraint.getKey().getPath());
        if ((constraint.getValue() != null) && (hasMultipleConstraints)) {
            writer.writeAttribute("code", constraint.getValue());
        }
        doAdditionalConstraintStuff(query, constraint.getKey(), writer);
        if (constraint.getKey() instanceof PathConstraintAttribute) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
            String outputValue = ((PathConstraintAttribute) constraint.getKey()).getValue();
            writer.writeAttribute("value", "" + outputValue);
        } else if (constraint.getKey() instanceof PathConstraintNull) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
        } else if (constraint.getKey() instanceof PathConstraintSubclass) {
            writer.writeAttribute("type", ((PathConstraintSubclass) constraint.getKey()).getType());
        } else if (constraint.getKey() instanceof PathConstraintBag) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
            writer.writeAttribute("value", ((PathConstraintBag) constraint.getKey()).getBag());
        } else if (constraint.getKey() instanceof PathConstraintIds) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
            StringBuilder sb = new StringBuilder();
            boolean needComma = false;
            for (Integer id : ((PathConstraintIds) constraint.getKey()).getIds()) {
                if (needComma) {
                    sb.append(", ");
                }
                needComma = true;
                sb.append("" + id);
            }
            writer.writeAttribute("ids", sb.toString());
        } else if (constraint.getKey() instanceof PathConstraintMultiValue) {
            // Includes PathConstraintRange, which is serialised in the exact same manner.
            writer.writeAttribute("op", "" + constraint.getKey().getOp());

            for (String value : ((PathConstraintMultiValue) constraint.getKey()).getValues()) {
                if (value == null) {
                    writer.writeStartElement("nullValue");
                    writer.writeEndElement();
                } else {
                    if (!value.equals(value.trim())) {
                        throw new XMLStreamException("Value in MultiValue starts or ends with "
                                + "whitespace - this query cannot be represented in XML");
                    }
                    writer.writeStartElement("value");
                    writer.writeCharacters(value);
                    writer.writeEndElement();
                }
            }
        } else if (constraint.getKey() instanceof PathConstraintLoop) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
            writer.writeAttribute("loopPath", ((PathConstraintLoop) constraint.getKey()).getLoopPath());
        } else if (constraint.getKey() instanceof PathConstraintLookup) {
            writer.writeAttribute("op", "" + constraint.getKey().getOp());
            writer.writeAttribute("value", ((PathConstraintLookup) constraint.getKey()).getValue());
            String extraValue = ((PathConstraintLookup) constraint.getKey()).getExtraValue();
            if (extraValue != null) {
                writer.writeAttribute("extraValue", extraValue);
            }
        } else {
            throw new IllegalStateException(
                    "Unrecognised constraint type " + constraint.getKey().getClass().getName());
        }
        if (!emptyElement) {
            writer.writeEndElement();
        }
    }
}

From source file:org.intermine.template.xml.TemplateQueryBinding.java

/**
 * Convert a TemplateQuery to XML and write XML to given writer.
 *
 * @param template the TemplateQuery/*from  w  w  w .  ja  va  2s  . c  o  m*/
 * @param writer the XMLStreamWriter to write to
 * @param version the version number of the XML format
 */
public void doMarshal(TemplateQuery template, XMLStreamWriter writer, int version) {
    if (template == null) {
        throw new NullPointerException("template must not be null");
    }
    if (writer == null) {
        throw new NullPointerException("writer must not be null");
    }
    try {
        writer.writeCharacters("\n");
        writer.writeStartElement("template");
        writer.writeAttribute("name", template.getName());
        if (template.getTitle() != null) {
            writer.writeAttribute("title", template.getTitle());
        }
        if (template.getComment() == null) {
            writer.writeAttribute("comment", "");
        } else {
            writer.writeAttribute("comment", template.getComment());
        }

        doMarshal(template, template.getName(), template.getModel().getName(), writer, version);
        writer.writeEndElement();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.intermine.web.logic.template.TemplateHelper.java

/**
 * Given a Map of TemplateQueries (mapping from template name to TemplateQuery)
 * return a string containing each template seriaised as XML. The root element
 * will be a <code>template-queries</code> element.
 *
 * @param templates  map from template name to TemplateQuery
 * @param version the version number of the XML format
 * @return  all template queries serialised as XML
 * @see  TemplateQuery/*w w  w. j  a v  a  2s .  c  o  m*/
 */
public static String templateMapToXml(Map<String, TemplateQuery> templates, int version) {
    StringWriter sw = new StringWriter();
    XMLOutputFactory factory = XMLOutputFactory.newInstance();

    try {
        XMLStreamWriter writer = factory.createXMLStreamWriter(sw);
        writer.writeStartElement("template-queries");
        for (TemplateQuery template : templates.values()) {
            TemplateQueryBinding.marshal(template, writer, version);
        }
        writer.writeEndElement();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
    return sw.toString();
}

From source file:org.mule.module.xml.util.XMLUtils.java

public static void copy(XMLStreamReader reader, XMLStreamWriter writer, boolean fragment)
        throws XMLStreamException {
    // number of elements read in
    int read = 0;
    int event = reader.getEventType();

    while (reader.hasNext()) {
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            read++;//w  w  w . j  a v  a 2s.c  o  m
            writeStartElement(reader, writer);
            break;
        case XMLStreamConstants.END_ELEMENT:
            writer.writeEndElement();
            read--;
            if (read <= 0 && !fragment) {
                return;
            }
            break;
        case XMLStreamConstants.CHARACTERS:
            writer.writeCharacters(reader.getText());
            break;
        case XMLStreamConstants.START_DOCUMENT:
        case XMLStreamConstants.END_DOCUMENT:
        case XMLStreamConstants.ATTRIBUTE:
        case XMLStreamConstants.NAMESPACE:
            break;
        default:
            break;
        }
        event = reader.next();
    }
}

From source file:org.mule.modules.jive.api.xml.XmlMapper.java

/**
 * @param xmlRootTag The root xml tag to use in the mapping
 * @param entity The {@link Map} to be converted in xml
 * @param writer The {@link Writer} to write the result
 *//*from ww w.  jav  a  2s  . c o m*/
public final void map2xml(final String xmlRootTag, final Map<String, Object> entity, final Writer writer) {
    try {
        final XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(writer);

        w.writeStartDocument();

        w.writeStartElement(xmlRootTag);

        writeXML(w, entity);

        w.writeEndElement();

        w.writeEndDocument();
    } catch (XMLStreamException e) {
        throw new UnhandledException(e);
    }
}

From source file:org.mule.modules.jive.api.xml.XmlMapper.java

/**Writes the xml of the internal data.
 * @param w The writer in which it'll write the xml
 * @param model The entity/*from  w w w .  ja v  a2 s  . c  o  m*/
 * @throws XMLStreamException When fails
 * */
@SuppressWarnings("unchecked")
private void writeXML(final XMLStreamWriter w, final Map<String, Object> model) throws XMLStreamException {
    final Set<Entry<String, Object>> entries = model.entrySet();
    for (final Entry<String, Object> entry : entries) {
        if (List.class.isInstance(entry.getValue())) {
            for (final String elem : (List<String>) entry.getValue()) {
                w.writeStartElement(entry.getKey());
                w.writeCharacters(elem);
                w.writeEndElement();
            }
        } else {
            String key = entry.getKey();
            if (StringUtils.startsWith(key, "return")) {
                key = "return";
            }
            w.writeStartElement(key);
            if (!HashMap.class.isInstance(entry.getValue())) {
                w.writeCharacters(entry.getValue().toString());
            } else {
                writeXML(w, (HashMap<String, Object>) entry.getValue());
            }
            w.writeEndElement();
        }
    }
}

From source file:org.netbeans.jbatch.modeler.spec.core.Definitions.java

static void transformXMLStream(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter) {
    try {/*  ww w  .ja  v  a 2s.co m*/
        //            TransformerFactory tf = TransformerFactory.newInstance();
        //            Transformer t = tf.newTransformer();
        //            StAXSource source = new StAXSource(xmlStreamReader);
        //            StAXResult result = new StAXResult(xmlStreamWriter);
        //            t.transform(source, result);
        System.out.println("Defnition Id : " + xmlStreamReader.getAttributeValue(null, "id"));
        boolean finish = false;
        while (xmlStreamReader.hasNext() && !finish) {
            switch (xmlStreamReader.getEventType()) {
            case XMLEvent.START_ELEMENT:
                String prefix = xmlStreamReader.getPrefix();
                String namespaceURI = xmlStreamReader.getNamespaceURI();
                if (namespaceURI != null) {
                    if (prefix != null) {
                        xmlStreamWriter.writeStartElement(xmlStreamReader.getPrefix(),
                                xmlStreamReader.getLocalName(), xmlStreamReader.getNamespaceURI());
                    } else {
                        xmlStreamWriter.writeStartElement(xmlStreamReader.getNamespaceURI(),
                                xmlStreamReader.getLocalName());
                    }
                } else {
                    xmlStreamWriter.writeStartElement(xmlStreamReader.getLocalName());
                }

                for (int i = 0; i < xmlStreamReader.getNamespaceCount(); i++) {
                    xmlStreamWriter.writeNamespace(xmlStreamReader.getNamespacePrefix(i),
                            xmlStreamReader.getNamespaceURI(i));
                }
                int count = xmlStreamReader.getAttributeCount();
                for (int i = 0; i < count; i++) {
                    //                            xmlStreamWriter.writeAttribute(xmlStreamReader.getAttributePrefix(i),
                    //                                    xmlStreamReader.getAttributeNamespace(i),
                    //                                    xmlStreamReader.getAttributeLocalName(i),
                    //                                    xmlStreamReader.getAttributeValue(i));

                    String attrNamespaceURI = xmlStreamReader.getAttributeNamespace(i),
                            attrPrefix = xmlStreamReader.getAttributePrefix(i);
                    if (attrNamespaceURI != null) {
                        if (attrPrefix != null) {
                            xmlStreamWriter.writeAttribute(attrPrefix, attrNamespaceURI,
                                    xmlStreamReader.getAttributeLocalName(i),
                                    xmlStreamReader.getAttributeValue(i));
                        } else {
                            xmlStreamWriter.writeAttribute(attrNamespaceURI,
                                    xmlStreamReader.getAttributeLocalName(i),
                                    xmlStreamReader.getAttributeValue(i));
                        }
                    } else {
                        xmlStreamWriter.writeAttribute(xmlStreamReader.getAttributeLocalName(i),
                                xmlStreamReader.getAttributeValue(i));
                    }

                }
                break;
            case XMLEvent.END_ELEMENT:
                xmlStreamWriter.writeEndElement();
                if (xmlStreamReader.getLocalName().equals("definitions")) {
                    finish = true;
                }
                break;
            case XMLEvent.SPACE:
            case XMLEvent.CHARACTERS:
                xmlStreamWriter.writeCharacters(xmlStreamReader.getTextCharacters(),
                        xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength());
                break;
            case XMLEvent.PROCESSING_INSTRUCTION:
                xmlStreamWriter.writeProcessingInstruction(xmlStreamReader.getPITarget(),
                        xmlStreamReader.getPIData());
                break;
            case XMLEvent.CDATA:
                xmlStreamWriter.writeCData(xmlStreamReader.getText());
                break;

            case XMLEvent.COMMENT:
                xmlStreamWriter.writeComment(xmlStreamReader.getText());
                break;
            case XMLEvent.ENTITY_REFERENCE:
                xmlStreamWriter.writeEntityRef(xmlStreamReader.getLocalName());
                break;
            case XMLEvent.START_DOCUMENT:
                String encoding = xmlStreamReader.getCharacterEncodingScheme();
                String version = xmlStreamReader.getVersion();

                if (encoding != null && version != null) {
                    xmlStreamWriter.writeStartDocument(encoding, version);
                } else if (version != null) {
                    xmlStreamWriter.writeStartDocument(xmlStreamReader.getVersion());
                }
                break;
            case XMLEvent.END_DOCUMENT:
                xmlStreamWriter.writeEndDocument();
                break;
            case XMLEvent.DTD:
                xmlStreamWriter.writeDTD(xmlStreamReader.getText());
                break;

            }
            if (!finish) {
                xmlStreamReader.next();
            }
        }
    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    }
}