Example usage for org.dom4j Element addElement

List of usage examples for org.dom4j Element addElement

Introduction

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

Prototype

Element addElement(String name);

Source Link

Document

Adds a new Element node with the given name to this branch and returns a reference to the new node.

Usage

From source file:architecture.common.lifecycle.internal.XmlApplicationPropertiesOld.java

License:Apache License

public synchronized void putAll(Map<? extends String, ? extends String> m) {
    for (Entry e : m.entrySet()) {
        String propertyName = (String) e.getKey();
        String propertyValue = (String) e.getValue();
        String propName[] = parsePropertyName(propertyName);
        Element element = doc.getRootElement();
        for (String p : propName) {
            if (element.element(p) == null)
                element.addElement(p);
            element = element.element(p);
        }//from w  w  w. ja va2s. c  o m
        if (propertyValue != null)
            element.setText(propertyValue);
    }
    saveProperties();
}

From source file:architecture.common.xml.XmlProperties.java

License:Apache 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://from   ww  w  . ja va 2 s  . c  om
 * 
 * <pre>
 * &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:architecture.common.xml.XmlProperties.java

License:Apache License

/**
 * Sets the value of the specified property. If the property doesn't
 * currently exist, it will be automatically created.
 *
 * @param name/*from   w  w w  . ja v  a2 s. c  om*/
 *            the name of the property to set.
 * @param value
 *            the new value for the property.
 */
public synchronized void setProperty(String name, String value) {
    if (!StringEscapeUtils.escapeXml(name).equals(name)) {
        throw new IllegalArgumentException(L10NUtils.getMessage("002155"));
    }
    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:architecture.ee.component.core.lifecycle.RepositoryImpl.java

License:Apache License

public ApplicationProperties getSetupApplicationProperties() {
    if (setupProperties == null) {
        try {/*from w  w w. j a va2 s  . co m*/
            File file = getFile(ApplicationConstants.DEFAULT_STARTUP_FILENAME);
            if (!file.exists()) {
                boolean error = false;
                // create default file...
                log.debug("No startup file now create !!!");
                Writer writer = null;
                try {

                    writer = new OutputStreamWriter(new FileOutputStream(file),
                            ApplicationConstants.DEFAULT_CHAR_ENCODING);
                    XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint());
                    StringBuilder sb = new StringBuilder();
                    org.dom4j.Document document = org.dom4j.DocumentHelper.createDocument();
                    org.dom4j.Element root = document.addElement("startup-config");
                    // setup start
                    // ------------------------------------------------------------
                    org.dom4j.Element setupNode = root.addElement("setup");
                    setupNode.addElement("complete").setText("false");
                    // setup end
                    // --------------------------------------------------------------
                    // license start
                    org.dom4j.Element licenseNode = root.addElement("license");
                    // license end
                    // view start
                    org.dom4j.Element viewNode = root.addElement("view");
                    org.dom4j.Element renderNode = viewNode.addElement("render");
                    org.dom4j.Element freemarkerNode = renderNode.addElement("freemarker");
                    freemarkerNode.addElement("enabled").setText("true");
                    freemarkerNode.addElement("source").addElement("location");
                    org.dom4j.Element velocityNode = renderNode.addElement("velocity");
                    velocityNode.addElement("enabled").setText("false");
                    // view end
                    // security start
                    org.dom4j.Element securityNode = root.addElement("security");
                    securityNode.addElement("authentication").addElement("encoding").addElement("algorithm")
                            .setText("SHA-256");
                    // security end

                    // scripting start
                    org.dom4j.Element scriptingNode = root.addElement("scripting");
                    org.dom4j.Element groovyNode = scriptingNode.addElement("groovy");
                    groovyNode.addElement("debug").setText("false");
                    org.dom4j.Element sourceGroovyNode = groovyNode.addElement("source");
                    sourceGroovyNode.addElement("location");
                    sourceGroovyNode.addElement("encoding").setText(ApplicationConstants.DEFAULT_CHAR_ENCODING);
                    sourceGroovyNode.addElement("recompile").setText("true");
                    // scripting end
                    // database start
                    org.dom4j.Element databaseNode = root.addElement("database");
                    // database end
                    xmlWriter.write(document);
                } catch (Exception e) {
                    log.error(L10NUtils.format("003007", file.getName(), e.getMessage()));
                    error = true;
                } finally {
                    try {
                        writer.flush();
                        writer.close();
                    } catch (Exception e) {
                        log.error(e);
                        error = true;
                    }
                }
            }
            this.setupProperties = new XmlApplicationProperties(file);
        } catch (Exception e) {
            log.warn("I warning you!");
            log.debug(e.getMessage(), e);
            return EmptyApplicationProperties.getInstance();
        }
    }
    return setupProperties;
}

From source file:architecture.ee.component.RepositoryImpl.java

License:Apache License

public ApplicationProperties getSetupApplicationProperties() {
    if (setupProperties == null) {
        if (initailized.get()) {

            File file = getFile(ApplicationConstants.DEFAULT_STARTUP_FILENAME);

            if (!file.exists()) {
                boolean error = false;
                // create default file...
                log.debug(CommonLogLocalizer.format("003012", file.getAbsolutePath()));
                Writer writer = null;
                try {

                    lock.lock();/*  w  w w. j  a va 2  s . co  m*/

                    writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
                    XMLWriter xmlWriter = new XMLWriter(writer, OutputFormat.createPrettyPrint());
                    StringBuilder sb = new StringBuilder();

                    org.dom4j.Document document = org.dom4j.DocumentHelper.createDocument();
                    org.dom4j.Element root = document.addElement("startup-config");
                    // setup start
                    // ------------------------------------------------------------
                    org.dom4j.Element setupNode = root.addElement("setup");
                    setupNode.addElement("complete").setText("false");
                    // setup end

                    // license start
                    root.addComment("LICENSE SETTING");
                    org.dom4j.Element licenseNode = root.addElement("license");
                    // license end

                    // view start
                    /*
                    org.dom4j.Element viewNode = root.addElement("view");
                    org.dom4j.Element renderNode = viewNode.addElement("render");
                    org.dom4j.Element freemarkerNode = renderNode.addElement("freemarker");
                    freemarkerNode.addElement("enabled").setText("true");
                    freemarkerNode.addElement("source").addElement("location");
                    org.dom4j.Element velocityNode = renderNode.addElement("velocity");
                    velocityNode.addElement("enabled").setText("false");
                    */
                    // view end

                    // security start         
                    root.addComment("SECURITY SETTING");
                    org.dom4j.Element securityNode = root.addElement("security");
                    org.dom4j.Element encrpptNode = securityNode.addElement("encrypt");
                    encrpptNode.addElement("algorithm").setText("Blowfish");
                    encrpptNode.addElement("key").addElement("current");
                    org.dom4j.Element encrpptPropertyNode = encrpptNode.addElement("property");
                    encrpptPropertyNode.addElement("name").setText("username");
                    encrpptPropertyNode.addElement("name").setText("password");
                    securityNode.addElement("authentication").addElement("encoding").addElement("algorithm")
                            .setText("SHA-256");
                    // security end
                    // services start
                    root.addComment("SERVICES SETTING");
                    org.dom4j.Element servicesNode = root.addElement("services");
                    servicesNode.addElement("sql").addElement("location").addText("sql");
                    // services end

                    // database start
                    root.addComment("DATABASE SETTING");
                    org.dom4j.Element databaseNode = root.addElement("database");
                    org.dom4j.Element databaseDefaultNode = databaseNode.addElement("default");
                    databaseDefaultNode.addComment(" 1. jndi datasource ");
                    databaseDefaultNode.addComment((new StringBuilder()).append("\n").append("      ")
                            .append("<jndiDataSourceProvider>").append("\n").append("      ")
                            .append("   <jndiName></jndiName>").append("\n").append("      ")
                            .append("</jndiDataSourceProvider>").append("\n").toString());
                    databaseDefaultNode.addComment(" 2. connection pool datasource using dbcp ");
                    databaseDefaultNode.addComment((new StringBuilder()).append("\n").append("      ")
                            .append("<pooledDataSourceProvider> ").append("\n").append("      ")
                            .append("    <driverClassName></driverClassName> ").append("\n").append("      ")
                            .append("    <url></url>").append("\n").append("      ")
                            .append("    <username></username>").append("\n").append("      ")
                            .append("    <password></password>").append("\n").append("      ")
                            .append("    <connectionProperties>").append("\n").append("      ")
                            .append("        <initialSize>1</initialSize>").append("\n").append("      ")
                            .append("        <maxActive>8</maxActive>").append("\n").append("      ")
                            .append("        <maxIdle>8</maxIdle>").append("\n").append("      ")
                            .append("        <maxWait>-1</maxWait>").append("\n").append("      ")
                            .append("        <minIdle>0</minIdle>").append("\n").append("      ")
                            .append("        <testOnBorrow>true</testOnBorrow>").append("\n").append("      ")
                            .append("        <testOnReturn>false</testOnReturn>").append("\n").append("      ")
                            .append("        <testWhileIdle>false</testWhileIdle>").append("\n")
                            .append("      ")
                            .append("        <validationQuery>select 1 from dual</validationQuery>")
                            .append("\n").append("      ").append("    </connectionProperties>").append("\n")
                            .append("      ").append("</pooledDataSourceProvider>").toString());
                    // database end
                    xmlWriter.write(document);
                } catch (Exception e) {
                    log.error("fail to making {} - {}", file.getName(), e.getMessage());
                    error = true;
                } finally {

                    try {
                        writer.flush();
                        writer.close();
                    } catch (Exception e) {
                        log.error("error", e);
                        error = true;
                    }
                    lock.unlock();
                }
            } else {
                try {
                    log.debug(CommonLogLocalizer.format("003011", file.getPath()));
                    this.setupProperties = new LocalApplicationProperties(file);
                } catch (IOException e) {
                    log.error(CommonLogLocalizer.getMessage("003013"), e);
                }
            }
        } else {
            return LocalApplicationProperties.EMPTY_APPLICATION_PROPERTIES;
        }
    }
    return setupProperties;
}

From source file:architecture.ee.util.xml.XmlProperties.java

License:Apache 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://from   www . ja  v  a 2s.  c o  m
 * 
 * <pre>
 * &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(XmlEscapers.xmlContentEscaper().escape(value));// 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:architecture.ee.util.xml.XmlProperties.java

License:Apache License

/**
 * Sets the value of the specified property. If the property doesn't
 * currently exist, it will be automatically created.
 *
 * @param name/* ww  w . j  a v a 2 s . com*/
 *            the name of the property to set.
 * @param value
 *            the new value for the property.
 */
public synchronized void setProperty(String name, String value) {

    if (!XmlEscapers.xmlContentEscaper().escape(name).equals(name)) {
        throw new IllegalArgumentException();// L10NUtils.getMessage("002155"));
    }
    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:bio.pih.genoogle.io.Output.java

/**
 * @param searchResults//from  w  w  w  .ja va 2  s  . co  m
 * 
 * @return {@link Document} containing the {@link SearchResults} in XML form.
 */
public static Document genoogleOutputToXML(List<SearchResults> searchResults) {
    assert searchResults != null;
    DocumentFactory factory = DocumentFactory.getInstance();

    Document doc = factory.createDocument();
    doc.setName("genoogle");

    Element output = doc.addElement(Genoogle.SOFTWARE_NAME);
    output.addAttribute("version", Genoogle.VERSION.toString());
    output.addAttribute("copyright", Genoogle.COPYRIGHT);

    Element iterationsElement = output.addElement("iterations");
    for (int i = 0; i < searchResults.size(); i++) {
        SearchResults searchResult = searchResults.get(i);

        Element iterationElement = iterationsElement.addElement("iteration");
        iterationElement.addAttribute("number", String.valueOf(i));

        SymbolList query = searchResult.getParams().getQuery();
        if (query instanceof RichSequence) {
            iterationElement.addAttribute("query", ((RichSequence) query).getHeader());
        }

        iterationElement.add(searchResultToXML(searchResult));
    }

    return doc;
}

From source file:bio.pih.genoogle.io.Output.java

public static Element genoogleXmlHeader() {
    DocumentFactory factory = DocumentFactory.getInstance();

    Document doc = factory.createDocument();
    doc.setName("genoogle");

    Map<String, String> xslProcessing = Maps.newHashMap();
    xslProcessing.put("type", "text/xsl");
    xslProcessing.put("href", "results.xsl");
    ProcessingInstruction xsltInstruction = DocumentHelper.createProcessingInstruction("xml-stylesheet",
            xslProcessing);/*  w  w  w.  jav a 2s .c  o m*/
    doc.add(xsltInstruction);

    Element output = doc.addElement("genoogle");
    output.addElement("references").addAttribute("program", Genoogle.SOFTWARE_NAME)
            .addAttribute("version", Double.toString(Genoogle.VERSION))
            .addAttribute("copyright", Genoogle.COPYRIGHT);
    return output;
}

From source file:bio.pih.genoogle.io.Output.java

/**
 * @param hsp//from w ww .j  a v a2 s.co  m
 * @return {@link Element} containing the {@link HSP} at XML form.
 */
public static Element hspToXML(HSP hsp) {
    assert hsp != null;
    DocumentFactory factory = DocumentFactory.getInstance();

    Element hspElement = factory.createElement("hsp");
    hspElement.addAttribute("score", Integer.toString((int) hsp.getScore()));
    hspElement.addAttribute("normalized-score", Integer.toString((int) hsp.getNormalizedScore()));
    hspElement.addAttribute("e-value", eValueToString(hsp.getEValue()));
    hspElement.addAttribute("query-from", Integer.toString(hsp.getQueryFrom()));
    hspElement.addAttribute("query-to", Integer.toString(hsp.getQueryTo()));
    hspElement.addAttribute("hit-from", Integer.toString(hsp.getHitFrom()));
    hspElement.addAttribute("hit-to", Integer.toString(hsp.getHitTo()));
    hspElement.addAttribute("identity-len", Integer.toString(hsp.getIdentityLength()));
    hspElement.addAttribute("align-len", Integer.toString(hsp.getAlignLength()));

    hspElement.addElement("query").addText(hsp.getQuerySeq());
    hspElement.addElement("align").addText(hsp.getPathSeq());
    hspElement.addElement("targt").addText(hsp.getTargetSeq());

    return hspElement;
}