Example usage for javax.xml.stream XMLStreamWriter writeCData

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

Introduction

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

Prototype

public void writeCData(String data) throws XMLStreamException;

Source Link

Document

Writes a CData section

Usage

From source file:com.flexive.shared.media.FxMetadata.java

/**
 * Get this metadata object as XML document
 *
 * @return XML document//w  ww . j a  v a 2s .c om
 * @throws FxApplicationException on errors
 */
public String toXML() throws FxApplicationException {
    StringWriter sw = new StringWriter(2000);
    try {
        XMLStreamWriter writer = getXmlOutputFactory().createXMLStreamWriter(sw);
        writer.writeStartDocument();
        writer.writeStartElement("metadata");
        writer.writeAttribute("mediatype", getMediaType().name());
        writer.writeAttribute("mimetype", getMimeType());
        writer.writeAttribute("filename", getFilename());
        writeXMLTags(writer);
        for (FxMetadataItem mdi : getMetadata()) {
            final String value = mdi.getValue().replaceAll("[\\x00-\\x1F]", ""); //filter out control characters
            if (StringUtils.isEmpty(value))
                continue;
            writer.writeStartElement("meta");
            writer.writeAttribute("key", mdi.getKey());
            writer.writeCData(value);
            writer.writeEndElement();
        }
        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new FxApplicationException(e, "ex.general.xml", e.getMessage());
    }
    return sw.getBuffer().toString();
}

From source file:com.concursive.connect.web.modules.api.services.BackupService.java

private void save(XMLStreamWriter writer, DataRecord record, String recordId, Object object,
        PacketContext context) throws Exception {
    // Data record
    writer.writeCharacters("  ");
    writer.writeStartElement("dataRecord");
    writer.writeAttribute("name", record.getName());
    writer.writeAttribute("id", recordId);
    writer.writeCharacters(System.getProperty("line.separator"));
    // Data fields
    for (DataField thisField : record) {
        writer.writeCharacters("    ");
        writer.writeStartElement(thisField.getName());
        if (thisField.getValue() != null) {
            if (StringUtils.countLines(thisField.getValue()) > 1) {
                writer.writeCData(thisField.getValue());
            } else {
                writer.writeCharacters(thisField.getValue());
            }//from w  ww  .ja v  a  2s.  com
        } else {
            writer.writeCharacters(DataRecord.NULL);
        }
        writer.writeEndElement();
        writer.writeCharacters(System.getProperty("line.separator"));
    }

    // If this is a file, stream it too
    if (object instanceof FileItem) {
        // Find the file in the filesystem
        File file = new File(context.getBaseFilePath()
                + DateUtils.getDatePath(record.getValueAsTimestamp("modified")) + record.getValue("filename"));
        if (!file.exists()) {
            LOG.error("File not found: " + file.getAbsolutePath());
        } else {
            // If there is a fileAttachment, then attach it as base64
            writer.writeCharacters("    ");
            writer.writeStartElement("fileAttachment");
            // Convert to base64 and append
            writer.writeCData(new String(Base64.encodeBase64(FileUtils.getBytesFromFile(file), true)));
            // Close the element
            writer.writeEndElement();
            writer.writeCharacters(System.getProperty("line.separator"));
        }
    }

    // Close the record
    writer.writeCharacters("  ");
    writer.writeEndElement();
    writer.writeCharacters(System.getProperty("line.separator"));
}

From source file:jp.co.atware.solr.geta.GETAssocComponent.java

/**
 * //from   w w w .ja  va  2s .c om
 * @param xml
 * @param params
 * @param queryValue
 * @param queryType
 * @throws XMLStreamException
 */
protected void convReqWriteQuery(XMLStreamWriter xml, SolrParams params, String queryValue, QueryType queryType)
        throws XMLStreamException {

    if (queryType == QueryType.fulltext) {
        // freetext
        xml.writeStartElement("freetext");
        String stemmer = params.get(PARAM_STEMMER, config.defaults.stemmer);
        if (stemmer != null) {
            xml.writeAttribute("stemmer", stemmer);
        }
        String freetext_cutoff_df = params.get(PARAM_FREETEXT_CUTOFF_DF, config.defaults.freetext_cutoff_df);
        if (config.defaults.source != null) {
            xml.writeAttribute("cutoff-df", freetext_cutoff_df);
        }
        xml.writeCData(queryValue);
        xml.writeEndElement();
    } else {
        // article
        xml.writeStartElement("article");
        if (queryType == QueryType.vector) {
            xml.writeAttribute("vec", queryValue);
        } else {
            xml.writeAttribute("name", queryValue);
        }
        String source = params.get(PARAM_SOURCE, config.defaults.source);
        if (source != null) {
            xml.writeAttribute("source", source);
        }
        String article_cutoff_df = params.get(PARAM_ARTICLE_CUTOFF_DF, config.defaults.article_cutoff_df);
        if (source != null) {
            xml.writeAttribute("cutoff-df", article_cutoff_df);
        }
        xml.writeEndElement();
    }
}

From source file:Main.java

/**
 * Borrowed from org.apache.xml.security.test.stax.utils.XmlReaderToWriter
 */// ww w . j a v  a  2  s  . c o  m
public static void write(XMLStreamReader xmlr, XMLStreamWriter writer) throws XMLStreamException {
    switch (xmlr.getEventType()) {
    case XMLEvent.START_ELEMENT:
        final String localName = xmlr.getLocalName();
        final String namespaceURI = xmlr.getNamespaceURI();
        if (namespaceURI != null && namespaceURI.length() > 0) {
            final String prefix = xmlr.getPrefix();
            if (prefix != null) {
                writer.writeStartElement(prefix, localName, namespaceURI);
            } else {
                writer.writeStartElement(namespaceURI, localName);
            }
        } else {
            writer.writeStartElement(localName);
        }

        for (int i = 0, len = xmlr.getNamespaceCount(); i < len; i++) {
            String prefix = xmlr.getNamespacePrefix(i);
            if (prefix == null) {
                writer.writeDefaultNamespace(xmlr.getNamespaceURI(i));
            } else {
                writer.writeNamespace(prefix, xmlr.getNamespaceURI(i));
            }
        }

        for (int i = 0, len = xmlr.getAttributeCount(); i < len; i++) {
            final String attUri = xmlr.getAttributeNamespace(i);

            if (attUri != null && attUri.length() > 0) {
                final String prefix = xmlr.getAttributePrefix(i);
                if (prefix != null) {
                    writer.writeAttribute(prefix, attUri, xmlr.getAttributeLocalName(i),
                            xmlr.getAttributeValue(i));
                } else {
                    writer.writeAttribute(attUri, xmlr.getAttributeLocalName(i), xmlr.getAttributeValue(i));
                }
            } else {
                writer.writeAttribute(xmlr.getAttributeLocalName(i), xmlr.getAttributeValue(i));
            }

        }
        break;
    case XMLEvent.END_ELEMENT:
        writer.writeEndElement();
        break;
    case XMLEvent.SPACE:
    case XMLEvent.CHARACTERS:
        char[] text = new char[xmlr.getTextLength()];
        xmlr.getTextCharacters(0, text, 0, xmlr.getTextLength());
        writer.writeCharacters(text, 0, text.length);
        break;
    case XMLEvent.PROCESSING_INSTRUCTION:
        writer.writeProcessingInstruction(xmlr.getPITarget(), xmlr.getPIData());
        break;
    case XMLEvent.CDATA:
        writer.writeCData(xmlr.getText());
        break;
    case XMLEvent.COMMENT:
        writer.writeComment(xmlr.getText());
        break;
    case XMLEvent.ENTITY_REFERENCE:
        writer.writeEntityRef(xmlr.getLocalName());
        break;
    case XMLEvent.START_DOCUMENT:
        String encoding = xmlr.getCharacterEncodingScheme();
        String version = xmlr.getVersion();

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

From source file:com.fiorano.openesb.application.aps.OutPortInst.java

public void toJXMLString(XMLStreamWriter writer) throws XMLStreamException {

    //Start OutPortInst
    writer.writeStartElement("OutPortInst");

    writer.writeAttribute("isSyncRequestType", "" + isSyncRequestType());

    FioranoStackSerializer.writeElement("Name", m_strPortName, writer);

    if (!StringUtils.isEmpty(m_strDscription)) {
        FioranoStackSerializer.writeElement("Description", m_strDscription, writer);
    }/*from ww  w  .  java2s .  c  om*/

    boolean standardXSD = false;

    if ("ON_EXCEPTION".equals(m_strPortName))
        standardXSD = CommonSchemas.ERROR_XSD == null ? m_strXSD == null
                : m_strXSD != null && CommonSchemas.ERROR_XSD.equals(m_strXSD);

    if (standardXSD) {
        writer.writeStartElement("StandardXSD");

        writer.writeEndElement();
    } else if (m_strXSDRef != null) {
        FioranoStackSerializer.writeElement(PortInstConstants.PORT_XSDREF, m_strXSDRef, writer);

    }

    if (m_strContextXSL != null) {
        writer.writeStartElement("SetContextXSL");
        writer.writeCData(m_strContextXSL);
        writer.writeEndElement();
    }

    if (m_strContextInfo != null) {
        writer.writeStartElement("SetContextInfo");
        writer.writeCData(m_strContextInfo);
        writer.writeEndElement();
    }

    if (m_transformerType != null) {
        writer.writeStartElement("SetTransformationType");
        writer.writeCData(m_transformerType);
        writer.writeEndElement();

    }

    if (!StringUtils.isEmpty(m_strJavaClass)) {
        FioranoStackSerializer.writeElement("JavaClass", m_strJavaClass, writer);
    }

    if (m_params != null && m_params.size() > 0) {
        Enumeration enums = m_params.elements();

        while (enums.hasMoreElements()) {
            Param param = (Param) enums.nextElement();
            if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue())) {
                if (!checkIfDefaultValue(param.getParamName(), param.getParamValue())) {
                    param.toJXMLString(writer);
                }
            }
        }
    }
    //End OutPortInst
    writer.writeEndElement();

}

From source file:com.liferay.portal.util.LocalizationImpl.java

private void _copyNonExempt(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter,
        String exemptLanguageId, String defaultLanguageId, boolean cdata) throws XMLStreamException {

    while (xmlStreamReader.hasNext()) {
        int event = xmlStreamReader.next();

        if (event == XMLStreamConstants.START_ELEMENT) {
            String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID);

            if (Validator.isNull(languageId)) {
                languageId = defaultLanguageId;
            }/*from w w  w . j av a  2  s  .  c om*/

            if (!languageId.equals(exemptLanguageId)) {
                xmlStreamWriter.writeStartElement(xmlStreamReader.getLocalName());
                xmlStreamWriter.writeAttribute(_LANGUAGE_ID, languageId);

                while (xmlStreamReader.hasNext()) {
                    event = xmlStreamReader.next();

                    if ((event == XMLStreamConstants.CHARACTERS) || (event == XMLStreamConstants.CDATA)) {

                        String text = xmlStreamReader.getText();

                        if (cdata) {
                            xmlStreamWriter.writeCData(text);
                        } else {
                            xmlStreamWriter.writeCharacters(xmlStreamReader.getText());
                        }

                        break;
                    } else if (event == XMLStreamConstants.END_ELEMENT) {
                        break;
                    }
                }

                xmlStreamWriter.writeEndElement();
            }
        } else if (event == XMLStreamConstants.END_DOCUMENT) {
            break;
        }
    }
}

From source file:ca.uhn.fhir.parser.XmlParser.java

private void encodeXhtml(XhtmlDt theDt, XMLStreamWriter theEventWriter) throws XMLStreamException {
    if (theDt == null || theDt.getValue() == null) {
        return;//  w  ww  .  j av  a2 s  .c  o m
    }

    boolean firstElement = true;
    for (XMLEvent event : theDt.getValue()) {
        switch (event.getEventType()) {
        case XMLStreamConstants.ATTRIBUTE:
            Attribute attr = (Attribute) event;
            if (isBlank(attr.getName().getPrefix())) {
                if (isBlank(attr.getName().getNamespaceURI())) {
                    theEventWriter.writeAttribute(attr.getName().getLocalPart(), attr.getValue());
                } else {
                    theEventWriter.writeAttribute(attr.getName().getNamespaceURI(),
                            attr.getName().getLocalPart(), attr.getValue());
                }
            } else {
                theEventWriter.writeAttribute(attr.getName().getPrefix(), attr.getName().getNamespaceURI(),
                        attr.getName().getLocalPart(), attr.getValue());
            }

            break;
        case XMLStreamConstants.CDATA:
            theEventWriter.writeCData(((Characters) event).getData());
            break;
        case XMLStreamConstants.CHARACTERS:
        case XMLStreamConstants.SPACE:
            String data = ((Characters) event).getData();
            theEventWriter.writeCharacters(data);
            break;
        case XMLStreamConstants.COMMENT:
            theEventWriter.writeComment(((Comment) event).getText());
            break;
        case XMLStreamConstants.END_ELEMENT:
            theEventWriter.writeEndElement();
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            EntityReference er = (EntityReference) event;
            theEventWriter.writeEntityRef(er.getName());
            break;
        case XMLStreamConstants.NAMESPACE:
            Namespace ns = (Namespace) event;
            theEventWriter.writeNamespace(ns.getPrefix(), ns.getNamespaceURI());
            break;
        case XMLStreamConstants.START_ELEMENT:
            StartElement se = event.asStartElement();
            if (firstElement) {
                if (StringUtils.isBlank(se.getName().getPrefix())) {
                    String namespaceURI = se.getName().getNamespaceURI();
                    if (StringUtils.isBlank(namespaceURI)) {
                        namespaceURI = "http://www.w3.org/1999/xhtml";
                    }
                    theEventWriter.writeStartElement(se.getName().getLocalPart());
                    theEventWriter.writeDefaultNamespace(namespaceURI);
                } else {
                    String prefix = se.getName().getPrefix();
                    String namespaceURI = se.getName().getNamespaceURI();
                    theEventWriter.writeStartElement(prefix, se.getName().getLocalPart(), namespaceURI);
                    theEventWriter.writeNamespace(prefix, namespaceURI);
                }
                firstElement = false;
            } else {
                if (isBlank(se.getName().getPrefix())) {
                    if (isBlank(se.getName().getNamespaceURI())) {
                        theEventWriter.writeStartElement(se.getName().getLocalPart());
                    } else {
                        if (StringUtils.isBlank(se.getName().getPrefix())) {
                            theEventWriter.writeStartElement(se.getName().getLocalPart());
                            // theEventWriter.writeDefaultNamespace(se.getName().getNamespaceURI());
                        } else {
                            theEventWriter.writeStartElement(se.getName().getNamespaceURI(),
                                    se.getName().getLocalPart());
                        }
                    }
                } else {
                    theEventWriter.writeStartElement(se.getName().getPrefix(), se.getName().getLocalPart(),
                            se.getName().getNamespaceURI());
                }
                for (Iterator<?> attrIter = se.getAttributes(); attrIter.hasNext();) {
                    Attribute next = (Attribute) attrIter.next();
                    theEventWriter.writeAttribute(next.getName().getLocalPart(), next.getValue());
                }
            }
            break;
        case XMLStreamConstants.DTD:
        case XMLStreamConstants.END_DOCUMENT:
        case XMLStreamConstants.ENTITY_DECLARATION:
        case XMLStreamConstants.NOTATION_DECLARATION:
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
        case XMLStreamConstants.START_DOCUMENT:
            break;
        }

    }
}

From source file:com.fiorano.openesb.application.aps.Route.java

public void toJXMLString(XMLStreamWriter writer) throws XMLStreamException {

    //Start Route
    writer.writeStartElement("Route");

    //Add Route Attributes
    writer.writeAttribute("isP2PRoute", "" + m_isP2PRoute);
    writer.writeAttribute("isPersistant", "" + m_isPersitant);
    writer.writeAttribute("isDurable", "" + m_isDurable);
    writer.writeAttribute("applyTransformationAtSrc", "" + m_applyTransformationAtSrc);

    //Name//  ww  w .ja v  a  2 s .  c om
    FioranoStackSerializer.writeElement("Name", m_routeName, writer);

    //RouteGuid
    FioranoStackSerializer.writeElement("RouteGUID", m_routeGUID, writer);

    //TimeToLive
    FioranoStackSerializer.writeElement("TimeToLive", "" + m_iTimeToLive, writer);

    //SrcServiceInstance
    FioranoStackSerializer.writeElement("SrcServiceInstance", m_srcServInst, writer);

    //SrcPort
    FioranoStackSerializer.writeElement("SrcPort", m_srcPortName, writer);

    //TransformationXSL
    if (m_transformationXSL != null) {
        writer.writeStartElement("TransformationXSL");
        writer.writeCData(m_transformationXSL);
        writer.writeEndElement();

    }
    //Selectors
    if (m_selectors != null) {
        Iterator itr = m_selectors.keySet().iterator();

        while (itr.hasNext()) {
            writer.writeStartElement("Selector");
            String type = (String) itr.next();
            writer.writeAttribute("type", type);
            Object val = m_selectors.get(type);
            String value = null;
            if (val instanceof String) {
                value = (String) m_selectors.get(type);
            } else if (val instanceof XPathDmi) {
                value = ((XPathDmi) val).getXPath();

                HashMap map = ((XPathDmi) val).getNameSpace();

                if (map != null) {
                    Set keys = map.keySet();
                    Iterator iter = keys.iterator();

                    while (iter.hasNext()) {
                        String key = (String) iter.next();
                        String keyval = (String) map.get(key);
                        writer.writeAttribute("esb_" + key, keyval);
                    }
                }
            }
            writer.writeCharacters(value);

            //End Selector
            writer.writeEndElement();
        }
    }

    //TgtServiceInstance
    FioranoStackSerializer.writeElement("TgtServiceInstance", m_trgtServInst, writer);

    //TgtPort
    FioranoStackSerializer.writeElement("TgtPort", m_trgtPortName, writer);

    //LongDescription
    if (!StringUtils.isEmpty(m_longDescription)) {
        FioranoStackSerializer.writeElement("LongDescription", m_longDescription, writer);
    }

    //ShortDescription
    if (!StringUtils.isEmpty(m_shortDescription)) {
        FioranoStackSerializer.writeElement("ShortDescription", m_shortDescription, writer);
    }

    if (m_altDestination != null) {
        m_altDestination.toJXMLString(writer);
    }

    if (m_params != null && m_params.size() > 0) {
        Enumeration enums = m_params.elements();

        while (enums.hasMoreElements()) {
            Param param = (Param) enums.nextElement();
            if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue()))
                param.toJXMLString(writer);
        }
    }
    //End Route
    writer.writeEndElement();
}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String updateLocalization(String xml, String key, String value, String requestedLanguageId,
        String defaultLanguageId, boolean cdata, boolean localized) {

    xml = _sanitizeXML(xml);//from  www . j  a v  a2 s. c om

    XMLStreamReader xmlStreamReader = null;
    XMLStreamWriter xmlStreamWriter = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String availableLocales = StringPool.BLANK;

        // Read root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            availableLocales = xmlStreamReader.getAttributeValue(null, _AVAILABLE_LOCALES);

            if (Validator.isNull(availableLocales)) {
                availableLocales = defaultLanguageId;
            }

            if (availableLocales.indexOf(requestedLanguageId) == -1) {
                availableLocales = StringUtil.add(availableLocales, requestedLanguageId, StringPool.COMMA);
            }
        }

        UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();

        xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(unsyncStringWriter);

        xmlStreamWriter.writeStartDocument();
        xmlStreamWriter.writeStartElement(_ROOT);

        if (localized) {
            xmlStreamWriter.writeAttribute(_AVAILABLE_LOCALES, availableLocales);
            xmlStreamWriter.writeAttribute(_DEFAULT_LOCALE, defaultLanguageId);
        }

        _copyNonExempt(xmlStreamReader, xmlStreamWriter, requestedLanguageId, defaultLanguageId, cdata);

        xmlStreamWriter.writeStartElement(key);

        if (localized) {
            xmlStreamWriter.writeAttribute(_LANGUAGE_ID, requestedLanguageId);
        }

        if (cdata) {
            xmlStreamWriter.writeCData(value);
        } else {
            xmlStreamWriter.writeCharacters(value);
        }

        xmlStreamWriter.writeEndElement();
        xmlStreamWriter.writeEndElement();
        xmlStreamWriter.writeEndDocument();

        xmlStreamWriter.close();
        xmlStreamWriter = null;

        xml = unsyncStringWriter.toString();
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }

        if (xmlStreamWriter != null) {
            try {
                xmlStreamWriter.close();
            } catch (Exception e) {
            }
        }
    }

    return xml;
}

From source file:org.activiti.bpmn.converter.export.FieldExtensionExport.java

public static boolean writeFieldExtensions(List<FieldExtension> fieldExtensionList,
        boolean didWriteExtensionStartElement, XMLStreamWriter xtw) throws Exception {

    for (FieldExtension fieldExtension : fieldExtensionList) {

        if (StringUtils.isNotEmpty(fieldExtension.getFieldName())) {

            if (StringUtils.isNotEmpty(fieldExtension.getStringValue())
                    || StringUtils.isNotEmpty(fieldExtension.getExpression())) {

                if (didWriteExtensionStartElement == false) {
                    xtw.writeStartElement(ELEMENT_EXTENSIONS);
                    didWriteExtensionStartElement = true;
                }/*from   www . jav a  2s. c o  m*/

                xtw.writeStartElement(ACTIVITI_EXTENSIONS_PREFIX, ELEMENT_FIELD, ACTIVITI_EXTENSIONS_NAMESPACE);
                BpmnXMLUtil.writeDefaultAttribute(ATTRIBUTE_FIELD_NAME, fieldExtension.getFieldName(), xtw);

                if (StringUtils.isNotEmpty(fieldExtension.getStringValue())) {
                    xtw.writeStartElement(ACTIVITI_EXTENSIONS_PREFIX, ELEMENT_FIELD_STRING,
                            ACTIVITI_EXTENSIONS_NAMESPACE);
                    xtw.writeCData(fieldExtension.getStringValue());
                } else {
                    xtw.writeStartElement(ACTIVITI_EXTENSIONS_PREFIX, ATTRIBUTE_FIELD_EXPRESSION,
                            ACTIVITI_EXTENSIONS_NAMESPACE);
                    xtw.writeCharacters(fieldExtension.getExpression());
                }
                xtw.writeEndElement();
                xtw.writeEndElement();
            }
        }
    }
    return didWriteExtensionStartElement;
}