Example usage for org.dom4j Document addElement

List of usage examples for org.dom4j Document addElement

Introduction

In this page you can find the example usage for org.dom4j Document 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:com.flaptor.hounder.crawler.modules.IndexerModule.java

License:Apache License

public void applyCommand(Object command) {
    if ("optimize".equals(command.toString())) {
        logger.info("optimize requested.");
        try {//from  w ww .  j  ava 2 s.c o m
            org.dom4j.Document dom = DocumentHelper.createDocument();
            dom.addElement("command").addAttribute("name", "optimize");
            for (int i = 0; i < indexers.length; i++) {
                indexers[i].index(dom);
            }
        } catch (Exception e) {
            logger.error(e, e);
        }
    } else if ("delete".equals(command.toString())) {
        FetchDocument doc = ((CommandWithDoc) command).getDoc();
        Page page = doc.getPage();
        deleteFromIndex(page);
    } else if ("startCycle".equals(command.toString())) {
        PageDB pagedb = ((CommandWithPageDB) command).getPageDB();
        scoreThreshold = new float[11];
        for (int i = 0; i < 11; i++) {
            scoreThreshold[i] = pagedb.getScoreThreshold(i * 10);
        }
        antiScoreThreshold = new float[11];
        for (int i = 0; i < 11; i++) {
            antiScoreThreshold[i] = pagedb.getAntiScoreThreshold(i * 10);
        }
    }
}

From source file:com.flaptor.hounder.indexer.RmiIndexerStub.java

License:Apache License

private static Document generateDeleteDocument(String url) {
    org.dom4j.Document dom = DocumentHelper.createDocument();
    Element root = dom.addElement("documentDelete");
    root.addElement("documentId").addText(url);
    return dom;//from w  ww  . j a  va  2 s. c  o  m
}

From source file:com.flaptor.hounder.indexer.RmiIndexerStub.java

License:Apache License

private static Document generateCommandDocument(String command) {
    org.dom4j.Document dom = DocumentHelper.createDocument();
    Element root = dom.addElement("command");
    root.addAttribute("name", command);
    return dom;//from w w  w. j av  a2  s .  co m
}

From source file:com.flaptor.hounder.indexer.SanitizerModule.java

License:Apache License

public static void main(String[] args) {
    String text = args[0];//w  w  w  .j av a 2 s  . com
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("documentAdd");
    root.addElement("text").addText(text);
    root.addElement("field").addAttribute("name", "text").addAttribute("indexed", "true")
            .addAttribute("stored", "true").addAttribute("tokenized", "true").addText(text);
    SanitizerModule mod = new SanitizerModule();
    Document[] docs = mod.internalProcess(doc);
    for (Document d : docs) {
        System.out.println(DomUtil.domToString(d));
    }
}

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  v a  2s  .c o m
 * @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.searcher.XmlResults.java

License:Apache License

/**
 * Creates a XML search results document (verbose version).
 * The generated dom contains only valid xml characters (infringing chars are removed).
 * @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 orderBy the field by which the results are sorted
 * @param sr the GroupedSearchResults structure containing the result of performing the query
 * @param status the code returned by the searcher
 * @param statusMsg the status description
 * @param xsltUri the uri for the xslt used to process the xml on the client side, 
 *          or null if no client-side processing is needed
 * @param rangeField field for which a range filter will be applied, or null if no filter used.
 * @param rangeStart start value for the range filter.
 * @param rangeEnd end value for the range filter.
 * @param params a map of parameters sent to the searcher with the request.
 * @return a DOM document//from w w  w .ja va2  s . c o m
 * <br>An empty sr argument means that no results were found.
 */
public static final Document buildXml(String queryString, int start, int count, String orderBy,
        GroupedSearchResults sr, int status, String statusMsg, String xsltUri, String rangeField,
        String rangeStart, String rangeEnd, Map<String, String[]> params) {

    Document dom = DocumentHelper.createDocument();
    if (null != xsltUri) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "text/xsl");
        map.put("href", xsltUri);
        dom.addProcessingInstruction("xml-stylesheet", map);
    }
    Element root;
    Element group;
    root = dom.addElement("SearchResults");
    root.addElement("totalResults").addText(Integer.toString(sr.totalResults()));
    root.addElement("totalGroupsEstimation").addText(Integer.toString(sr.totalGroupsEstimation()));
    if (count > 0) {
        root.addElement("startIndex").addText(Integer.toString(start));
    }
    if (count > 0) {
        root.addElement("itemsPerPage").addText(Integer.toString(count));
    }
    if (null != orderBy) {
        root.addElement("orderBy").addText(DomUtil.filterXml(orderBy));
    }
    if (null != queryString) {
        root.addElement("query").addText(DomUtil.filterXml(queryString));
    }
    if (null != rangeField) {
        root.addElement("filter").addAttribute("field", rangeField).addAttribute("start", rangeStart)
                .addAttribute("end", rangeEnd);
    }
    if (null != params) {
        for (String key : params.keySet()) {
            if (null == root.selectSingleNode(key)) {
                String val = params.get(key)[0];
                root.addElement(key).addText(val);
            }
        }
    }
    AQuery suggestedQuery = sr.getSuggestedQuery();
    if (null != suggestedQuery) {
        root.addElement("suggestedQuery")
                .addText(DomUtil.filterXml(((LazyParsedQuery) suggestedQuery).getQueryString()));
    }
    root.addElement("status").addText(Integer.toString(status));
    root.addElement("statusDesc").addText(statusMsg);

    for (int i = 0; i < sr.groups(); i++) {
        String name = sr.getGroup(i).first();
        group = root.addElement("group").addAttribute("name", name);
        Vector<org.apache.lucene.document.Document> docs = sr.getGroup(i).last();
        for (int j = 0; j < docs.size(); j++) {
            org.apache.lucene.document.Document doc = sr.getGroup(i).last().get(j);
            createAndAddElement(doc, group);
        }
    }
    return dom;
}

From source file:com.glaf.activiti.extension.xml.ExtensionWriter.java

License:Apache License

public Document write(List<ExtensionEntity> extensions) {
    Document doc = DocumentHelper.createDocument();
    if (extensions != null && extensions.size() > 0) {
        Element root = doc.addElement("bpm-cfg");
        Iterator<ExtensionEntity> iterator = extensions.iterator();
        while (iterator.hasNext()) {
            ExtensionEntity extension = iterator.next();
            if (root.attribute("type") == null && extension.getType() != null) {
                root.addAttribute("type", extension.getType());
            }//  www.  j a v  a 2s  . c o m
            if (StringUtils.isNotEmpty(extension.getTaskName())) {
                Element element = root.addElement("taskmgr");
                element.addAttribute("processName", extension.getProcessName());
                element.addAttribute("taskName", extension.getTaskName());
                if (extension.getFieldValue("taskMgmtType") != null) {
                    Element elem = element.addElement("taskMgmtType");
                    elem.setText(extension.getFieldValue("taskMgmtType"));
                }
                if (extension.getFieldValue("handlers") != null) {
                    Element elem = element.addElement("handlers");
                    elem.setText(extension.getFieldValue("handlers"));
                }
                if (extension.getFields() != null && extension.getFields().size() > 0) {
                    Element elem = element.addElement("properties");
                    Iterator<ExtensionFieldEntity> iter = extension.getFields().values().iterator();
                    while (iter.hasNext()) {
                        ExtensionFieldEntity field = iter.next();
                        Element e = elem.addElement("property");
                        e.addAttribute("key", field.getName());
                        e.addCDATA(field.getValue());
                    }
                }
            } else if (StringUtils.isNotEmpty(extension.getName())) {
                Element element = root.addElement("action");
                element.addAttribute("processName", extension.getProcessName());
                element.addAttribute("name", extension.getName());
                if (extension.getFieldValue("sql") != null) {
                    Element elem = element.addElement("sql");
                    elem.addCDATA(extension.getFieldValue("sql"));
                }
                if (extension.getFieldValue("handlers") != null) {
                    Element elem = element.addElement("handlers");
                    elem.setText(extension.getFieldValue("handlers"));
                }
                if (extension.getParams() != null && extension.getParams().size() > 0) {
                    Element em = element.addElement("parameters");
                    Iterator<ExtensionParamEntity> iter = extension.getParams().iterator();
                    while (iter.hasNext()) {
                        ExtensionParamEntity param = iter.next();
                        Element e = em.addElement("parameter");
                        e.addAttribute("name", param.getName());
                        e.addAttribute("type", param.getType());
                        e.addCDATA(param.getValue());
                    }
                }
            }
        }
    }
    return doc;
}

From source file:com.glaf.core.xml.XmlWriter.java

License:Apache License

public Document write(List<ClassDefinition> rows) {
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("mapping");
    for (ClassDefinition classDefinition : rows) {
        Element element = root.addElement("entity");
        element.addAttribute("name", classDefinition.getEntityName());
        element.addAttribute("package", classDefinition.getPackageName());
        element.addAttribute("moduleName", classDefinition.getModuleName());
        element.addAttribute("table", classDefinition.getTableName());
        element.addAttribute("title", classDefinition.getTitle());
        element.addAttribute("englishTitle", classDefinition.getEnglishTitle());
        FieldDefinition idField = classDefinition.getIdField();
        if (idField != null) {
            Element idElement = element.addElement("id");
            idElement.addAttribute("name", idField.getName());
            idElement.addAttribute("column", idField.getColumnName());
            idElement.addAttribute("type", idField.getType());
            idElement.addAttribute("title", idField.getTitle());
            idElement.addAttribute("englishTitle", idField.getEnglishTitle());
            if (idField.getLength() > 0) {
                idElement.addAttribute("length", String.valueOf(idField.getLength()));
            }//from   ww w  .j  av  a  2s .  c  om
        }

        Map<String, FieldDefinition> fields = classDefinition.getFields();
        Set<Entry<String, FieldDefinition>> entrySet = fields.entrySet();
        for (Entry<String, FieldDefinition> entry : entrySet) {
            String name = entry.getKey();
            FieldDefinition field = entry.getValue();
            if (idField != null
                    && StringUtils.equalsIgnoreCase(idField.getColumnName(), field.getColumnName())) {
                continue;
            }
            Element elem = element.addElement("property");
            elem.addAttribute("name", name);
            elem.addAttribute("column", field.getColumnName());
            elem.addAttribute("type", field.getType());
            elem.addAttribute("title", field.getTitle());
            elem.addAttribute("englishTitle", field.getEnglishTitle());

            if (StringUtils.equals(field.getType(), "String") && field.getLength() > 0) {
                elem.addAttribute("length", String.valueOf(field.getLength()));
            }
            if (field.isUnique()) {
                elem.addAttribute("unique", String.valueOf(field.isUnique()));
            }
            if (field.isSearchable()) {
                elem.addAttribute("searchable", String.valueOf(field.isSearchable()));
            }
            if (!field.isNullable()) {
                elem.addAttribute("nullable", String.valueOf(field.isNullable()));
            }
            if (field.isEditable()) {
                elem.addAttribute("editable", String.valueOf(field.isEditable()));
            }
            if (field.getDisplayType() > 0) {
                elem.addAttribute("displayType", String.valueOf(field.getDisplayType()));
            }
        }
    }
    return doc;
}

From source file:com.glaf.dts.util.XmlWriter.java

License:Apache License

public Document write(List<DataTransfer> rows) {
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("mapping");
    for (DataTransfer dataTransfer : rows) {
        Element element = root.addElement("entity");
        element.addAttribute("name", dataTransfer.getEntityName());
        element.addAttribute("package", dataTransfer.getPackageName());
        element.addAttribute("entityName", dataTransfer.getEntityName());
        element.addAttribute("className", dataTransfer.getClassName());
        element.addAttribute("table", dataTransfer.getTableName());
        element.addAttribute("title", dataTransfer.getTitle());
        element.addAttribute("englishTitle", dataTransfer.getEnglishTitle());
        element.addAttribute("parseType", dataTransfer.getParseType());
        element.addAttribute("parseClass", dataTransfer.getParseClass());
        element.addAttribute("filePrefix", dataTransfer.getFilePrefix());
        element.addAttribute("aggregationKeys", dataTransfer.getAggregationKeys());
        element.addAttribute("deleteFetch", dataTransfer.getDeleteFetch());
        element.addAttribute("insertOnly", dataTransfer.getInsertOnly());
        element.addAttribute("primaryKey", dataTransfer.getPrimaryKey());
        element.addAttribute("queryIds", dataTransfer.getQueryIds());
        element.addAttribute("split", dataTransfer.getSplit());
        element.addAttribute("stopWord", dataTransfer.getStopWord());
        element.addAttribute("temporaryFlag", dataTransfer.getTemporaryFlag());
        element.addAttribute("batchSize", String.valueOf(dataTransfer.getBatchSize()));
        element.addAttribute("startRow", String.valueOf(dataTransfer.getStartRow()));
        element.addAttribute("stopSkipRow", String.valueOf(dataTransfer.getStopSkipRow()));
        element.addAttribute("systemFlag", dataTransfer.getSystemFlag());

        ColumnDefinition idField = dataTransfer.getIdColumn();
        if (idField != null) {
            Element idElement = element.addElement("id");
            idElement.addAttribute("name", idField.getName());
            idElement.addAttribute("column", idField.getColumnName());
            idElement.addAttribute("type", idField.getType());
            idElement.addAttribute("title", idField.getTitle());
            idElement.addAttribute("englishTitle", idField.getEnglishTitle());
            if (idField.getLength() > 0) {
                idElement.addAttribute("length", String.valueOf(idField.getLength()));
            }//from www.  j  a  v  a2  s.  co  m
            if (idField.getValueExpression() != null) {
                idElement.addAttribute("valueExpression", idField.getValueExpression());
            }
        }

        List<ColumnDefinition> columns = dataTransfer.getColumns();
        for (ColumnDefinition field : columns) {
            if (idField != null
                    && StringUtils.equalsIgnoreCase(idField.getColumnName(), field.getColumnName())) {
                continue;
            }
            Element elem = element.addElement("property");
            elem.addAttribute("name", field.getName());
            elem.addAttribute("column", field.getColumnName());
            elem.addAttribute("type", field.getType());
            if (field.getTitle() != null) {
                elem.addAttribute("title", field.getTitle());
            }
            if (field.getEnglishTitle() != null) {
                elem.addAttribute("englishTitle", field.getEnglishTitle());
            }
            if (field.getValueExpression() != null) {
                elem.addAttribute("valueExpression", field.getValueExpression());
            }

            if (field.getLength() > 0) {
                elem.addAttribute("length", String.valueOf(field.getLength()));
            }
            if (field.getPosition() != null && field.getPosition() > 0) {
                elem.addAttribute("position", String.valueOf(field.getPosition()));
            }
            if (field.getPrecision() > 0) {
                elem.addAttribute("precision", String.valueOf(field.getPrecision()));
            }
            if (field.isUnique()) {
                elem.addAttribute("unique", String.valueOf(field.isUnique()));
            }
            if (field.isSearchable()) {
                elem.addAttribute("searchable", String.valueOf(field.isSearchable()));
            }
            if (!field.isNullable()) {
                elem.addAttribute("nullable", String.valueOf(field.isNullable()));
            }
            if (field.isEditable()) {
                elem.addAttribute("editable", String.valueOf(field.isEditable()));
            }
            elem.addAttribute("displayType", String.valueOf(field.getDisplayType()));
        }
    }
    return doc;
}

From source file:com.glaf.jbpm.config.JbpmExtensionWriter.java

License:Apache License

public Document write(List<Extension> extensions) {
    Document doc = DocumentHelper.createDocument();
    if (extensions != null && extensions.size() > 0) {
        Element root = doc.addElement("bpm-cfg");
        Iterator<Extension> iterator = extensions.iterator();
        while (iterator.hasNext()) {
            Extension extension = iterator.next();
            if (root.attribute("type") == null && extension.getType() != null) {
                root.addAttribute("type", extension.getType());
            }// w ww  .j  av a  2 s  .co  m
            if (StringUtils.isNotEmpty(extension.getTaskName())) {
                Element element = root.addElement("taskmgr");
                element.addAttribute("processName", extension.getProcessName());
                element.addAttribute("taskName", extension.getTaskName());
                if (extension.getFieldValue("taskMgmtType") != null) {
                    Element elem = element.addElement("taskMgmtType");
                    elem.setText(extension.getFieldValue("taskMgmtType"));
                }
                if (extension.getFieldValue("handlers") != null) {
                    Element elem = element.addElement("handlers");
                    elem.setText(extension.getFieldValue("handlers"));
                }
                if (extension.getFields() != null && extension.getFields().size() > 0) {
                    Element elem = element.addElement("properties");
                    Iterator<ExtensionField> iter = extension.getFields().values().iterator();
                    while (iter.hasNext()) {
                        ExtensionField field = iter.next();
                        Element e = elem.addElement("property");
                        e.addAttribute("key", field.getName());
                        e.addCDATA(field.getValue());
                    }
                }
            } else if (StringUtils.isNotEmpty(extension.getName())) {
                Element element = root.addElement("action");
                element.addAttribute("processName", extension.getProcessName());
                element.addAttribute("name", extension.getName());
                if (extension.getFieldValue("sql") != null) {
                    Element elem = element.addElement("sql");
                    elem.addCDATA(extension.getFieldValue("sql"));
                }
                if (extension.getFieldValue("handlers") != null) {
                    Element elem = element.addElement("handlers");
                    elem.setText(extension.getFieldValue("handlers"));
                }
                if (extension.getParams() != null && extension.getParams().size() > 0) {
                    Element em = element.addElement("parameters");
                    Iterator<ExtensionParam> iter = extension.getParams().iterator();
                    while (iter.hasNext()) {
                        ExtensionParam param = iter.next();
                        Element e = em.addElement("parameter");
                        e.addAttribute("name", param.getName());
                        e.addAttribute("type", param.getType());
                        e.addCDATA(param.getValue());
                    }
                }
            }
        }
    }
    return doc;
}