Example usage for org.dom4j Attribute setValue

List of usage examples for org.dom4j Attribute setValue

Introduction

In this page you can find the example usage for org.dom4j Attribute setValue.

Prototype

void setValue(String value);

Source Link

Document

Sets the value of this attribute or this method will throw an UnsupportedOperationException if it is read-only.

Usage

From source file:org.opencms.setup.xml.CmsSetupXmlHelper.java

License:Open Source License

/**
 * Replaces a attibute's value in the given node addressed by the xPath.<p>
 * /*  w w w.  j a  v  a  2  s .  c  o m*/
 * @param document the document to replace the node attribute
 * @param xPath the xPath to the node
 * @param attribute the attribute to replace the value of
 * @param value the new value to set
 * 
 * @return <code>true</code> if successful <code>false</code> otherwise
 */
public static boolean setAttribute(Document document, String xPath, String attribute, String value) {

    Node node = document.selectSingleNode(xPath);
    Element e = (Element) node;
    @SuppressWarnings("unchecked")
    List<Attribute> attributes = e.attributes();
    for (Attribute a : attributes) {
        if (a.getName().equals(attribute)) {
            a.setValue(value);
            return true;
        }
    }
    return false;
}

From source file:org.opencms.setup.xml.v8.CmsXmlAddSolrSearch.java

License:Open Source License

/**
 * @see org.opencms.setup.xml.CmsXmlUpdateAction#executeUpdate(org.dom4j.Document, java.lang.String, boolean)
 *//*www . ja  v a 2  s .c  o  m*/
@SuppressWarnings("unchecked")
@Override
public boolean executeUpdate(Document doc, String xpath, boolean forReal) {

    Element node = (Element) doc.selectSingleNode("/opencms/search");
    if (node.selectSingleNode("solr") == null) {
        String solrComment = " To enable Solr in OpenCms you must create a solr/ home\n"
                + "           directory in the WEB-INF folder of your OpenCms application.\n"
                + "           Copy the solr/ folder from the OpenCms standard distribution\n"
                + "           as a starting point for your configuration. ";
        try {
            Element solrElement = createElementFromXml("<solr enabled=\"false\"></solr>");
            solrElement.addComment(solrComment);
            node.elements().add(0, solrElement);
        } catch (DocumentException e) {
            System.out.println("Could not add solr node");
            return false;
        }
    } else {
        String solrComment = "\n"
                + "           During the update Solr will be disabled in the WEB-INF/config/opencms-search.xml.\n"
                + "           To update Solr you must update the 'schema.xml and' the 'solrconfig.xml' manually.\n"
                + "           The new default configuration files are located in the solr-update/ directory in\n"
                + "           the WEB-INF folder of your application. If you are using the default configuration\n"
                + "           from the distribution, it is sufficient to copy the new configuration files to the\n"
                + "           WEB-INF/solr folder. Else if you have customized the Solr configuration you might\n"
                + "           want to merge the 'schema.xml' and the 'solrconfig.xml' first. When you are done\n"
                + "           set the attribute enabled to 'true' again.\n";
        Element solrElement = (Element) node.selectSingleNode("solr");
        Attribute a = solrElement.attribute("enabled");
        if (a != null) {
            a.setValue("false");
        }
        solrElement.addComment(solrComment);
    }

    try {

        tryToAddMissingElement(doc, "//index[name='Solr Offline']", "//indexes",
                "<index class=\"org.opencms.search.solr.CmsSolrIndex\">\n"
                        + "                <name>Solr Offline</name>\n"
                        + "                <rebuild>offline</rebuild>\n"
                        + "                <project>Offline</project>\n"
                        + "                <locale>all</locale>\n"
                        + "                <configuration>solr_fields</configuration>\n"
                        + "                <sources>\n" + "                    <source>solr_source</source>\n"
                        + "                </sources>\n"
                        + "                <param name=\"search.solr.postProcessor\">org.opencms.search.solr.CmsSolrLinkProcessor</param>\n"
                        + "            </index>");

        tryToAddMissingElement(doc, "//index[name='Solr Online']", "//indexes",
                "<index class=\"org.opencms.search.solr.CmsSolrIndex\">\n"
                        + "                <name>Solr Online</name>\n"
                        + "                <rebuild>auto</rebuild>\n"
                        + "                <project>Online</project>\n"
                        + "                <locale>all</locale>\n"
                        + "                <configuration>solr_fields</configuration>\n"
                        + "                <sources>\n" + "                    <source>solr_source</source>\n"
                        + "                </sources>\n"
                        + "                <param name=\"search.solr.postProcessor\">org.opencms.search.solr.CmsSolrLinkProcessor</param>\n"
                        + "            </index>");

        Element solrSource = (Element) (doc.selectSingleNode("//indexsource[name='solr_source']"));
        // will be added again in next step
        if (solrSource != null) {
            solrSource.detach();
        }

        tryToAddMissingElement(doc, "//indexsource[name='solr_source']", "//indexsources",
                "<indexsource>\n" + "                <name>solr_source</name>\n"
                        + "                <indexer class=\"org.opencms.search.CmsVfsIndexer\" />\n"
                        + "                <resources>\n" + "                    <resource>/</resource>\n"
                        + "                </resources>\n" + "                <documenttypes-indexed>\n"
                        + "                    <name>xmlcontent-solr</name>\n"
                        + "                    <name>containerpage-solr</name>\n"
                        + "                    <name>xmlpage</name>\n"
                        + "                    <name>text</name>\n" + "                    <name>jsp</name>\n"
                        + "                    <name>pdf</name>\n" + "                    <name>rtf</name>\n"
                        + "                    <name>html</name>\n" + "                    <name>image</name>\n"
                        + "                    <name>generic</name>\n"
                        + "                    <name>msoffice-ole2</name>\n"
                        + "                    <name>msoffice-ooxml</name>\n"
                        + "                    <name>openoffice</name>\n"
                        + "                </documenttypes-indexed>\n" + "            </indexsource>");

        tryToAddMissingElement(doc, "//fieldconfiguration[name='solr_fields']", "//fieldconfigurations",
                "<fieldconfiguration class=\"org.opencms.search.solr.CmsSolrFieldConfiguration\">\n"
                        + "                <name>solr_fields</name>\n"
                        + "                <description>The Solr search index field configuration.</description>\n"
                        + "                <fields />\n" + "            </fieldconfiguration>");

        tryToAddMissingElement(doc, "//documenttype[name='xmlcontent-solr']", "//documenttypes",
                "<documenttype>\n" + "                <name>xmlcontent-solr</name>\n"
                        + "                <class>org.opencms.search.solr.CmsSolrDocumentXmlContent</class>\n"
                        + "                <mimetypes>\n"
                        + "                    <mimetype>text/html</mimetype>\n"
                        + "                </mimetypes>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>xmlcontent-solr</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype>");

        tryToAddMissingElement(doc, "//documenttype[name='containerpage-solr']", "//documenttypes",
                "<documenttype>\n" + "                <name>containerpage-solr</name>\n"
                        + "                <class>org.opencms.search.solr.CmsSolrDocumentContainerPage</class>\n"
                        + "                <mimetypes>\n"
                        + "                    <mimetype>text/html</mimetype>\n"
                        + "                </mimetypes>\n" + "                <resourcetypes>\n"
                        + "                    <resourcetype>containerpage-solr</resourcetype>\n"
                        + "                </resourcetypes>\n" + "            </documenttype>");

    } catch (DocumentException e) {
        e.printStackTrace();
    }

    return true;
}

From source file:org.opencms.xml.A_CmsXmlDocument.java

License:Open Source License

/**
 * Corrects the structure of this XML document.<p>
 * //  w  ww. jav  a  2s  .  c o  m
 * @param cms the current OpenCms user context
 * 
 * @return the file that contains the corrected XML structure
 * 
 * @throws CmsXmlException if something goes wrong
 */
public CmsFile correctXmlStructure(CmsObject cms) throws CmsXmlException {

    // apply XSD schema translation
    Attribute schema = m_document.getRootElement()
            .attribute(I_CmsXmlSchemaType.XSI_NAMESPACE_ATTRIBUTE_NO_SCHEMA_LOCATION);
    if (schema != null) {
        String schemaLocation = schema.getValue();
        String translatedSchema = OpenCms.getResourceManager().getXsdTranslator()
                .translateResource(schemaLocation);
        if (!schemaLocation.equals(translatedSchema)) {
            schema.setValue(translatedSchema);
        }
    }

    // iterate over all locales
    Iterator<Locale> i = m_locales.iterator();
    while (i.hasNext()) {
        Locale locale = i.next();
        List<String> names = getNames(locale);
        List<I_CmsXmlContentValue> validValues = new ArrayList<I_CmsXmlContentValue>();

        // iterate over all nodes per language
        Iterator<String> j = names.iterator();
        while (j.hasNext()) {

            // this step is required for values that need a processing of their content
            // an example for this is the HTML value that does link replacement                
            String name = j.next();
            I_CmsXmlContentValue value = getValue(name, locale);
            if (value.isSimpleType()) {
                String content = value.getStringValue(cms);
                value.setStringValue(cms, content);
            }

            // save valid elements for later check
            validValues.add(value);
        }

        if (isAutoCorrectionEnabled()) {
            // full correction of XML

            List<Element> roots = new ArrayList<Element>();
            List<CmsXmlContentDefinition> rootCds = new ArrayList<CmsXmlContentDefinition>();
            List<Element> validElements = new ArrayList<Element>();

            // gather all XML content definitions and their parent nodes                                
            Iterator<I_CmsXmlContentValue> it = validValues.iterator();
            while (it.hasNext()) {
                // collect all root elements, also for the nested content definitions
                I_CmsXmlContentValue value = it.next();
                Element element = value.getElement();
                validElements.add(element);
                if (element.supportsParent()) {
                    // get the parent XML node
                    Element root = element.getParent();
                    if ((root != null) && !roots.contains(root)) {
                        // this is a parent node we do not have already in our storage
                        CmsXmlContentDefinition rcd = value.getContentDefinition();
                        if (rcd != null) {
                            // this value has a valid XML content definition
                            roots.add(root);
                            rootCds.add(rcd);
                        } else {
                            // no valid content definition for the XML value
                            throw new CmsXmlException(
                                    Messages.get().container(Messages.ERR_CORRECT_NO_CONTENT_DEF_3,
                                            value.getName(), value.getTypeName(), value.getPath()));
                        }
                    }
                }
            }

            for (int le = 0; le < roots.size(); le++) {
                // iterate all XML content root nodes and correct each XML subtree

                Element root = roots.get(le);
                CmsXmlContentDefinition cd = rootCds.get(le);

                // step 1: first sort the nodes according to the schema, this takes care of re-ordered elements
                List<List<Element>> nodeLists = new ArrayList<List<Element>>();
                for (I_CmsXmlSchemaType type : cd.getTypeSequence()) {
                    List<Element> elements = CmsXmlGenericWrapper.elements(root, type.getName());
                    int maxOccures = cd.getChoiceMaxOccurs() > 0 ? cd.getChoiceMaxOccurs()
                            : type.getMaxOccurs();
                    if (elements.size() > maxOccures) {
                        // to many nodes of this type appear according to the current schema definition
                        for (int lo = (elements.size() - 1); lo >= type.getMaxOccurs(); lo--) {
                            elements.remove(lo);
                        }
                    }
                    nodeLists.add(elements);
                }

                // step 2: clear the list of nodes (this will remove all invalid nodes)
                List<Element> nodeList = CmsXmlGenericWrapper.elements(root);
                nodeList.clear();
                Iterator<List<Element>> in = nodeLists.iterator();
                while (in.hasNext()) {
                    // now add all valid nodes in the right order
                    List<Element> elements = in.next();
                    nodeList.addAll(elements);
                }

                // step 3: now append the missing elements according to the XML content definition
                cd.addDefaultXml(cms, this, root, locale);
            }
        }
    }

    // write the modified XML back to the VFS file 
    if (m_file != null) {
        // make sure the file object is available
        m_file.setContents(marshal());
    }
    return m_file;
}

From source file:org.opencms.xml.page.CmsXmlPage.java

License:Open Source License

/**
 * Sets the enabled flag of an already existing element.<p>
 * //  ww w  .j  a v  a  2 s .co  m
 * Note: if isEnabled is set to true, the attribute is removed
 * since true is the default
 * 
 * @param name name name of the element
 * @param locale locale of the element
 * @param isEnabled enabled flag for the element
 */
public void setEnabled(String name, Locale locale, boolean isEnabled) {

    CmsXmlHtmlValue value = (CmsXmlHtmlValue) getValue(name, locale);
    Element element = value.getElement();
    Attribute enabled = element.attribute(ATTRIBUTE_ENABLED);

    if (enabled == null) {
        if (!isEnabled) {
            element.addAttribute(ATTRIBUTE_ENABLED, Boolean.toString(isEnabled));
        }
    } else if (isEnabled) {
        element.remove(enabled);
    } else {
        enabled.setValue(Boolean.toString(isEnabled));
    }
}

From source file:org.orbeon.oxf.processor.tamino.dom4j.TDOM4JAdapter.java

License:Open Source License

/**
 * Sets the ino:docname on this DOM4J specific TXMLObject.
 *
 * @param docname is the ino:docname attribute of the data object.
 */// w  w w .j  a  v a 2  s. c  o m
public void setDocname(String docname) {
    if (docname == null || docname.equals("")) {
        if (element == null)
            super.setDocname(null);
        else {
            QName qname = new QName(TInoNamespace.DOCNAME.getName(), inoNamespace);
            Attribute att = new FlyweightAttribute(qname);
            element.remove(att);
        }
    } else {
        if (element == null)
            super.setDocname(docname);
        else {
            QName qname = new QName(TInoNamespace.DOCNAME.getName(), inoNamespace);
            Attribute att = element.attribute(qname);
            if (att != null)
                att.setValue(docname);
            else {
                att = new FlyweightAttribute(TInoNamespace.DOCNAME.getName(), docname, inoNamespace);
                element.add(att);
            }
        }
    }
}

From source file:org.orbeon.oxf.processor.tamino.dom4j.TDOM4JAdapter.java

License:Open Source License

/**
 * Sets the ino:id for the XML instance.
 *///from  w  ww.  j  a  v  a  2  s  .c  o  m
public void setId(String inoId) {
    if (inoId == null || inoId.length() == 0) {
        if (element == null)
            super.setId(null);
        else {
            QName qtmpName = new QName(TInoNamespace.ID.getName(), inoNamespace);
            Attribute tmpAttribute = new FlyweightAttribute(qtmpName);
            element.remove(tmpAttribute);
        }
    } else {
        if (element == null)
            super.setId(inoId);
        else {
            QName qname = new QName(TInoNamespace.ID.getName(), inoNamespace);
            Attribute att = element.attribute(qname);
            if (att != null)
                att.setValue(inoId);
            else {
                att = new FlyweightAttribute(TInoNamespace.ID.getName(), inoId, inoNamespace);
                element.add(att);
            }
        }
    }
}

From source file:org.orbeon.oxf.transformer.xupdate.statement.Utils.java

License:Open Source License

/**
 * Evaluate a sequence a statements, and insert the result of the
 * evaluation the given parent node at the given position.
 *//* ww  w  . ja  v a 2 s  . c  o  m*/
public static void insert(LocationData locationData, Node parent, int position, Object toInsert) {
    List nodesToInsert = xpathObjectToDOM4JList(locationData, toInsert);
    if (parent instanceof Element)
        Collections.reverse(nodesToInsert);
    for (Iterator j = nodesToInsert.iterator(); j.hasNext();) {
        Object object = j.next();
        Node node = object instanceof String || object instanceof Number
                ? Dom4jUtils.createText(object.toString())
                : (Node) ((Node) object).clone();
        if (parent instanceof Element) {
            Element element = (Element) parent;
            if (node instanceof Attribute) {
                element.attributes().add(node);
            } else {
                element.content().add(position, node);
            }
        } else if (parent instanceof Attribute) {
            Attribute attribute = (Attribute) parent;
            attribute.setValue(attribute.getValue() + node.getText());
        } else if (parent instanceof Document) {
            // Update a document element
            final Document document = (Document) parent;
            if (node instanceof Element) {
                if (document.getRootElement() != null)
                    throw new ValidationException("Document already has a root element", locationData);
                document.setRootElement((Element) node);
            } else if (node instanceof ProcessingInstruction) {
                document.add(node);
            } else {
                throw new ValidationException(
                        "Only an element or processing instruction can be at the root of a document",
                        locationData);
            }

        } else {
            throw new ValidationException("Cannot insert into a node of type '" + parent.getClass() + "'",
                    locationData);
        }
    }
}

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

License:Open Source License

/**
 * Set the name of the parameter that is being looped on.
 * //from www.j a v a  2  s  .c o  m
 * @param loopOn
 *          the parameter name. If null the loop parameter is removed.
 */
public void setLoopOn(String loopOn) {
    Attribute attr = controlElement.attribute(ActionSequenceDocument.LOOP_ON_NAME);
    if (loopOn == null) {
        if (attr != null) {
            attr.detach();
            ActionSequenceDocument.fireControlStatementChanged(this);
        }
    } else {
        loopOn = loopOn.trim();
        if (attr == null) {
            controlElement.addAttribute(ActionSequenceDocument.LOOP_ON_NAME, loopOn);
            attr = controlElement.attribute(ActionSequenceDocument.LOOP_ON_NAME);
            ActionSequenceDocument.fireControlStatementChanged(this);
        } else if (!loopOn.equals(attr.getValue())) {
            attr.setValue(loopOn);
            ActionSequenceDocument.fireControlStatementChanged(this);
        }
    }
}

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

License:Open Source License

public void setLoopUsingPeek(Boolean usePeek) {

    Attribute attr = controlElement.attribute(ActionSequenceDocument.PEEK_ONLY_NAME);
    if (usePeek == null) {
        if (attr != null) {
            attr.detach();/*w  w  w  .  ja  va 2 s . c  o  m*/
            ActionSequenceDocument.fireControlStatementChanged(this);
        }
    } else {
        if (attr == null) {
            controlElement.addAttribute(ActionSequenceDocument.PEEK_ONLY_NAME, usePeek.toString());
            attr = controlElement.attribute(ActionSequenceDocument.PEEK_ONLY_NAME);
            ActionSequenceDocument.fireControlStatementChanged(this);
        } else if (!usePeek.toString().equals(attr.getValue())) {
            attr.setValue(usePeek.toString());
            ActionSequenceDocument.fireControlStatementChanged(this);
        }
    }
}

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

License:Open Source License

public void setOutputParameter(boolean isOutputParameter) {
    List<Attribute> attribs = ioElement.attributes();
    for (Attribute attrib : attribs) {
        if (attrib.getName().equals(IS_OUTPUT_PARAM_ATTR)) {
            attrib.setValue(Boolean.toString(isOutputParameter));
            ActionSequenceDocument.fireIoChanged(this);
            return;
        }//  w w w  . j  av a 2 s  .co m
    }
    // not found, create new
    ioElement.addAttribute(IS_OUTPUT_PARAM_ATTR, Boolean.toString(isOutputParameter));
    ActionSequenceDocument.fireIoChanged(this);
}