Example usage for org.dom4j Element addText

List of usage examples for org.dom4j Element addText

Introduction

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

Prototype

Element addText(String text);

Source Link

Document

Adds a new Text node with the given text to this element.

Usage

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

public static String toHTML(Map m) {
    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement("html");
    doc.setRootElement(root);//from w w  w . jav  a2s.  c  om
    Element body = root.addElement("body");
    Element table = body.addElement("table");
    Iterator keys = m.keySet().iterator();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        Object val = m.get(key);
        Element row = table.addElement("tr");
        Element keyCell = row.addElement("td");
        keyCell.setText(key);
        Element valCell = row.addElement("td");
        if (val instanceof String) {
            valCell.setText(val.toString());
        } else if (val instanceof Collection) {
            Collection col = (Collection) val;
            for (Iterator it = col.iterator(); it.hasNext();) {
                Element p = valCell.addElement("p");
                Object o = it.next();
                if (o instanceof Map) {
                    Map valmap = (Map) o;
                    Iterator fields = valmap.keySet().iterator();
                    while (fields.hasNext()) {
                        String field = (String) fields.next();
                        String value = (String) valmap.get(field);
                        p.addText(field + ": " + value);
                        if (fields.hasNext()) {
                            p.addElement("br");
                        }
                    }
                } else {
                    p.setText(o.toString());
                }
            }
        } else if (val instanceof Map) {
            Map m2 = (Map) val;
            for (Iterator it = m2.keySet().iterator(); it.hasNext();) {
                String k2 = (String) it.next();
                String v2 = (String) m2.get(k2);
                Element div = valCell.addElement("div");
                div.setText(k2 + ": " + v2);
            }
        } else if (val instanceof Exception) {
            Exception ex = (Exception) val;
            valCell.addElement("p").setText(ex.toString());
            StackTraceElement[] elem = ex.getStackTrace();
            for (int i = 0; i < elem.length; i++) {
                valCell.addText(elem[i].toString());
                valCell.addElement("br");
            }
        }

    }
    return doc.asXML();
}

From source file:edu.umd.cs.findbugs.xml.Dom4JXMLOutput.java

License:Open Source License

@Override
public void writeText(String text) {
    Element top = (Element) stack.getLast();
    top.addText(text);
}

From source file:edu.upenn.cis.orchestra.workloadgenerator.GeneratorJournal.java

License:Apache License

/**
 * Serializes the journal in the format below. The peer and maping elements
 * are as in the Orchestra schema file.//from  w  w  w.j a v  a 2 s  . c o m
 * 
 * <pre>
 *    &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
 *    &lt;!--00:50:07 06/12/08 EDT
 *    {integers=1, inout=true, oracle=0, skip=0, cutoff=1024, password=password, addBypasses=1, deletions=1, 
 *     username=xyz, relsize=15, tukwila=0, fanout=2, olivier=1, schemas=3, dbalias=BIOTBS, insertions=2, 
 *     iterations=2, seed=0, mappingsServer=jdbc:db2://localhost:50000, bidir=0, updateAlias=null, addPeers=1, 
 *     coverage=1.0, deleteBypasses=1, maxcycles=-1, peers=3, filename=prot, mincycles=-1, deletePeers=1}--&gt;
 *    &lt;deltas&gt;
 *      &lt;iteration idx=&quot;0&quot;&gt;
 *        &lt;operation type=&quot;addPeer&quot; name=&quot;P0&quot;/&gt;
 *        &lt;operation type=&quot;addPeer&quot; name=&quot;P1&quot;&gt;
 *          &lt;mapping name=&quot;M0&quot;/&gt;
 *          &lt;mapping name=&quot;M2&quot;/&gt;
 *        &lt;/operation&gt;
 *        &lt;operation type=&quot;addPeer&quot; name=&quot;P2&quot;&gt;
 *          &lt;mapping name=&quot;M1&quot;/&gt;
 *        &lt;/operation&gt;
 *      &lt;/iteration&gt;
 *      &lt;iteration idx=&quot;1&quot;&gt;
 *        &lt;operation type=&quot;addPeer&quot; name=&quot;P3&quot;&gt;
 *          &lt;mapping name=&quot;M3&quot;/&gt;
 *        &lt;/operation&gt;
 *        &lt;operation type=&quot;deletePeer&quot; name=&quot;P0&quot;/&gt;
 *      &lt;/iteration&gt;
 *      &lt;iteration idx=&quot;2&quot;&gt;
 *        &lt;operation type=&quot;addPeer&quot; name=&quot;P4&quot;&gt;
 *          &lt;mapping name=&quot;M4&quot;/&gt;
 *          &lt;mapping name=&quot;M5&quot;/&gt;
 *          &lt;mapping name=&quot;M6&quot;/&gt;
 *        &lt;/operation&gt;
 *        &lt;operation type=&quot;deletePeer&quot; name=&quot;P2&quot;/&gt;
 *        &lt;operation type=&quot;addBypass&quot; name=&quot;M23&quot;/&gt;
 *        &lt;operation type=&quot;deleteBypass&quot; name=&quot;M2&quot;/&gt;
 *      &lt;/iteration&gt;
 *      &lt;peer name=&quot;P0&quot; address=&quot;localhost&quot;&gt;
 *      &lt;/peer&gt;
 *      &lt;mapping name=&quot;M0&quot; materialized=&quot;true&quot;&gt;
 *      &lt;/mapping&gt;
 *    &lt;/deltas&gt;
 * 
 * </pre>
 * 
 * @param params
 *            run parameters, see <code>Generator</code>.
 * @return serialzed <code>GeneratorJournal</code>.
 */
@SuppressWarnings("unchecked")
public Document serialize(Map<String, Object> params) {
    // TODO: this method copies code from MetadataXml, needs refactoring.
    Document deltasDoc = DocumentHelper.createDocument();
    deltasDoc.addComment(WorkloadGeneratorUtils.stamp() + "\n" + params);

    Element deltas = deltasDoc.addElement("deltas");

    List<Integer> indexes = new LinkedList<Integer>(_operations.keySet());
    Collections.sort(indexes);
    for (Integer idx : indexes) {
        Element iteration = deltas.addElement("iteration").addAttribute("idx", idx.toString());
        List<List<String>> operations = _operations.get(idx);
        for (List<String> operation : operations) {
            Element opElement = iteration.addElement("operation").addAttribute("type", operation.get(0))
                    .addAttribute("name", operation.get(1));
            if ("addPeer".equals(operation.get(0))) {
                if (null == _peersToMaps.get(operation.get(1))) {
                    continue;
                }
                for (String mapping : _peersToMaps.get(operation.get(1))) {
                    opElement.addElement("mapping").addAttribute("name", mapping);
                }
            }
        }
    }

    for (int i = 0; i < _peers.size(); i++) {
        Element peer = deltas.addElement("peer").addAttribute("name", "P" + i).addAttribute("address",
                "localhost");
        int j = _peers.get(i);
        Element schema = peer.addElement("schema").addAttribute("name", "S" + j);
        for (int k = 0; k < _logicalSchemas.get(j).size(); k++) {
            for (String var : iovariations((Boolean) params.get("inout"))) {
                Element relation = schema.addElement("relation")
                        .addAttribute("name", WorkloadGeneratorUtils.relname(i, j, k) + var)
                        .addAttribute("materialized", "true");

                if ((Double) params.get("coverage") == 1) {
                    relation.addAttribute("noNulls", "true");
                }

                String hasLocalData;
                if (Generator.peerHasLocalData(i, (Integer) params.get("topology"),
                        (Integer) params.get("modlocal"), (Integer) params.get("peers"),
                        (Integer) params.get("fanout"))) {
                    hasLocalData = "true";
                } else {
                    hasLocalData = "false";
                }
                relation.addAttribute("hasLocalData", hasLocalData);
                relation.addElement("dbinfo").addAttribute("schema", (String) params.get("username"))
                        .addAttribute("table", WorkloadGeneratorUtils.relname(i, j, k) + var);
                relation.addElement("field").addAttribute("name", "KID").addAttribute("type", "integer")
                        .addAttribute("key", "true");
                for (String att : _logicalSchemas.get(j).get(k)) {
                    relation.addElement("field").addAttribute("name", att).addAttribute("type",
                            MetadataXml.universalType(att, params));
                }
            }
        }
    }

    for (int k = 0; k < _mappings.size(); k++) {
        int i = (Integer) _mappings.get(k).get(1);
        int j = (Integer) _mappings.get(k).get(2);

        List<String> x = (List<String>) _mappings.get(k).get(3);
        List<String> source = MetadataXml.selectAtoms(i, "KID", x, "_", _logicalSchemas, _peers,
                (Boolean) params.get("addValueAttr"), true);
        // _ means don't care
        List<String> target = MetadataXml.selectAtoms(j, "KID", x, "-", _logicalSchemas, _peers,
                (Boolean) params.get("addValueAttr"), false);
        // - means null
        Element mapping = deltas.addElement("mapping").addAttribute("name", "M" + k)
                .addAttribute("materialized", "true");
        if (1 == (Integer) params.get("bidir")) {
            mapping.addAttribute("bidirectional", "true");
        }
        Element head = mapping.addElement("head");
        for (String atom : target) {
            Element atomElem = head.addElement("atom");
            if (1 == (Integer) params.get("bidir")) {
                atomElem.addAttribute("del", "true");
            }
            atomElem.addText(atom);
        }
        Element body = mapping.addElement("body");
        for (String atom : source) {
            Element atomElem = body.addElement("atom");
            if (1 == (Integer) params.get("bidir")) {
                atomElem.addAttribute("del", "true");
            }
            atomElem.addText(atom);
        }
    }

    return deltasDoc;

}

From source file:edu.upenn.cis.orchestra.workloadgenerator.MetadataXml.java

License:Apache License

@SuppressWarnings("unchecked")
public void metadataXml(List<List<List<String>>> schemas, List<Integer> peers, List<List<Object>> mappings,
        String extension) {// ww w . java 2  s.  c om

    Writer writer = null;
    if (null == _params.get("filename")) {
        writer = new PrintWriter(System.out);
    } else {
        try {
            if (!"".equals(extension)) {
                extension = "." + extension;
            }
            writer = new FileWriter((String) _params.get("filename") + extension + ".schema");
            // + ".schema.new");
        } catch (IOException e) {
            throw new IllegalStateException("Unable to create schema file.", e);
        }
    }

    Document document = DocumentHelper.createDocument();
    document.addComment(WorkloadGeneratorUtils.stamp() + "\n" + _params);
    Element catalog = document.addElement("catalog").addAttribute("recMode", "false").addAttribute("name",
            (String) _params.get("filename"));
    catalog.addElement("migrated").setText("true");
    for (int i = 0; i < peers.size(); i++) {
        if (null == peers.get(i)) {
            continue;
        }
        Element peer = catalog.addElement("peer").addAttribute("name", "P" + i).addAttribute("address",
                "localhost");
        int j = peers.get(i);
        Element schema = peer.addElement("schema").addAttribute("name", "S" + j);
        for (int k = 0; k < schemas.get(j).size(); k++) {
            for (String var : iovariations()) {
                Element relation = schema.addElement("relation")
                        .addAttribute("name", WorkloadGeneratorUtils.relname(i, j, k) + var)
                        .addAttribute("materialized", "true");
                if ((Double) _params.get("coverage") == 1) {
                    relation.addAttribute("noNulls", "true");
                }

                String hasLocalData;
                if (Generator.peerHasLocalData(i, (Integer) _params.get("topology"),
                        (Integer) _params.get("modlocal"), (Integer) _params.get("peers"),
                        (Integer) _params.get("fanout"))) {
                    hasLocalData = "true";
                } else {
                    hasLocalData = "false";
                }

                relation.addAttribute("hasLocalData", hasLocalData);
                relation.addElement("dbinfo").addAttribute("schema", (String) _params.get("username"))
                        .addAttribute("table", WorkloadGeneratorUtils.relname(i, j, k) + var);
                relation.addElement("field").addAttribute("name", "KID").addAttribute("type", "integer")
                        .addAttribute("key", "true");
                for (String att : schemas.get(j).get(k)) {
                    if ((Boolean) _params.get("addValueAttr") && att.equals(Relation.valueAttrName)) {
                        relation.addElement("field").addAttribute("name", att).addAttribute("type", "integer")
                                .addAttribute("key", "true");
                    } else {
                        relation.addElement("field").addAttribute("name", att).addAttribute("type",
                                universalType(att, _params));
                    }
                }
            }
        }
    }

    for (int k = 0; k < mappings.size(); k++) {
        if (null == mappings.get(k)) {
            continue;
        }
        int i = (Integer) mappings.get(k).get(0);
        int j = (Integer) mappings.get(k).get(1);

        List<String> x = (List<String>) mappings.get(k).get(2);
        List<String> source = selectAtoms(i, "KID", x, "_", schemas, peers,
                (Boolean) _params.get("addValueAttr"), true);
        // _ means don't care
        List<String> target = selectAtoms(j, "KID", x, "-", schemas, peers,
                (Boolean) _params.get("addValueAttr"), false);
        // - means null
        Element mapping = catalog.addElement("mapping").addAttribute("name", "M" + k)
                .addAttribute("materialized", "true");
        if (1 == (Integer) _params.get("bidir")) {
            mapping.addAttribute("bidirectional", "true");
        }
        Element head = mapping.addElement("head");
        for (String atom : target) {
            Element atomElem = head.addElement("atom");
            if (1 == (Integer) _params.get("bidir")) {
                atomElem.addAttribute("del", "true");
            }
            atomElem.addText(atom);
        }
        Element body = mapping.addElement("body");
        for (String atom : source) {
            Element atomElem = body.addElement("atom");
            if (1 == (Integer) _params.get("bidir")) {
                atomElem.addAttribute("del", "true");
            }
            atomElem.addText(atom);
        }
    }

    Element mappingsElem = catalog.addElement("engine").addElement("mappings");
    if (1 == (Integer) _params.get("tukwila")) {
        mappingsElem.addAttribute("type", "tukwila").addAttribute("host", "localhost").addAttribute("port",
                "7777");
    } else {
        mappingsElem.addAttribute("type", "sql")
                .addAttribute("server", (String) _params.get("mappingsServer") + "/"
                // "jdbc:db2://localhost:50000/"
                        + _params.get("dbalias"))
                .addAttribute("username", (String) _params.get("username"))
                .addAttribute("password", (String) _params.get("password"));
    }
    if (null != _params.get("updateAlias")) {
        catalog.addElement("updates")
                .addAttribute("server", "jdbc:db2://localhost:50000/" + _params.get("updateAlias"))
                .addAttribute("username", (String) _params.get("username"))
                .addAttribute("password", (String) _params.get("password"));
    }

    // Output some default (dummy) reconciliation store info
    Element store = catalog.addElement("store");
    store.addElement("update").addAttribute("type", "bdb").addAttribute("hostname", "localhost")
            .addAttribute("port", "777");
    store.addElement("state").addAttribute("type", "hash");

    // Output trust conditions saying that everyone trusts everyone
    for (int i = 0; i < peers.size(); i++) {
        if (null == peers.get(i)) {
            continue;
        }
        int j = peers.get(i);
        Element trustConditions = catalog.addElement("trustConditions").addAttribute("peer", "P" + i)
                .addAttribute("schema", "S" + j);
        for (int i2 = 0; i2 < peers.size(); i2++) {
            if (null == peers.get(i2)) {
                continue;
            }
            int j2 = peers.get(i2);
            if (i != i2) {
                for (int k2 = 0; k2 < schemas.get(j2).size(); k2++) {
                    trustConditions.addElement("trusts").addAttribute("pid", "P" + i2)
                            .addAttribute("pidType", "STRING").addAttribute("pidType", "STRING")
                            .addAttribute("priority", "5")
                            .addAttribute("relation", WorkloadGeneratorUtils.relname(i2, j2, k2));
                }
            }
        }
    }

    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = new XMLWriter(writer, format);
        xmlWriter.write(document);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new IllegalStateException("Problem writing schema file.", e);
    }
}

From source file:edu.vt.middleware.ldap.dsml.AbstractDsml.java

License:Open Source License

/**
 * This will take an attribute name and it's values and return a DSML
 * attribute element./*from   ww  w  .j  a va  2 s.c om*/
 *
 * @param  attrName  <code>String</code>
 * @param  attrValues  <code>Set</code>
 * @param  ns  <code>Namespace</code> of DSML
 * @param  elementName  <code>String</code> of the attribute element
 * @param  elementAttrName  <code>String</code> of the attribute element
 * @param  elementValueName  <code>String</code> of the value element
 *
 * @return  <code>Element</code>
 */
protected Element createDsmlAttribute(final String attrName, final Set<?> attrValues, final Namespace ns,
        final String elementName, final String elementAttrName, final String elementValueName) {
    final Element attrElement = DocumentHelper.createElement("");

    if (attrName != null) {

        attrElement.setQName(new QName(elementName, ns));
        if (elementAttrName != null) {
            attrElement.addAttribute(elementAttrName, attrName);
        }
        if (attrValues != null) {
            final Iterator<?> i = attrValues.iterator();
            while (i.hasNext()) {
                final Object rawValue = i.next();
                String value = null;
                boolean isBase64 = false;
                if (rawValue instanceof String) {
                    value = (String) rawValue;
                } else if (rawValue instanceof byte[]) {
                    value = LdapUtil.base64Encode((byte[]) rawValue);
                    isBase64 = true;
                } else {
                    if (this.logger.isWarnEnabled()) {
                        this.logger.warn("Could not cast attribute value as a byte[]" + " or a String");
                    }
                }
                if (value != null) {
                    final Element valueElement = attrElement.addElement(new QName(elementValueName, ns));
                    valueElement.addText(value);
                    if (isBase64) {
                        valueElement.addAttribute("encoding", "base64");
                    }
                }
            }
        }
    }

    return attrElement;
}

From source file:eml.studio.server.oozie.workflow.ActionNodeDef.java

License:Open Source License

protected void generateElement(Element root, String tag, String content) {
    if (content == null)
        content = "";
    Element ele = root.addElement(tag);
    ele.addText(content);
}

From source file:eml.studio.server.oozie.workflow.EndNodeDef.java

License:Open Source License

@Override
public void append2XML(Element root) {
    Element kill = root.addElement("kill");
    Element msg = kill.addElement("message");
    msg.addText("Map/Reduce failed, error message[${wf:errorMessage(wf:lastErrorNode())}]");
    kill.addAttribute("name", "fail");

    Element end = root.addElement("end");
    end.addAttribute("name", getName());
}

From source file:eml.studio.server.oozie.workflow.WFGraph.java

License:Open Source License

public static void main(String args[]) {

    Namespace rootNs = new Namespace("", "uri:oozie:workflow:0.4"); // root namespace uri
    QName rootQName = QName.get("workflow-app", rootNs); // your root element's name
    Element workflow = DocumentHelper.createElement(rootQName);
    Document doc = DocumentHelper.createDocument(workflow);

    workflow.addAttribute("name", "test");
    Element test = workflow.addElement("test");
    test.addText("hello");
    OutputFormat outputFormat = OutputFormat.createPrettyPrint();
    outputFormat.setEncoding("UTF-8");
    outputFormat.setIndent(true);/*from  w  w w .  ja  va2  s  .  c om*/
    outputFormat.setIndent("    ");
    outputFormat.setNewlines(true);
    try {
        StringWriter stringWriter = new StringWriter();
        XMLWriter xmlWriter = new XMLWriter(stringWriter);
        xmlWriter.write(doc);
        xmlWriter.close();
        System.out.println(doc.asXML());
        System.out.println(stringWriter.toString().trim());

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:eu.planets_project.pp.plato.xml.LibraryExport.java

License:Open Source License

/**
 * TODO: move this to a dom4j utility library, it is copied from
 * {@link ProjectExporter}/*w w  w .ja va 2 s.  co  m*/
 * 
 * Long strings are stored as XML-elements, not as attributes.
 * It is not possible to add an element with value <code>null</code>,
 * therefore this has to be handled here:
 * A new element is only added if there is a value at all.
 *
 * @param parent
 * @param name
 * @param value
 */
private Element addStringElement(Element parent, String name, String value) {
    Element e = null;
    // &&(!"".equals(value)
    if (value != null) {
        e = parent.addElement(name);
        if (!"".equals(value)) {
            e.addText(value);
        }
    }
    return e;
}

From source file:eu.sisob.uma.NPL.Researchers.TextMiningParserGateDetector.java

License:Open Source License

/**
 * Define annotator collector acoording index
 * I_TYPE_CONTENT_ENTIRE_WEB_PAGE => Extract info from CV and personal web page of researchers
 * @param lstAnnColl_ list of annotator collector
 *//*from  www .  j  a  v  a 2 s. c om*/
@Override
protected void iniAnnotatorCollectors(TreeMap lstAnnColl_) {
    AnnotatorCollector a = null;

    a = new AnnotatorCollector(DataExchangeLiterals.ID_TEXTMININGPARSER_GATERESEARCHER_DEFAULTANNREC) {
        @Override
        public void collect(Object doc, MiddleData aoData) {
            org.dom4j.Element eOut = org.dom4j.DocumentFactory.getInstance().createElement("blockinfo");
            eOut.addAttribute(DataExchangeLiterals.MIDDLE_ELEMENT_XML_ID_ANNOTATIONRECOLLECTING,
                    aoData.getId_annotationrecollecting()); // aoData[MiddleData.I_INDEX_DATA_TYPE].toString());
            eOut.addAttribute(DataExchangeLiterals.MIDDLE_ELEMENT_XML_ID_ENTITY_ATT, aoData.getId_entity()); // aoData[MiddleData.I_INDEX_DATA_ID].toString());

            gate.Document docGate = (gate.Document) doc;
            AnnotationSet annoset = docGate.getAnnotations();
            List<Annotation> anns = new ArrayList<Annotation>();

            //Expressions
            //anns.addAll(annoset.get("JobTitleTest"));
            //anns.addAll(annoset.get("DegreeTest"));
            anns.addAll(annoset.get("OrgTest"));

            //Collections.sort(anns, new OffsetBeginEndComparator());

            //need to bee order
            if (anns.size() > 0) {
                for (Annotation an : anns) {
                    String cvnItemName = an.getType();
                    org.dom4j.Element eAux = new org.dom4j.DocumentFactory().createElement(cvnItemName);
                    //eAux.addElement("Domain").addText(gate.Utils.stringFor(docGate,
                    //                                  an.getStartNode().getOffset() > 100 ? an.getStartNode().getOffset() - 100 : an.getStartNode().getOffset(),
                    //                                  an.getEndNode().getOffset() + 100 < docGate.getContent().size() ? an.getEndNode().getOffset() + 100 :  an.getEndNode().getOffset()));
                    eAux.addText(gate.Utils.stringFor(docGate, an));
                    eOut.add(eAux);
                }
            }

            Logger.getLogger("MyLog").info(String.format("%3d expressions in %s : ",
                    eOut != null ? eOut.elements().size() : 0, docGate.getSourceUrl())); // + docXML.asXML()

            aoData.setData_out(eOut);
        }
    };
    lstAnnColl_.put(a.type, a);
}