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.infoglue.cms.util.dom.DOMBuilder.java

License:Open Source License

/**
 * This method adds a cdata-element with a given name to a given parent element.
 *///  w  ww . j a  va 2 s  . com

public Element addCDATAElement(Element element, String text) {
    Element newElement = element.addCDATA(text);
    return newElement;
}

From source file:org.infoglue.igide.editor.IGMultiPageEditor.java

License:Open Source License

/**
 * Saves the multi-page editor's document.
 *//* www  .  j  av a2 s. c o  m*/
public void doSave(IProgressMonitor monitor) {
    Logger.logConsole("YES - doSave: " + monitor + ":" + isReloadCMSPushCall);
    saving = true;
    boolean dirtyflag = isDirty();
    Utils.getMonitor(monitor).beginTask("Saving content to CMS", 100);

    for (int i = 0; i < getPageCount(); i++) {
        IEditorPart editor = getEditor(i);
        editor.doSave(monitor);

    }

    Logger.logConsole("Saved each editor part...");
    Utils.getMonitor(monitor).worked(25);
    InfoglueEditorInput input = getInfoglueEditorInput();
    Logger.logConsole("input: " + input);
    input.getContent().doSave(monitor);
    System.out.println("isReloadCMSPushCall: " + isReloadCMSPushCall);
    if (!isReloadCMSPushCall)
        try {
            Logger.logConsole("saveLocalXML called");
            ContentVersion cv = InfoglueCMS.getProjectContentVersion(
                    input.getContent().getNode().getProject().getName(), input.getContent().getNode().getId());

            SAXReader reader = new SAXReader();

            Document document = reader.read(new StringReader(cv.getValue()));
            Map<String, String> namespaceUris = new HashMap<String, String>();
            namespaceUris.put("art", "x-schema:ArticleSchema.xml");

            XPath xPath = DocumentHelper.createXPath("/art:article/art:attributes");
            xPath.setNamespaceURIs(namespaceUris);

            Element attributesNode = (Element) xPath.selectSingleNode(document); //(Element)document.selectSingleNode("/article/attributes");

            @SuppressWarnings("unchecked")
            List<Element> attributes = attributesNode.elements();//document.selectNodes("//attributes/*");

            EditableInfoglueContent content = input.getContent();
            final ArrayList<String> contentAttributes = content.getAttributesOrder();

            Map<String, Element> attributeMap = new HashMap<String, Element>();

            // This loop remove elements from the DOM element
            for (Element attribute : attributes) {
                // DOM4j will shorten empty attributes, which is not good for InfoGlue
                if ("".equals(attribute.getText())) {
                    attribute.clearContent();
                    attribute.addCDATA("");
                }

                if (attributeMap.containsKey(attribute.getName())) {
                    Logger.logConsole("Found duplicate attribute. Removing it. Name: " + attribute.getName());
                    attributesNode.remove(attribute);
                } else {
                    String attributeName = attribute.getName();
                    if (contentAttributes.contains(attributeName)) {
                        attributeMap.put(attributeName, attribute);
                    } else if (!"IGAuthorFullName".equals(attributeName)
                            && !"IGAuthorEmail".equals(attributeName)) {
                        Logger.logConsole(
                                "Found attribute in version that is not in the content type. Removing. Name: "
                                        + attributeName);
                        attributesNode.remove(attribute);
                    }
                }
            }

            // This loop add elements to the DOM element
            for (int i = 0; i < getPageCount(); i++) {
                IEditorPart editor = getEditor(i);
                editor.doSave(monitor);
                IEditorInput editorInput = editor.getEditorInput();
                AttributeEditorInput attributeInput = null;
                if (editorInput instanceof AttributeEditorInput) {
                    attributeInput = (AttributeEditorInput) editorInput;
                    ContentTypeAttribute cta = attributeInput.getAttribute();
                    Element attributeNode = attributeMap.get(cta.getName());
                    if (attributeNode == null) {
                        Logger.logConsole("Found no attribute for editor, name: " + cta.getName());
                        Element attributeElement = attributesNode.addElement(cta.getName());
                        attributeElement.clearContent();
                        attributeElement.addCDATA(cta.getValue());
                    } else {
                        System.out.println("Setting value: " + cta.getValue() + " on node: " + cta.getName());
                        attributeNode.clearContent();
                        attributeNode.addCDATA(cta.getValue());
                    }
                }
            }

            // Sort the attributes
            attributes = (List<Element>) attributesNode.elements();
            Collections.sort(attributes, new Comparator<Element>() {
                @Override
                public int compare(Element element1, Element element2) {
                    int index1 = contentAttributes.indexOf(element1);
                    int index2 = contentAttributes.indexOf(element2);

                    if (index1 != -1 && index2 != -1) {
                        return index1 - index2;
                    } else if (index1 == -1 && index2 != -1) {
                        return 1;
                    } else if (index1 != -1 && index2 == -1) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });

            // Re-set the attributes after manipulation and sorting
            attributesNode.setContent(attributes);

            cv.setValue(document.asXML());

            InfoglueCMS.saveLocalXML(input.getContent().getNode(), cv);
            Logger.logConsole((new StringBuilder("Part in doSave:")).append(cv.getValue().substring(113, 200))
                    .toString());
        } catch (Exception e) {
            Logger.logConsole("Error in saveLocal");
            System.out.println("Exception: " + e.getMessage() + ", class: " + e.getClass());
            e.printStackTrace();
        }
    Utils.getMonitor(monitor).worked(100);
    Utils.getMonitor(monitor).done();
    saving = false;
}

From source file:org.jivesoftware.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 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 hierarchy,
    // 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 hierarchy
        // 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<Element> iter = element.elementIterator(childName);
    while (iter.hasNext()) {
        toRemove.add(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<Node> it = childElement.nodeIterator();
            while (it.hasNext()) {
                Node node = it.next();
                if (node instanceof CDATA) {
                    childElement.remove(node);
                    break;
                }
            }
            childElement.addCDATA(value.substring(9, value.length() - 3));
        } else {
            String propValue = StringEscapeUtils.escapeXml(value);
            // check to see if the property is marked as encrypted
            if (JiveGlobals.isPropertyEncrypted(name)) {
                propValue = JiveGlobals.getPropertyEncryptor().encrypt(value);
                childElement.addAttribute(ENCRYPTED_ATTRIBUTE, "true");
            }
            childElement.setText(propValue);
        }
    }
    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:org.jivesoftware.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  .ja v a2  s .c o 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 hierarchy.
    Element element = document.getRootElement();
    for (String aPropName : propName) {
        // If we don't find this part of the property in the XML hierarchy
        // 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 {
        String propValue = StringEscapeUtils.escapeXml(value);
        // check to see if the property is marked as encrypted
        if (JiveGlobals.isPropertyEncrypted(name)) {
            propValue = JiveGlobals.getPropertyEncryptor().encrypt(value);
            element.addAttribute(ENCRYPTED_ATTRIBUTE, "true");
        }
        element.setText(propValue);
    }
    // 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:org.lib.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 .  ja  v a  2s .  com*/
public synchronized void setProperty(String name, String value) {
    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[")) {
        element.addCDATA(value.substring(9, value.length() - 3));
    } else {
        element.setText(value);
    }
    // Write the XML properties to disk
    saveProperties();

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

From source file:org.nuclos.client.datasource.querybuilder.QueryBuilderEditor.java

License:Open Source License

/**
 * @return/*  ww  w  .  j a v a2s  .  c  om*/
 * @throws NuclosBusinessException
 */
public String getXML(DatasourceEntityOptions eOptions) throws CommonBusinessException {
    String result = "";
    try {
        final Document doc = DocumentHelper.createDocument();
        doc.addDocType(QueryBuilderConstants.DOCTYPE, null, QueryBuilderConstants.SYSTEMID);

        Element root = doc.addElement(QueryBuilderConstants.DOCTYPE);
        Element header = root.addElement(QueryBuilderConstants.TAG_HEADER);
        Element tables = root.addElement(QueryBuilderConstants.TAG_TABLES);
        Element connectors = root.addElement(QueryBuilderConstants.TAG_CONNECTORS);
        Element columns = root.addElement(QueryBuilderConstants.TAG_COLUMNS);
        Element parameters = root.addElement(QueryBuilderConstants.TAG_PARAMETERS);
        Element sql = root.addElement(QueryBuilderConstants.TAG_SQL);

        serializeHeader(header);
        serializeTables(tables);
        serializeConnectors(connectors);
        serializeColumns(columns);
        serializeParameters(parameters);

        if (eOptions != null) {
            Element entityoptions = root.addElement(QueryBuilderConstants.TAG_ENTITYOPTIONS);
            entityoptions.addAttribute("dynamic", eOptions.isDynamic() ? "yes" : "no");
        }

        final boolean bModelUsed = parent.isModelUsed();
        sql.addAttribute("isModelUsed", bModelUsed ? "true" : "false");
        if (!bModelUsed) {
            sql.addCDATA(StringUtils.emptyIfNull(parent.getSql()));
        }

        final OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        //format.setEncoding("ISO-8859-1");
        final StringWriter sw = new StringWriter();
        final XMLWriter xmlw = new XMLWriter(sw, format);
        xmlw.write(doc);
        xmlw.close();
        result = sw.toString();
    } catch (IOException ex) {
        throw new NuclosFatalException(ex);
    }
    return result;
}

From source file:org.nuxeo.ecm.core.io.impl.ExportedDocumentImpl.java

License:Apache License

protected void readProperty(Element parent, Namespace targetNs, Field field, Object value, boolean inlineBlobs)
        throws IOException {
    if (value == null) {
        return; // have no content
    }/*from   ww w .  ja va2 s . c om*/
    Type type = field.getType();
    QName name = QName.get(field.getName().getLocalName(), targetNs.prefix, targetNs.uri);
    Element element = parent.addElement(name);

    // extract the element content
    if (type.isSimpleType()) {
        // use CDATA to avoid any bad interaction between content and envelope
        String encodedValue = type.encode(value);
        if (encodedValue != null) {
            // workaround embedded CDATA
            encodedValue = encodedValue.replaceAll("]]>", "]]]]><![CDATA[>");
        }
        element.addCDATA(encodedValue);
    } else if (type.isComplexType()) {
        ComplexType ctype = (ComplexType) type;
        if (TypeConstants.isContentType(ctype)) {
            readBlob(element, ctype, (Blob) value, inlineBlobs);
        } else {
            readComplex(element, ctype, (Map) value, inlineBlobs);
        }
    } else if (type.isListType()) {
        if (value instanceof List) {
            readList(element, (ListType) type, (List) value, inlineBlobs);
        } else if (value.getClass().getComponentType() != null) {
            readList(element, (ListType) type, PrimitiveArrays.toList(value), inlineBlobs);
        } else {
            throw new IllegalArgumentException("A value of list type is neither list neither array: " + value);
        }
    }
}

From source file:org.nuxeo.export.doc.xml.ExportedDocumentAsXMLWithVocLabels.java

License:Open Source License

@Override
protected void readProperty(Element parent, Namespace targetNs, Field field, Object value, boolean inlineBlobs)
        throws IOException {

    // In all cases, first return the field value
    super.readProperty(parent, targetNs, field, value, inlineBlobs);

    // Then, add the label if the field declares it uses a vocabulary
    // by following the expected naming convention
    if (value != null && field.getType().isSimpleType()) {
        String fieldName = field.getName().toString();
        int pos = fieldName.indexOf(kFIELD_TAG_FOR_VOCABULARY);
        if (pos > 0) {
            String vocName = fieldName.substring(pos + kFIELD_TAG_FOR_VOCABULARY.length());
            if (vocName.isEmpty()) {
                log.error("Found tag \"" + kFIELD_TAG_FOR_VOCABULARY + "\" in field name " + fieldName
                        + ", but no vocabulary label afetr the tag");
            } else {
                String fieldValue = value.toString();
                org.nuxeo.ecm.directory.Session session = null;
                try {
                    session = getDirService().open(vocName);
                    if (session == null) { // Vocabulary not found
                        log.error("Vocabulary '" + vocName + "' not found");
                    } else {
                        DocumentModel directoryDoc = session.getEntry(fieldValue);
                        if (directoryDoc == null) {
                            log.error("Entry id <" + fieldValue + "> not found in vocabulary " + vocName);
                        } else {
                            DataModel dm = directoryDoc.getDataModels().values().iterator().next();
                            String label = (String) dm.getData("label");

                            QName name = QName.get(field.getName().getLocalName() + kFIELD_EXTENSION_FOR_XML,
                                    targetNs.prefix, targetNs.uri);
                            Element element = parent.addElement(name);
                            element.addCDATA(label);// Should be encoded?
                        }//w  ww  .  j  a  v  a 2  s. c  om
                    }

                } catch (Exception e) {
                    log.error(e);
                } finally {
                    if (session != null) {
                        try {
                            session.close();
                        } catch (DirectoryException e) {
                            // We ignore this one
                        }
                    }
                }
            }
        }
    }
}

From source file:org.olat.ims.qti.editor.beecom.objects.FIBQuestion.java

License:Apache License

/**
 * Build mastery respcondition for FIB in all-banks-must-be-correct mode. Adds one respcondition in which all blanks must be answered correctly. This respcondition
 * uses the mastery feedback.// ww  w  . j  a v a  2s  .co m
 * 
 * @param resprocessingXML
 */
private void buildRespconditionFIBSingle(final Element resprocessingXML) {
    final Element correct = resprocessingXML.addElement("respcondition");
    correct.addAttribute("title", "Mastery");
    correct.addAttribute("continue", "Yes");

    final Element conditionvar = correct.addElement("conditionvar");
    final Element and = conditionvar.addElement("and");
    for (final Iterator i = getResponses().iterator(); i.hasNext();) {
        final FIBResponse fib = (FIBResponse) i.next();
        if (fib.getType().equals(FIBResponse.TYPE_BLANK)) {
            final String[] correctFIBs = fib.getCorrectBlank().split(";");
            final Element or = and.addElement("or");
            for (int j = 0; j < correctFIBs.length; j++) {
                final Element varequal = or.addElement("varequal");
                varequal.addAttribute("respident", fib.getIdent());
                varequal.addAttribute("case", fib.getCaseSensitive());
                if (correctFIBs[j].length() > 0) {
                    varequal.addCDATA(correctFIBs[j]);
                }
            }
        }
    }

    final Element setvar = correct.addElement("setvar");
    setvar.addAttribute("varname", "SCORE");
    setvar.addAttribute("action", "Set");
    setvar.setText("" + getSingleCorrectScore());

    // Use mastery feedback
    QTIEditHelper.addFeedbackMastery(correct);

    // remove whole respcondition if empty
    if (and.element("or") == null) {
        resprocessingXML.remove(correct);
    }
}

From source file:org.olat.ims.qti.editor.beecom.objects.FIBQuestion.java

License:Apache License

/**
 * Build mastery respconditions for FIB in points-per-blank mode. Adds respconditions for every single blank and a respcondition in case of all blanks answered
 * correctly that uses the mastery feedback.
 * /*w w  w  . ja  v  a  2s .  c  o  m*/
 * @param resprocessingXML
 */
private void buildRespconditionFIBMulti(final Element resprocessingXML) {
    for (final Iterator i = getResponses().iterator(); i.hasNext();) {
        final FIBResponse fib = (FIBResponse) i.next();
        if (!fib.getType().equals(FIBResponse.TYPE_BLANK)) {
            continue;
        }
        final float points = fib.getPoints();
        if (points == 0) {
            continue;
        }

        final Element correct = resprocessingXML.addElement("respcondition");
        correct.addAttribute("continue", "Yes");
        if (points > 0) {
            correct.addAttribute("title", "Mastery");
        } else {
            // doesn't make much sense, but maybe the user has some fancy
            // ideas...
            correct.addAttribute("title", "Fail");
        }

        final Element or = correct.addElement("conditionvar").addElement("or");
        final String[] correctFIBs = fib.getCorrectBlank().split(";");
        for (int j = 0; j < correctFIBs.length; j++) {
            final Element varequal = or.addElement("varequal");
            varequal.addAttribute("respident", fib.getIdent());
            varequal.addAttribute("case", fib.getCaseSensitive());
            if (correctFIBs[j].length() > 0) {
                varequal.addCDATA(correctFIBs[j]);
            }
        }
        final Element setvar = correct.addElement("setvar");
        setvar.addAttribute("varname", "SCORE");
        setvar.addAttribute("action", "Add");
        setvar.setText("" + points);
    }

    // Resp condition for feedback mastery:
    // all response with points>0 must be selected
    final Element respcondition_correct = resprocessingXML.addElement("respcondition");
    respcondition_correct.addAttribute("title", "Mastery");
    respcondition_correct.addAttribute("continue", "Yes");
    final Element conditionvar = respcondition_correct.addElement("conditionvar");
    final Element and = conditionvar.addElement("and");

    for (final Iterator i = getResponses().iterator(); i.hasNext();) {
        final FIBResponse tmpResponse = (FIBResponse) i.next();
        if (!tmpResponse.getType().equals(FIBResponse.TYPE_BLANK)) {
            continue;
        }
        final String[] correctFIBs = tmpResponse.getCorrectBlank().split(";");
        final Element or = and.addElement("or");
        for (int j = 0; j < correctFIBs.length; j++) {
            final Element varequal = or.addElement("varequal");
            varequal.addAttribute("respident", tmpResponse.getIdent());
            varequal.addAttribute("case", tmpResponse.getCaseSensitive());
            if (correctFIBs[j].length() > 0) {
                varequal.addCDATA(correctFIBs[j]);
            }
        } // for loop
    } // for loop

    // Use mastery feedback
    QTIEditHelper.addFeedbackMastery(respcondition_correct);

    // remove whole respcondition if empty
    if (and.element("or") == null) {
        resprocessingXML.remove(respcondition_correct);
    }
}