Example usage for org.dom4j Element add

List of usage examples for org.dom4j Element add

Introduction

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

Prototype

void add(Namespace namespace);

Source Link

Document

Adds the given Namespace to this element.

Usage

From source file:com.easyjf.generator.AllGenerator.java

License:Apache License

private void genXml(AllProcessor processor) {
    for (String templateFile : this.xmlfiles.keySet()) {
        tg.setProcess(processor);//  w w  w .j  av  a 2 s.  c o  m
        String fileName = (String) xmlfiles.get(templateFile);
        File targetFile = new File(fileName);
        tg.setTargetDir("");
        tg.setTemplateDir(templateDir);
        tg.setTemplateName(templateFile);
        if (targetFile.exists()) {
            tg.setTargetName(fileName + "_tmp");
            tg.generator(false);
            try {
                Document doc = this.getDocument(fileName + "_tmp");
                Document document = this.getDocument(fileName);
                String existNode = "/easyjf-web/modules/module[@name='" + this.lowerBeanName + "']";

                Node node = "mvc.xml".equals(templateFile) ? document.selectSingleNode(existNode)
                        : findBean(document,
                                this.lowerBeanName + ("dao.xml".equals(templateFile) ? "Dao" : "Service"));
                if (node == null) {
                    String appendNode = "/easyjf-web/modules", cnode = appendNode + "/module";
                    if (!"mvc.xml".equals(templateFile))
                        appendNode = "/beans";
                    Element moduleE = (Element) document.selectSingleNode(appendNode);
                    Node n = "mvc.xml".equals(templateFile) ? doc.selectSingleNode(cnode)
                            : findBean(doc,
                                    this.lowerBeanName + ("dao.xml".equals(templateFile) ? "Dao" : "Service"));
                    if (moduleE != null && n != null) {
                        n.detach();
                        moduleE.add(n);
                    }
                    OutputFormat format = OutputFormat.createPrettyPrint();
                    XMLWriter output = new XMLWriter(new FileWriter(new File(fileName)), format);
                    output.write(document);
                    output.close();
                }
                new File(fileName + "_tmp").deleteOnExit();
                new File(fileName + "_tmp").delete();
            } catch (Exception e) {
                //               e.printStackTrace();
            }
            System.out.println(
                    I18n.getLocaleMessage("generator.Successfully.add.to.configuration.information.to.a.file")
                            + fileName);
        } else {
            System.out.println(
                    I18n.getLocaleMessage("generator.Successful.configuration.file.generation") + fileName);
            tg.setTargetName(fileName);
            new File(fileName + "_tmp").deleteOnExit();
            new File(fileName + "_tmp").delete();
            tg.generator(false);
        }

    }
}

From source file:com.easyjf.web.config.BeanConfigReader.java

License:Apache License

public static Collection parseCollectionValue(Element e) {
    java.util.Collection values = null;
    Element node = XmlElementUtil.findElement("list", e);
    if (node != null) {
        List ps = XmlElementUtil.findElements("value", node);
        if (ps != null && ps.size() > 0) {
            values = new ArrayList();
            for (int i = 0; i < ps.size(); i++) {
                Element parent = DocumentHelper.createElement("property");
                parent.add((Element) ((org.dom4j.Node) ps.get(i)).clone());
                values.add(parsePropertyValue(parent));
            }//from   ww  w  .j a v a2s . co  m
        } else {

        }
    }
    return values;
}

From source file:com.eurelis.opencms.ant.task.ManifestBuilderTask.java

License:Open Source License

public Document createDocument() {

    document = DocumentHelper.createDocument();
    document.setXMLEncoding("UTF-8");
    Element root = document.addElement("export");

    Element info = root.addElement("info");
    if (creator != null)
        info.addElement("creator").addText(creator);
    if (opencmsversion != null)
        info.addElement("opencms_version").addText(opencmsversion);
    info.addElement("createdate").addText(dateformat.format(new Date()));
    if (project != null)
        info.addElement("infoproject").addText(project);
    if (exportversion != null)
        info.addElement("export_version").addText(exportversion);

    Element module = root.addElement("module");

    if (name != null)
        module.addElement("name").addText(name);
    if (nicename != null)
        module.addElement("nicename").addText(nicename);
    if (group != null)
        module.addElement("group").addText(group);
    if (moduleclass != null)
        module.addElement("class").addText(moduleclass);
    if (moduledescription != null)
        module.addElement("description").add(new FlyweightCDATA(moduledescription));
    if (version != null)
        module.addElement("version").addText(version);
    if (authorname != null)
        module.addElement("authorname").add(new FlyweightCDATA(authorname));
    if (authoremail != null)
        module.addElement("authoremail").add(new FlyweightCDATA(authoremail));
    module.addElement("datecreated").addText(dateformat.format(new Date()));
    module.addElement("userinstalled").addText(userinstalled);
    module.addElement("dateinstalled").addText(dateinstalled);

    Element dependenciesBlock = module.addElement("dependencies");
    for (Dependency dep : dependencies) {
        dependenciesBlock.addElement("dependency").addAttribute("name", dep.getName()).addAttribute("version",
                dep.getVersion());//from www. j a  v  a  2s .com
    }

    Element exportPointsBlock = module.addElement("exportpoints");
    for (ExportPoint ep : exportpoints) {
        exportPointsBlock.addElement("exportpoint").addAttribute("uri", ep.getSrc()).addAttribute("destination",
                ep.getDst());
    }

    Element resourcesBlock = module.addElement("resources");
    for (Resource res : resources) {
        resourcesBlock.addElement("resource").addAttribute("uri", res.getUri());
    }

    Element parametersBlock = module.addElement("parameters");
    for (Parameter par : parameters) {
        parametersBlock.addElement("param").addAttribute("name", par.getName()).addText(par.getValue());
    }

    insertResourceTypes(module);
    insertExplorerTypes(module);

    if (!filesets.isEmpty()) {

        Element files = root.addElement("files");

        for (FileSet fileset : filesets) {
            DirectoryScanner ds = fileset.getDirectoryScanner(fileset.getProject());
            String[] dirs = ds.getIncludedDirectories();
            String[] filesColl = ds.getIncludedFiles();

            String[] excluDirsArray = ds.getExcludedDirectories();
            List<String> excluDirs = new ArrayList<String>();
            excluDirs.addAll(Arrays.asList(excluDirsArray));

            String[] excluFilesArray = ds.getExcludedFiles();
            List<String> excluFiles = new ArrayList<String>();
            excluFiles.addAll(Arrays.asList(excluFilesArray));

            CmsUUID.init("B4:B6:76:78:7F:3E");

            // FOLDERS MANAGEMENT
            for (int i = 0; i < dirs.length; i++) {
                String filepath = dirs[i];
                String filepathUnix = dirs[i].replace(SEPARATOR, "/");
                if (dirs[i] != "") {
                    Element tmpFile = files.addElement("file");
                    tmpFile.addElement("destination").addText(filepathUnix);

                    String folderPropertiesPath = getProject().getBaseDir() + SEPARATOR + srcfolder + SEPARATOR
                            + folderPropertiesPath(filepath);
                    String tmpType = getEurelisProperty("type", folderPropertiesPath);
                    if (null == tmpType) {
                        tmpType = "folder";
                    }
                    tmpFile.addElement("type").addText(tmpType);

                    if (generateuuids) {
                        Element uuidNode = tmpFile.addElement("uuidstructure");
                        String tmpUUID = getEurelisProperty("structureUUID", folderPropertiesPath);
                        if (null != tmpUUID)
                            uuidNode.addText(tmpUUID);
                        else
                            uuidNode.addText(new CmsUUID().toString());
                        // AJOUTER SAUVEGARDE DU NOUVEL UUID
                    }

                    long date = new File(
                            getProject().getBaseDir() + SEPARATOR + srcfolder + SEPARATOR + filepath)
                                    .lastModified();
                    if (0L == date)
                        date = new Date().getTime();
                    String formattedDate = dateformat.format(date);
                    tmpFile.addElement("datelastmodified").addText(formattedDate);
                    tmpFile.addElement("userlastmodified").addText("Admin");
                    // WARNING : CONSTANT VALUE
                    tmpFile.addElement("datecreated").addText(formattedDate);
                    // WARNING : CONSTANT VALUE
                    tmpFile.addElement("usercreated").addText("Admin");
                    tmpFile.addElement("flags").addText("0");

                    Element properties = tmpFile.addElement("properties");
                    // props detection and implementation
                    String tmpPropFile = folderPropertiesPath;
                    addPropertiesToTree(properties, tmpPropFile);

                    String tmpAccessFile = getProject().getBaseDir() + SEPARATOR + srcfolder + SEPARATOR
                            + folderAccessesPath(filepath);
                    addAccessesToTree(tmpFile, tmpAccessFile);
                }
            }
            // FILES MANAGEMENT
            for (int i = 0; i < filesColl.length; i++) {
                String filepath = filesColl[i];
                String filepathUnix = filesColl[i].replace(SEPARATOR, "/");
                if (filesColl[i] != "") {
                    Element tmpFile = files.addElement("file");
                    tmpFile.addElement("source").addText(filepathUnix);
                    tmpFile.addElement("destination").addText(filepathUnix);

                    String propertiesFilepath = getProject().getBaseDir() + SEPARATOR + srcfolder + SEPARATOR
                            + filePropertiesPath(filepath);
                    String tmpType = getEurelisProperty("type", propertiesFilepath);
                    if (null == tmpType) {
                        if (filepathUnix.endsWith(".config"))
                            tmpType = "module_config";
                        else if (filepathUnix.endsWith("main.jsp"))
                            tmpType = "containerpage_template";
                        else if (filepathUnix.endsWith(".jsp"))
                            tmpType = "jsp";
                        else if (filepathUnix.endsWith(".png") || filepathUnix.endsWith(".gif")
                                || filepathUnix.endsWith(".jpg") || filepathUnix.endsWith(".jpeg"))
                            tmpType = "image";
                        else if (filepathUnix.endsWith(".html") && filepathUnix.contains("/models/"))
                            tmpType = "containerpage";
                        else
                            tmpType = "plain";
                    }
                    tmpFile.addElement("type").addText(tmpType);

                    if (generateuuids) {
                        Element uuidNode = tmpFile.addElement("uuidresource");
                        Element uuidNode2 = tmpFile.addElement("uuidstructure");
                        String tmpUUID = getEurelisProperty("resourceUUID", propertiesFilepath);
                        if (null != tmpUUID)
                            uuidNode.addText(tmpUUID);
                        else
                            uuidNode.addText(new CmsUUID().toString());
                        tmpUUID = getEurelisProperty("structureUUID", propertiesFilepath);
                        if (null != tmpUUID)
                            uuidNode2.addText(tmpUUID);
                        else
                            uuidNode2.addText(new CmsUUID().toString());
                    }

                    long date = new File(
                            getProject().getBaseDir() + SEPARATOR + srcfolder + SEPARATOR + filepath)
                                    .lastModified();
                    if (0L == date)
                        date = new Date().getTime();
                    String formattedDate = dateformat.format(date);

                    tmpFile.addElement("datelastmodified").addText(formattedDate);
                    tmpFile.addElement("userlastmodified").addText("Admin");
                    tmpFile.addElement("datecreated").addText(formattedDate);
                    tmpFile.addElement("usercreated").addText("Admin");
                    tmpFile.addElement("flags").addText("0");
                    Element properties = tmpFile.addElement("properties");
                    String tmpPropFile = propertiesFilepath;
                    addPropertiesToTree(properties, tmpPropFile);

                    tmpFile.addElement("accesscontrol");

                }
            }
        }
    }

    return document;
}

From source file:com.eurelis.opencms.ant.task.ManifestBuilderTask.java

License:Open Source License

private void insertExplorerTypes(Element module) {
    if (null != explorertypes) {
        File xml = new File(explorertypes);
        SAXReader reader = new SAXReader();
        Document doc;//  w  w w  .j  a  v a 2  s. co m
        try {
            doc = reader.read(xml);
            Element root = doc.getRootElement();
            module.add(root);
        } catch (DocumentException e) {
            module.addElement("explorertypes");
        }

    }
}

From source file:com.eurelis.opencms.ant.task.ManifestBuilderTask.java

License:Open Source License

private void insertResourceTypes(Element module) {
    if (null != resourcetypes) {
        File xml = new File(resourcetypes);
        SAXReader reader = new SAXReader();
        Document doc;/*from   www. j  av a 2 s  .  c o m*/
        try {
            doc = reader.read(xml);
            Element root = doc.getRootElement();
            module.add(root);
        } catch (DocumentException e) {
            module.addElement("resourcetypes");
        }
    }

}

From source file:com.eurelis.opencms.ant.task.ManifestBuilderTask.java

License:Open Source License

private void addPropertiesToTree(Element root, String propFilePath) {
    try {//from  www .j  av a  2s  . c  om
        Properties props = new Properties();
        if (new File(propFilePath).exists())
            props.load(new FileInputStream(propFilePath));
        if (!props.isEmpty()) {
            for (Object keyObject : props.keySet()) {
                try {
                    String key = (String) keyObject;
                    if (key == null)
                        continue;
                    String value = props.getProperty(key);
                    if (value == null)
                        continue;
                    if (value.length() > 0) {
                        if (key.contains("EurelisProperty")) {
                            continue;
                        }
                        Element property = root.addElement("property");
                        property.addElement("name")
                                .addText(key.matches("^.*\\.[is]$") ? key.substring(0, key.length() - 2) : key);
                        property.addElement("value").add(new FlyweightCDATA(value));
                        if (key.endsWith(".s"))
                            property.addAttribute("type", "shared");
                    }
                } catch (Exception e) {
                    log(e, Project.MSG_ERR);
                    e.printStackTrace();
                }
            }
        }

    } catch (Exception e) {
        log(e, Project.MSG_ERR);
        e.printStackTrace();
    }
}

From source file:com.eurelis.opencms.ant.task.ManifestBuilderTask.java

License:Open Source License

private void addAccessesToTree(Element root, String propFilePath) {
    if (null != propFilePath) {
        File xml = new File(propFilePath);
        SAXReader reader = new SAXReader();
        Document doc;// w  w  w  . ja  v a 2s.c  o  m
        try {
            doc = reader.read(xml);
            Element elem = doc.getRootElement();
            if (null != elem)
                root.add(elem);
            else
                root.addElement("accesscontrol");
        } catch (DocumentException e) {
            root.addElement("accesscontrol");
        }
    }
}

From source file:com.flaptor.hounder.searcher.OpenSearch.java

License:Apache License

/**
 * Creates a OpenSearch's compatible DOM document.
 * The generated dom contains only valid xml characters (infringing chars are removed).
 * Compliant with OpenSearch 1.0 with most of the Nutch 0.8.1 extensions.
 * @param baseUrl the url of the webapp/*from   ww  w  .  j a va  2s  .  c  om*/
 * @param htmlSearcher the name of the component (servlet/jsp) that returns the search results in an HTML page
 * @param opensearchSearcher the name of the component (servlet/jsp) that returns the search results in an OpenSearch RSS page
 * @param extraParams the parameters present in the request, not passed explicitly (such as sort, reverse, etc.)
 * @param queryString the query string, as entered by the user
 * @param start the offset of the first result
 * @param count the number of results requested (the actual number of results found may be smaller)
 * @param sr the SearchResults structure containing the result of performing the query
 * @return a DOM document
 * <br>An empty sr argument means that no results were found.
 */
public static final Document buildDom_1_0(String baseUrl, String htmlSearcher, String opensearchSearcher,
        String extraParams, String queryString, int start, int count, GroupedSearchResults sr, int status,
        String statusMessage, boolean useXslt) {

    String encodedQuery = null;
    try {
        encodedQuery = URLEncoder.encode(queryString, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // Should never happen!
        encodedQuery = "";
    }
    Document dom = DocumentHelper.createDocument();
    if (useXslt) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "text/xsl");
        map.put("href", xsltPath);
        dom.addProcessingInstruction("xml-stylesheet", map);
    }

    Namespace opensearchNs = DocumentHelper.createNamespace("opensearch", XMLNS_A9_OPENSEARCH_1_0);
    Namespace hounderNs = DocumentHelper.createNamespace("hounder", XMLNS_HOUNDER_OPENSEARCH_1_0);
    Element root;
    Element channel;
    if (!useXslt) {
        root = dom.addElement("rss").addAttribute("version", "2.0");
        channel = root.addElement("channel");
    } else {
        channel = dom.addElement("searchResults");
        root = channel;
    }
    root.add(opensearchNs);
    root.add(hounderNs);

    channel.addElement("title").addText(titlePrefix + " " + DomUtil.filterXml(queryString));
    channel.addElement("link")
            .addText(baseUrl + "/" + htmlSearcher + "?query=" + encodedQuery + "&start=" + start + extraParams);
    channel.addElement("description").addText(descPrefix + " " + DomUtil.filterXml(queryString));
    channel.addElement(QName.get("totalResults", opensearchNs))
            .addText(Integer.toString(sr.totalGroupsEstimation()));
    channel.addElement(QName.get("startIndex", opensearchNs)).addText(Integer.toString(start));
    channel.addElement(QName.get("itemsPerPage", opensearchNs)).addText(Integer.toString(count));
    channel.addElement(QName.get("query", hounderNs)).addText(DomUtil.filterXml(queryString));
    AQuery suggestedQuery = sr.getSuggestedQuery();
    if (null != suggestedQuery) {
        channel.addElement(QName.get("suggestedQuery", hounderNs))
                .addText(DomUtil.filterXml(suggestedQuery.toString()));
    }
    channel.addElement(QName.get("status", hounderNs)).addText(Integer.toString(status));
    channel.addElement(QName.get("statusDesc", hounderNs)).addText(statusMessage);
    if (sr.lastDocumentOffset() > 0) {
        channel.addElement(QName.get("nextPage", hounderNs)).addText(baseUrl + "/" + opensearchSearcher
                + "?query=" + encodedQuery + "&start=" + (sr.lastDocumentOffset()) + extraParams);
    }

    for (int i = 0; i < sr.groups(); i++) {
        Vector<org.apache.lucene.document.Document> docs = sr.getGroup(i).last();
        Element parent = null;
        for (int j = 0; j < docs.size(); j++) {
            org.apache.lucene.document.Document doc = sr.getGroup(i).last().get(j);
            if (0 == j) {// j=0 is head of group. j>0 is tail
                parent = createAndAddElement(doc, channel, hounderNs);
            } else {
                createAndAddElement(doc, parent, hounderNs);
            }

        }
    }
    return dom;
}

From source file:com.flaptor.hounder.util.HtmlParser.java

License:Apache License

/**
 * This parser deletes all the tags and returns only the text. However some
 * tags are used to separate dofferent phrases, so we just add a '.' after
 * some tags to make sure we will be able to distinguish one phrase from 
 * the other in the text//from   ww  w.j  ava 2 s  . c  om
 * @param htmlDoc
 */
@SuppressWarnings("unchecked")
private void replaceSeparatorTags(Document htmlDoc) {
    for (String tag : SEPARATOR_TAGS) {
        List<Element> nodes = (List<Element>) htmlDoc.selectNodes("//" + tag.toUpperCase());
        for (Element node : nodes) {
            try {
                // The 'separator' must be created each time inside the for,
                // else there is a 'already have a parent' conflict
                Node separator = DOMDocumentFactory.getInstance().createText(SEPARATOR);
                node.add(separator);
            } catch (Exception e) {
                logger.warn("Ignoring exception, not appending at " + node.getPath());
                continue;
            }
        }
    }
}

From source file:com.flaptor.util.parser.HtmlParser.java

License:Apache License

/**
 * This parser deletes all the tags and returns only the text. However some
 * tags are used to separate dofferent phrases, so we just add a '.' after
 * some tags to make sure we will be able to distinguish one phrase from 
 * the other in the text/* w w w .ja v a2s.  c  o  m*/
 * @param htmlDoc
 */
@SuppressWarnings("unchecked")
private void replaceSeparatorTags(Document htmlDoc) {
    for (String tag : SEPARATOR_TAGS) {
        List<Element> nodes = (List<Element>) htmlDoc.selectNodes("//" + tag.toUpperCase());
        for (Element node : nodes) {
            try {
                // The 'separator' must be created each time inside the for,
                // else there is a 'already have a parent' conflict
                Node separator = DOMDocumentFactory.getInstance().createText(SEPARATOR);
                node.add(separator);
            } catch (Exception e) {
                logger.debug("Ignoring exception, not appending at " + node.getPath());
                continue;
            }
        }
    }
}