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:org.olat.ims.qti.editor.beecom.objects.Mattext.java

License:Apache License

/**
 * @see org.olat.ims.qti.editor.beecom.objects.QTIObject#addToElement(org.dom4j.Element)
 */// w  ww.  jav  a 2  s  .c  o m
@Override
public void addToElement(final Element root) {
    if (content != null) {
        final Element mattext = root.addElement("mattext");
        // Since we use rich text (html) as content, the text type is set to
        // "text/html". This way the document conforms to the qti standard.
        mattext.addAttribute("texttype", "text/html");
        mattext.addCDATA(content);
    }
}

From source file:org.olat.ims.qti.editor.QTIEditHelper.java

License:Apache License

/**
 * Add objectives.// www.  jav  a 2s. c om
 * 
 * @param root
 * @param objectives
 */
public static void addObjectives(final Element root, final String objectives) {
    if (objectives != null && objectives.length() > 0) {
        final Element mattext = root.addElement("objectives").addElement("material").addElement("mattext");
        mattext.addCDATA(objectives);
    }
}

From source file:org.olat.ims.qti.qpool.QTIExportProcessor.java

License:Apache License

/**
 * Collect the file and rewrite the /*  w w  w .ja va2 s  .  co  m*/
 * @param el
 * @param container
 * @param materials
 * @param paths
 */
private void collectResourcesInMatText(Element el, VFSContainer container, ItemsAndMaterials materials) {
    //mattext
    @SuppressWarnings("unchecked")
    List<Element> mattextList = el.selectNodes(".//mattext");
    for (Element mat : mattextList) {
        Attribute texttypeAttr = mat.attribute("texttype");
        String texttype = texttypeAttr.getValue();
        if ("text/html".equals(texttype)) {
            @SuppressWarnings("unchecked")
            List<Node> childElList = new ArrayList<Node>(mat.content());
            for (Node childEl : childElList) {
                mat.remove(childEl);
            }

            for (Node childEl : childElList) {
                if (Node.CDATA_SECTION_NODE == childEl.getNodeType()) {
                    CDATA data = (CDATA) childEl;
                    boolean changed = false;
                    String text = data.getText();
                    List<String> materialPaths = findMaterialInMatText(text);
                    for (String materialPath : materialPaths) {
                        VFSItem matVfsItem = container.resolve(materialPath);
                        if (matVfsItem instanceof VFSLeaf) {
                            String exportUri = generateExportPath(materials.getPaths(), matVfsItem);
                            materials.addMaterial(new ItemMaterial((VFSLeaf) matVfsItem, exportUri));
                            text = text.replaceAll(materialPath, exportUri);
                            changed = true;
                        }
                    }
                    if (changed) {
                        mat.addCDATA(text);
                    } else {
                        mat.add(childEl);
                    }
                } else {
                    mat.add(childEl);
                }
            }
        }
    }
}

From source file:org.opencms.importexport.CmsExport.java

License:Open Source License

/**
 * Exports one single user with all its data.<p>
 * /*from  w  w w.j  av a  2 s .  c  o m*/
 * @param parent the parent node to add the users to
 * @param user the user to be exported
 * 
 * @throws CmsImportExportException if something goes wrong
 * @throws SAXException if something goes wrong processing the manifest.xml
 */
protected void exportUser(Element parent, CmsUser user) throws CmsImportExportException, SAXException {

    try {
        // add user node to the manifest.xml
        Element e = parent.addElement(CmsImportVersion7.N_USER);
        e.addElement(CmsImportVersion7.N_NAME).addText(user.getSimpleName());
        // encode the password, using a base 64 decoder
        String passwd = new String(Base64.encodeBase64(user.getPassword().getBytes()));
        e.addElement(CmsImportVersion7.N_PASSWORD).addCDATA(passwd);
        e.addElement(CmsImportVersion7.N_FIRSTNAME).addText(user.getFirstname());
        e.addElement(CmsImportVersion7.N_LASTNAME).addText(user.getLastname());
        e.addElement(CmsImportVersion7.N_EMAIL).addText(user.getEmail());
        e.addElement(CmsImportVersion7.N_FLAGS).addText(Integer.toString(user.getFlags()));
        e.addElement(CmsImportVersion7.N_DATECREATED).addText(Long.toString(user.getDateCreated()));

        Element userInfoNode = e.addElement(CmsImportVersion7.N_USERINFO);
        List<String> keys = new ArrayList<String>(user.getAdditionalInfo().keySet());
        Collections.sort(keys);
        Iterator<String> itInfoKeys = keys.iterator();
        while (itInfoKeys.hasNext()) {
            String key = itInfoKeys.next();
            if (key == null) {
                continue;
            }
            Object value = user.getAdditionalInfo(key);
            if (value == null) {
                continue;
            }
            Element entryNode = userInfoNode.addElement(CmsImportVersion7.N_USERINFO_ENTRY);
            entryNode.addAttribute(CmsImportVersion7.A_NAME, key);
            entryNode.addAttribute(CmsImportVersion7.A_TYPE, value.getClass().getName());
            try {
                // serialize the user info and write it into a file
                entryNode.addCDATA(CmsDataTypeUtil.dataExport(value));
            } catch (IOException ioe) {
                getReport().println(ioe);
                if (LOG.isErrorEnabled()) {
                    LOG.error(Messages.get().getBundle().key(Messages.ERR_IMPORTEXPORT_ERROR_EXPORTING_USER_1,
                            user.getName()), ioe);
                }
            }
        }

        // append node for roles of user
        Element userRoles = e.addElement(CmsImportVersion7.N_USERROLES);
        List<CmsRole> roles = OpenCms.getRoleManager().getRolesOfUser(getCms(), user.getName(), "", true, true,
                true);
        for (int i = 0; i < roles.size(); i++) {
            String roleName = roles.get(i).getFqn();
            userRoles.addElement(CmsImportVersion7.N_USERROLE).addText(roleName);
        }
        // append the node for groups of user
        Element userGroups = e.addElement(CmsImportVersion7.N_USERGROUPS);
        List<CmsGroup> groups = getCms().getGroupsOfUser(user.getName(), true, true);
        for (int i = 0; i < groups.size(); i++) {
            String groupName = groups.get(i).getName();
            userGroups.addElement(CmsImportVersion7.N_USERGROUP).addText(groupName);
        }
        // write the XML
        digestElement(parent, e);
    } catch (CmsException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(e.getLocalizedMessage(), e);
        }
        throw new CmsImportExportException(e.getMessageContainer(), e);
    }
}

From source file:org.opencms.relations.CmsLinkUpdateUtil.java

License:Open Source License

/**
 * Updates the given xml node with the given value.<p>
 * // w  w  w . java2  s  . c om
 * @param parent the parent node
 * @param nodeName the node to update
 * @param value the value to use to update the given node, can be <code>null</code>
 * @param cdata if the value should be in a CDATA section or not
 */
private static void updateNode(Element parent, String nodeName, String value, boolean cdata) {

    // get current node element
    Element nodeElement = parent.element(nodeName);
    if (value != null) {
        if (nodeElement == null) {
            // element wasn't there before, add element and set value
            nodeElement = parent.addElement(nodeName);
        }
        // element is there, update element value
        nodeElement.clearContent();
        if (cdata) {
            nodeElement.addCDATA(value);
        } else {
            nodeElement.addText(value);
        }
    } else {
        // remove only if element exists
        if (nodeElement != null) {
            // remove element
            parent.remove(nodeElement);
        }
    }
}

From source file:org.opencms.xml.types.CmsXmlHtmlValue.java

License:Open Source License

/**
 * @see org.opencms.xml.types.I_CmsXmlContentValue#setStringValue(org.opencms.file.CmsObject, java.lang.String)
 *///from w  w  w  . j a v a 2s .c o m
public void setStringValue(CmsObject cms, String value) {

    Element content = m_element.element(CmsXmlPage.NODE_CONTENT);
    Element links = m_element.element(CmsXmlPage.NODE_LINKS);
    CmsLinkProcessor linkProcessor = null;

    String encoding = m_document.getEncoding();
    linkProcessor = m_document.getLinkProcessor(cms, new CmsLinkTable());

    String finalValue = value;
    if (finalValue != null) {
        // nested CDATA tags are not allowed, so replace CDATA tags with their contents
        finalValue = finalValue.replaceAll("(?s)// <!\\[CDATA\\[(.*?)// \\]\\]>", "$1"); // special case for embedded Javascript 
        finalValue = finalValue.replaceAll("(?s)<!\\[CDATA\\[(.*?)\\]\\]>", "$1");
    }
    if (encoding != null) {
        // ensure all chars in the given content are valid chars for the selected charset
        finalValue = CmsEncoder.adjustHtmlEncoding(finalValue, encoding);
    }

    // remove unnecessary tags if required
    String contentConversion = m_document.getConversion();
    if (CmsHtmlConverter.isConversionEnabled(contentConversion)) {
        CmsHtmlConverter converter = new CmsHtmlConverter(encoding, contentConversion);
        finalValue = converter.convertToStringSilent(finalValue);
    }
    if (linkProcessor != null) {
        try {
            // replace links in HTML by macros and fill link table      
            finalValue = linkProcessor.replaceLinks(finalValue);
        } catch (Exception exc) {
            throw new CmsRuntimeException(Messages.get().container(Messages.ERR_HTML_DATA_PROCESSING_0), exc);
        }
    }

    content.clearContent();
    links.clearContent();

    if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(finalValue)) {
        content.addCDATA(finalValue);
        if (linkProcessor != null) {
            // may be null in case of default value generation (i.e. setStringValue(String) was called)

            CmsLinkTable linkTable = linkProcessor.getLinkTable();
            for (Iterator<CmsLink> i = linkTable.iterator(); i.hasNext();) {
                CmsLink link = i.next();
                CmsLinkUpdateUtil.updateXmlForHtmlValue(link, link.getName(),
                        links.addElement(CmsXmlPage.NODE_LINK));
            }
        }
    }

    // ensure the String value is re-calculated next time
    m_stringValue = null;
}

From source file:org.opensha.commons.util.XMLUtils.java

License:Apache License

public static void byteArrayToXML(Element parent, byte[] array, String elName) {
    Preconditions.checkNotNull(parent, "parent element can't be null");
    Preconditions.checkNotNull(array, "array cannot be null");
    Preconditions.checkArgument(array.length > 0, "array cannot be empty");
    Preconditions.checkNotNull(elName, "elName cannot be null");
    Preconditions.checkArgument(!elName.isEmpty(), "elName cannot be empty");
    Element el = parent.addElement(elName);
    String str = Base64.encodeBase64String(array);
    el.addCDATA(str);
}

From source file:org.panopticode.report.treemap.BaseTreemap.java

License:Open Source License

protected void renderJavascriptFunctions(Element parentElement, List<MetricDeclaration> projectMetrics,
        List<MetricDeclaration> packageMetrics, List<MetricDeclaration> fileMetrics,
        List<MetricDeclaration> classMetrics, List<MetricDeclaration> methodMetrics) {
    StringBuffer javascript;//w  ww . j a  va 2 s.  c  o  m

    javascript = new StringBuffer();

    javascript.append("\n");
    javascript.append(
            "function showDetails(projectName, projectMetrics, packageName, packageMetrics, fileName, fileMetrics, className, classMetrics, methodName, methodMetrics) {\n");
    javascript.append("  replaceText('projectName', 'Project: ' + projectName);\n");
    javascript.append(buildReplaceTextForMetrics("ProjectMetric", "projectMetrics", projectMetrics));
    javascript.append("  replaceText('packageName', 'Package: ' + packageName);\n");
    javascript.append(buildReplaceTextForMetrics("PackageMetric", "packageMetrics", packageMetrics));
    javascript.append("  replaceText('fileName', 'File: ' + fileName);\n");
    javascript.append(buildReplaceTextForMetrics("FileMetric", "fileMetrics", fileMetrics));
    javascript.append("  replaceText('className', 'Class: ' + className);\n");
    javascript.append(buildReplaceTextForMetrics("ClassMetric", "classMetrics", classMetrics));
    javascript.append("  replaceText('methodName', 'Method: ' + methodName);\n");
    javascript.append(buildReplaceTextForMetrics("MethodMetric", "methodMetrics", methodMetrics));
    javascript.append("}\n");
    javascript.append("\n");
    javascript.append("function getMetric(metricsMap, key) {\n");
    javascript.append("  var index;\n");
    javascript.append("  for (index = 0; index < metricsMap.length; index++) {\n");
    javascript.append("    if (metricsMap[index][0] == key) {\n");
    javascript.append("      return metricsMap[index][1];\n");
    javascript.append("    }\n");
    javascript.append("  }\n");
    javascript.append("  return 'Unknown';\n");
    javascript.append("}\n");
    javascript.append("\n");
    javascript.append("function replaceText(id, newText) {\n");
    javascript.append("  var parentElement;\n");
    javascript.append("  var newTextNode;\n");
    javascript.append("\n");
    javascript.append("  newTextNode = document.createTextNode(newText);\n");
    javascript.append("\n");
    javascript.append("  parentElement = document.getElementById(id);\n");
    javascript.append("  parentElement.replaceChild(newTextNode, parentElement.firstChild);\n");
    javascript.append("}\n");

    Element scriptElement = parentElement.addElement("script", "http://www.w3.org/2000/svg");
    scriptElement.addAttribute("type", "text/ecmascript");
    scriptElement.addCDATA(javascript.toString());
}

From source file:org.pentaho.actionsequence.dom.ActionIfStatement.java

License:Open Source License

/**
 * Sets the if condition. The condition should be well formatted javascript.
 * //from   w w w .  j  av a2  s. co  m
 * @param condition
 *          the condition.
 */
public void setCondition(String condition) {
    Element conditionElement = controlElement.element(ActionSequenceDocument.CONDITION_NAME);
    if (conditionElement == null) {
        conditionElement = controlElement.addElement(ActionSequenceDocument.CONDITION_NAME);
    }
    conditionElement.clearContent();
    conditionElement.addCDATA(condition);
    ActionSequenceDocument.fireControlStatementChanged(this);
}

From source file:org.pentaho.actionsequence.dom.actions.ActionDefinition.java

License:Open Source License

/**
 * Sets the value of the component definition element at the specified XPath.
 * /*ww  w.ja v a  2 s  . com*/
 * @param compDefXpath
 *          the XPath of the element relative to the component definition element.
 * @param value
 *          the value to be assigned to the element
 * @param useCData
 *          whether a CDATA node should be used to save the value
 */
public void setComponentDefinition(String compDefXpath, String value, boolean useCData) {
    if (value == null) {
        Element[] componentDefs = getComponentDefElements(compDefXpath);
        for (int i = 0; i < componentDefs.length; i++) {
            componentDefs[i].detach();
        }
        if (componentDefs.length > 0) {
            ActionSequenceDocument.fireActionChanged(this);
        }
    } else {
        Element componentDef = getComponentDefElement(compDefXpath);
        if (componentDef == null) {
            componentDef = DocumentHelper.makeElement(actionDefElement,
                    ActionSequenceDocument.COMPONENT_DEF_NAME + "/" + compDefXpath); //$NON-NLS-1$
        }
        componentDef.clearContent();
        if (useCData) {
            componentDef.addCDATA(value);
        } else {
            componentDef.setText(value);
        }
        ActionSequenceDocument.fireActionChanged(this);
    }
}