Example usage for org.dom4j Element addCDATA

List of usage examples for org.dom4j Element addCDATA

Introduction

In this page you can find the example usage for org.dom4j Element addCDATA.

Prototype

Element addCDATA(String cdata);

Source Link

Document

Adds a new CDATA node with the given text to this element.

Usage

From source file:com.nokia.ant.Database.java

License:Open Source License

private Element addTextElement(Element parent, String name, String text, boolean escape) {
    Element element = parent.addElement(name);
    if (text != null) {
        if (escape) {
            element.addCDATA(text);
        } else {/*w  w w . j  av a 2s  .  com*/
            element.setText(text);
        }
    }
    return element;
}

From source file:com.openedit.users.filesystem.XmlUserArchive.java

License:Open Source License

public void saveUser(User user) throws UserManagerException {
    if (user.isVirtual()) {
        log.error("Cannot save virtual users: " + user.getUserName());
        return;/*  w  w w  .ja v a 2  s  . c o m*/
    }
    DocumentFactory factory = DocumentFactory.getInstance();
    Document doc = factory.createDocument();
    Element userElem = doc.addElement("user");
    userElem.addAttribute("enabled", Boolean.toString(user.isEnabled()));
    if (user.getUserName() == null) {
        int id = getUserIdCounter().incrementCount();
        String newid = String.valueOf(id);
        user.setId(newid);
    }
    Element userNameElem = userElem.addElement("user-name");
    userNameElem.addCDATA(user.getUserName());

    Element passwordElem = userElem.addElement("password");
    //
    if (user.getPassword() != null && !user.getPassword().equals("")) {
        String ps = user.getPassword();
        ps = encrypt(ps);
        // password may have changed we should set it so it's not in plain
        // text anymore.
        user.setPassword(ps);
        passwordElem.addCDATA(ps);
    }
    Element creationDateElem = userElem.addElement("creation-date");
    if (user.getCreationDate() != null) {
        creationDateElem.setText(String.valueOf(user.getCreationDate().getTime()));
    } else {
        creationDateElem.setText(String.valueOf(System.currentTimeMillis()));
    }

    // Tuan add property lastLogined-Time
    Element lastLoginTime = userElem.addElement("lastLogined-Time");
    lastLoginTime.setText(DateStorageUtil.getStorageUtil().formatForStorage(new Date()));

    MapPropertyContainer map = (MapPropertyContainer) user.getPropertyContainer();
    if (map != null) {
        Element propertiesElem = map.createPropertiesElement("properties");
        userElem.add(propertiesElem);
    }
    if (user.getGroups() != null) {
        for (Iterator iter = user.getGroups().iterator(); iter.hasNext();) {
            Group group = (Group) iter.next();
            Element child = userElem.addElement("group");
            child.addAttribute("id", group.getId());
        }
    }
    synchronized (user) {
        // File file = loadUserFile(user.getUserName());
        XmlFile xfile = new XmlFile();
        xfile.setRoot(doc.getRootElement());
        xfile.setPath(getUserDirectory() + "/" + user.getUserName() + ".xml");
        getXmlArchive().saveXml(xfile, null);

        getUserNameToUserMap().put(user.getUserName(), user);
    }
}

From source file:com.ostrichemulators.semtool.ui.components.playsheets.BrowserPlaySheet2.java

License:Open Source License

protected BufferedImage getExportImageFromSVGBlock() throws IOException {
    log.debug("Using SVG block to save image.");
    DOMReader rdr = new DOMReader();
    Document doc = rdr.read(engine.getDocument());
    Document svgdoc = null;/*from w  w w . ja va 2 s. com*/
    File svgfile = null;
    try {
        Map<String, String> namespaceUris = new HashMap<>();
        namespaceUris.put("svg", "http://www.w3.org/2000/svg");
        namespaceUris.put("xhtml", "http://www.w3.org/1999/xhtml");

        XPath xp = DocumentHelper.createXPath("//svg:svg");
        xp.setNamespaceURIs(namespaceUris);
        // don't forget about the styles
        XPath stylexp = DocumentHelper.createXPath("//xhtml:style");
        stylexp.setNamespaceURIs(namespaceUris);

        svgdoc = DocumentHelper.createDocument();
        Element svg = null;
        List<?> theSVGElements = xp.selectNodes(doc);
        if (theSVGElements.size() == 1) {
            svg = Element.class.cast(theSVGElements.get(0)).createCopy();
        } else {
            int currentTop = 0;
            int biggestSize = 0;
            for (int i = 0; i < theSVGElements.size(); i++) {
                Element thisElement = Element.class.cast(theSVGElements.get(i)).createCopy();
                int thisSize = thisElement.asXML().length();
                if (thisSize > biggestSize) {
                    currentTop = i;
                    biggestSize = thisSize;
                }
            }
            svg = Element.class.cast(theSVGElements.get(currentTop)).createCopy();
        }

        svgdoc.setRootElement(svg);

        Element oldstyle = Element.class.cast(stylexp.selectSingleNode(doc));
        if (null != oldstyle) {
            Element defs = svg.addElement("defs");
            Element style = defs.addElement("style");
            style.addAttribute("type", "text/css");
            String styledata = oldstyle.getTextTrim();
            style.addCDATA(styledata);
            // put the stylesheet definitions first
            List l = svg.elements();
            l.remove(defs);
            l.add(0, defs);
        }

        // clean up the SVG a little...
        // d3 comes up with coords like
        // M360,27475.063247863247C450,27475.063247863247 450,27269.907692307694 540,27269.907692307694
        XPath cleanxp1 = DocumentHelper.createXPath("//svg:path");
        Pattern pat = Pattern.compile(",([0-9]+)\\.([0-9]{1,2})[0-9]+");
        cleanxp1.setNamespaceURIs(namespaceUris);
        List<?> cleanups = cleanxp1.selectNodes(svgdoc);
        for (Object n : cleanups) {
            Element e = Element.class.cast(n);
            String dstr = e.attributeValue("d");
            Matcher m = pat.matcher(dstr);
            dstr = m.replaceAll(",$1.$2 ");
            e.addAttribute("d", dstr.replaceAll("([0-9])C([0-9])", "$1 C$2").trim());
        }
        XPath cleanxp2 = DocumentHelper.createXPath("//svg:g[@class='node']");
        cleanxp2.setNamespaceURIs(namespaceUris);
        cleanups = cleanxp2.selectNodes(svgdoc);
        for (Object n : cleanups) {
            Element e = Element.class.cast(n);
            String dstr = e.attributeValue("transform");
            Matcher m = pat.matcher(dstr);
            dstr = m.replaceAll(",$1.$2");
            e.addAttribute("transform", dstr.trim());
        }

        svgfile = File.createTempFile("graphviz-", ".svg");
        try (Writer svgw = new BufferedWriter(new FileWriter(svgfile))) {
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter xmlw = new XMLWriter(svgw, format);
            xmlw.write(svgdoc);
            xmlw.close();

            if (log.isDebugEnabled()) {
                FileUtils.copyFile(svgfile, new File(FileUtils.getTempDirectory(), "graphvisualization.svg"));
            }
        }

        try (Reader svgr = new BufferedReader(new FileReader(svgfile))) {
            TranscoderInput inputSvg = new TranscoderInput(svgr);

            ByteArrayOutputStream baos = new ByteArrayOutputStream((int) svgfile.length());
            TranscoderOutput outputPng = new TranscoderOutput(baos);

            try {
                PNGTranscoder transcoder = new PNGTranscoder();
                transcoder.addTranscodingHint(PNGTranscoder.KEY_INDEXED, 256);
                transcoder.addTranscodingHint(ImageTranscoder.KEY_BACKGROUND_COLOR, Color.WHITE);
                transcoder.transcode(inputSvg, outputPng);
            } catch (Throwable t) {
                log.error(t, t);
            }
            baos.flush();
            baos.close();

            return ImageIO.read(new ByteArrayInputStream(baos.toByteArray()));
        }
    } catch (InvalidXPathException e) {
        log.error(e);
        String msg = "Problem creating image";
        if (null != svgdoc) {
            try {
                File errsvg = new File(FileUtils.getTempDirectory(), "graphvisualization.svg");
                FileUtils.write(errsvg, svgdoc.asXML(), Charset.defaultCharset());
                msg = "Could not create the image. SVG data store here: " + errsvg.getAbsolutePath();
            } catch (IOException ex) {
                // don't care
            }
        }
        throw new IOException(msg, e);
    } finally {
        if (null != svgfile) {
            FileUtils.deleteQuietly(svgfile);
        }
    }
}

From source file:com.pureinfo.dolphin.script.lang.Expression.java

License:Open Source License

/**
 * @see com.pureinfo.force.xml.IXMLSupporter#toXMLElement(org.dom4j.Element)
 *//*from   w  ww  . j a v  a  2  s  . c om*/
public void toXMLElement(Element _element) throws PureException {
    //to export body
    Element ele;
    switch (m_nType) {
    case TYPE_STRING: {
        ele = _element.addElement("str");
        ele.addCDATA((String) m_body);
        break;
    }
    case TYPE_VARIABLE: {
        ele = _element.addElement("var");
        ((IXMLSupporter) m_body).toXMLElement(ele);
        break;
    }
    case TYPE_FUNCTION: {
        ele = _element.addElement("func");
        ((IXMLSupporter) m_body).toXMLElement(ele);
        break;
    }
    }

    //to export formatters
    Object formatter;
    for (int i = 0; i < m_formatters.size(); i++) {
        formatter = m_formatters.get(i);
        ele = _element.addElement("op");
        ele.addAttribute("name", ">>");

        if (formatter instanceof String) {
            ele = _element.addElement("str");
            ele.addCDATA((String) formatter);
        } else {
            ele = _element.addElement("var");
            ((Variable) formatter).toXMLElement(ele);
        }
    }
}

From source file:com.pureinfo.dolphin.script.lang.ScriptBlock.java

License:Open Source License

/**
 * @see com.pureinfo.force.xml.IXMLSupporter#toXMLElement(org.dom4j.Element)
 *///w  w  w.  j a  v  a2  s .com
public void toXMLElement(Element _element) throws PureException {
    Object content;
    Element element;
    for (int i = 0; i < m_contents.size(); i++) {
        content = m_contents.get(i);
        if (content instanceof String) {
            element = _element.addElement("text");
            element.addCDATA((String) content);
        } else {
            element = _element.addElement("stmt");
            ((IXMLSupporter) content).toXMLElement(element);
        }
    }
}

From source file:com.suneee.core.util.XMLProperties.java

License:Open Source License

/**
 * Sets a property to an array of values. Multiple values matching the same property
 * is mapped to an XML file as multiple elements containing each value.
 * For example, using the name "foo.bar.prop", and the value string array containing
 * {"some value", "other value", "last value"} would produce the following XML:
 * <pre>/* w  w w .ja va2s . c o  m*/
 * &lt;foo&gt;
 *     &lt;bar&gt;
 *         &lt;prop&gt;some value&lt;/prop&gt;
 *         &lt;prop&gt;other value&lt;/prop&gt;
 *         &lt;prop&gt;last value&lt;/prop&gt;
 *     &lt;/bar&gt;
 * &lt;/foo&gt;
 * </pre>
 *
 * @param name the name of the property.
 * @param values the values for the property (can be empty but not null).
 */
public void setProperties(String name, List<String> values) {
    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML heirarchy,
    // stopping one short.
    Element element = document.getRootElement();
    for (int i = 0; i < propName.length - 1; i++) {
        // If we don't find this part of the property in the XML heirarchy
        // we add it as a new node
        if (element.element(propName[i]) == null) {
            element.addElement(propName[i]);
        }
        element = element.element(propName[i]);
    }
    String childName = propName[propName.length - 1];
    // We found matching property, clear all children.
    List<Element> toRemove = new ArrayList<Element>();
    Iterator iter = element.elementIterator(childName);
    while (iter.hasNext()) {
        toRemove.add((Element) iter.next());
    }
    for (iter = toRemove.iterator(); iter.hasNext();) {
        element.remove((Element) iter.next());
    }
    // Add the new children.
    for (String value : values) {
        Element childElement = element.addElement(childName);
        if (value.startsWith("<![CDATA[")) {
            Iterator it = childElement.nodeIterator();
            while (it.hasNext()) {
                Node node = (Node) it.next();
                if (node instanceof CDATA) {
                    childElement.remove(node);
                    break;
                }
            }
            childElement.addCDATA(value.substring(9, value.length() - 3));
        } else {
            childElement.setText(StringEscapeUtils.escapeXml(value));
        }
    }
    saveProperties();

    // Generate event.
    /*Map<String, Object> params = new HashMap<String, Object>();
    params.put("value", values);
    PropertyEventDispatcher.dispatchEvent(name,
        PropertyEventDispatcher.EventType.xml_property_set, params);*/
}

From source file:com.suneee.core.util.XMLProperties.java

License:Open Source License

/**
 * Sets the value of the specified property. If the property doesn't
 * currently exist, it will be automatically created.
 *
 * @param name  the name of the property to set.
 * @param value the new value for the property.
 *///from  w  w w  .  jav  a2s.  com
public synchronized void setProperty(String name, String value) {
    if (!StringEscapeUtils.escapeXml(name).equals(name)) {
        throw new IllegalArgumentException("Property name cannot contain XML entities.");
    }
    if (name == null) {
        return;
    }
    if (value == null) {
        value = "";
    }

    // Set cache correctly with prop name and value.
    propertyCache.put(name, value);

    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML heirarchy.
    Element element = document.getRootElement();
    for (String aPropName : propName) {
        // If we don't find this part of the property in the XML heirarchy
        // we add it as a new node
        if (element.element(aPropName) == null) {
            element.addElement(aPropName);
        }
        element = element.element(aPropName);
    }
    // Set the value of the property in this node.
    if (value.startsWith("<![CDATA[")) {
        Iterator it = element.nodeIterator();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            if (node instanceof CDATA) {
                element.remove(node);
                break;
            }
        }
        element.addCDATA(value.substring(9, value.length() - 3));
    } else {
        element.setText(value);
    }
    // Write the XML properties to disk
    saveProperties();

    // Generate event.
    /*   Map<String, Object> params = new HashMap<String, Object>();
       params.put("value", value);
       PropertyEventDispatcher.dispatchEvent(name,
        PropertyEventDispatcher.EventType.xml_property_set, params);*/
}

From source file:com.tao.realweb.util.XMLProperties.java

License:Open Source License

/**
 * Sets a property to an array of values. Multiple values matching the same property
 * is mapped to an XML file as multiple elements containing each value.
 * For example, using the name "foo.bar.prop", and the value string array containing
 * {"some value", "other value", "last value"} would produce the following XML:
 * <pre>//from   w  w w. ja  v a 2s  . c o m
 * &lt;foo&gt;
 *     &lt;bar&gt;
 *         &lt;prop&gt;some value&lt;/prop&gt;
 *         &lt;prop&gt;other value&lt;/prop&gt;
 *         &lt;prop&gt;last value&lt;/prop&gt;
 *     &lt;/bar&gt;
 * &lt;/foo&gt;
 * </pre>
 *
 * @param name the name of the property.
 * @param values the values for the property (can be empty but not null).
 */
public void setProperties(String name, List<String> values) {
    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML heirarchy,
    // stopping one short.
    Element element = document.getRootElement();
    for (int i = 0; i < propName.length - 1; i++) {
        // If we don't find this part of the property in the XML heirarchy
        // we add it as a new node
        if (element.element(propName[i]) == null) {
            element.addElement(propName[i]);
        }
        element = element.element(propName[i]);
    }
    String childName = propName[propName.length - 1];
    // We found matching property, clear all children.
    List<Element> toRemove = new ArrayList<Element>();
    Iterator iter = element.elementIterator(childName);
    while (iter.hasNext()) {
        toRemove.add((Element) iter.next());
    }
    for (iter = toRemove.iterator(); iter.hasNext();) {
        element.remove((Element) iter.next());
    }
    // Add the new children.
    for (String value : values) {
        Element childElement = element.addElement(childName);
        if (value.startsWith("<![CDATA[")) {
            Iterator it = childElement.nodeIterator();
            while (it.hasNext()) {
                Node node = (Node) it.next();
                if (node instanceof CDATA) {
                    childElement.remove(node);
                    break;
                }
            }
            childElement.addCDATA(value.substring(9, value.length() - 3));
        } else {
            childElement.setText(StringEscapeUtils.escapeXml(value));
        }
    }
    saveProperties();

    // Generate event.
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("value", values);
    PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params);
}

From source file:com.tao.realweb.util.XMLProperties.java

License:Open Source License

/**
 * Sets the value of the specified property. If the property doesn't
 * currently exist, it will be automatically created.
 *
 * @param name  the name of the property to set.
 * @param value the new value for the property.
 *//*  w w  w. jav a  2 s.co  m*/
public synchronized void setProperty(String name, String value) {
    if (!StringEscapeUtils.escapeXml(name).equals(name)) {
        throw new IllegalArgumentException("Property name cannot contain XML entities.");
    }
    if (name == null) {
        return;
    }
    if (value == null) {
        value = "";
    }

    // Set cache correctly with prop name and value.
    propertyCache.put(name, value);

    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML heirarchy.
    Element element = document.getRootElement();
    for (String aPropName : propName) {
        // If we don't find this part of the property in the XML heirarchy
        // we add it as a new node
        if (element.element(aPropName) == null) {
            element.addElement(aPropName);
        }
        element = element.element(aPropName);
    }
    // Set the value of the property in this node.
    if (value.startsWith("<![CDATA[")) {
        Iterator it = element.nodeIterator();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            if (node instanceof CDATA) {
                element.remove(node);
                break;
            }
        }
        element.addCDATA(value.substring(9, value.length() - 3));
    } else {
        element.setText(value);
    }
    // Write the XML properties to disk
    saveProperties();

    // Generate event.
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("value", value);
    PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params);
}

From source file:com.tedi.engine.XMLOutput.java

License:Open Source License

public String process(Vector structureV, Vector dataV) {
    doc = DocumentHelper.createDocument();
    Element root = null;/*from w w w.j a v  a  2s  .co  m*/
    String suppress = null;
    String result = "";

    if (logger.isDebugEnabled()) {
        logger.debug("Processing XML output.");
    }

    if (structureV != null && structureV.size() > 0 && structureV != null) {
        try {
            // main loop for creating the XML document
            for (int i = 0; i < structureV.size(); i++) {
                String value = (String) dataV.elementAt(i);
                Vector fieldV = (Vector) structureV.elementAt(i);
                String path = (String) fieldV.elementAt(0);
                String endpoint = (String) fieldV.elementAt(1);
                String datatype = (String) fieldV.elementAt(4);
                // deal with suppression criteria
                // --------------------------------------------------------------
                if (suppress != null) {
                    if (path.indexOf(suppress) > -1)
                        continue;
                    else
                        suppress = null;
                }
                // if printing of this part of the tree was supressed, skip
                // ahead
                if (value.equals(TEDI_SUPRESS)) {
                    if (suppress == null)
                        suppress = path;
                    continue;
                }
                // ---------------------------------------------------------------------------------------------
                Vector currentRowVector = (Vector) structureV.elementAt(i);
                // Only non-calc fields make it to output
                if (!currentRowVector.elementAt(4).toString().equals(CALC)) {
                    StringTokenizer st = new StringTokenizer(path, "/");
                    int count = st.countTokens();
                    // factor out the root
                    String firstToken = st.nextToken();
                    count--;
                    // Set root if required
                    if (root == null) {
                        this.setSystemID(firstToken);
                        root = DocumentHelper.createElement(firstToken);
                        doc.setRootElement(root);
                        if (count == 0 && endpoint.length() == 0)
                            continue;
                    } else if (endpoint.length() == 0)
                        count--;
                    // Handle error condition of no root
                    if (root == null) {
                        execResults.addMessage(ExecutionResults.M_ERROR, ExecutionResults.J2EE_TARGET_ERR,
                                "Mapping defintion error locating root element declaration.");
                        execResults.setReturnCode(ExecutionResults.RESULT_ERROR);
                        break;
                    }
                    if (endpoint.length() > 0) {
                        if (mapFile.isSuppressAttribIfEmpty() && value.length() == 0)
                            continue;
                        else if (mapFile.isSuppressAttribIfHasOnlyWhitespace() && value.trim().length() == 0)
                            continue;
                    }
                    // this is the main loop for a path
                    Element elem = root;
                    for (int j = 0; j < count; j++) {
                        String item = st.nextToken();
                        List childList = elem.elements(item);
                        if (childList.size() > 0) {
                            elem = (Element) childList.get(childList.size() - 1);
                        } else {
                            elem = elem.addElement(item);
                        }
                    }
                    if (endpoint.length() == 0) {
                        elem = elem.addElement(st.nextToken());
                        if (datatype.equals(TEXT_CDATA))
                            elem.addCDATA(value);
                        else if (!datatype.equals(NOT_MAPPABLE))
                            elem.addText(value);
                    } else {
                        elem.addAttribute(endpoint, value);
                    }
                }
            } // end for() main loop

            // "isSuppressDocType" indicator re-used to suppress NS prefixes
            if (!isSuppressDocType) {
                addNSPrefixesToDocument();
            }

            result = cleanDocument(doc);
        } catch (Exception e) {
            execResults.addMessage(ExecutionResults.M_ERROR, ExecutionResults.J2EE_TARGET_ERR,
                    "Error creating XML document: " + e.getMessage());
            execResults.setReturnCode(ExecutionResults.RESULT_ERROR);
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Processing of XML output completed.");
    }
    return result;
}