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:com.magnet.mmx.server.plugin.mmxmgmt.message.TopicMessageBuilder.java

License:Apache License

/**
 * <iq>/*from  w  w w  .java 2 s  . c  om*/
 * <pubsub>
 * <publish>
 * <item>
 * <mmx>
 * <p/>
 * </mmx>
 * </item>
 * </publish>
 * </pubsub>
 * </iq>
 *
 * @return
 */

public IQ build() {

    if (topicId == null) {
        throw new IllegalArgumentException("topicId needs to be specified");
    }

    IQ message = new IQ();

    String id = idGenerator.generateTopicMessageId(appId, topicId);
    String toAddress = "pubsub." + domain;
    JID from = buildFromJID(appEntity, domain);

    message.setType(IQ.Type.set);
    message.setID(id);
    message.setTo(toAddress);
    message.setFrom(from);

    Element pubsubElement = message.setChildElement(PUBSUB_NAME, PUBSUB_NS);
    Element publishElement = pubsubElement.addElement(PUBLISH_NAME);
    publishElement.addAttribute(ATTRIBUTE_NODE, topicId);
    Element itemElement = publishElement.addElement(ITEM_NAME);
    //we need to have an id attribute for the item element
    itemElement.addAttribute(Constants.XMPP_ATTR_ID, idGenerator.generateItemIdentifier(topicId));
    Element mmxElement = itemElement.addElement(Constants.MMX, Constants.MMX_NS_MSG_PAYLOAD);

    Element payloadElement = mmxElement.addElement(Constants.MMX_PAYLOAD);
    payloadElement.addAttribute(Constants.MMX_ATTR_CTYPE, request.getContentType());
    payloadElement.addAttribute(Constants.MMX_ATTR_MTYPE, request.getMessageType());

    String formattedDateTime = TimeUtil.toString(new Date(utcTime));
    payloadElement.addAttribute(Constants.MMX_ATTR_STAMP, formattedDateTime);
    String text = request.getContent();
    payloadElement.setText(text);
    payloadElement.addAttribute(Constants.MMX_ATTR_CHUNK, MessageBuilder.buildChunkAttributeValue(text));

    return message;
}

From source file:com.magnet.mmx.tsung.GenTestScript.java

License:Apache License

static String generateSendMessageStanza() {
    String fromJid = "%%_username%%@" + genSettings.servername + "/tsung";
    String toJid = "%%_tojid%%@" + genSettings.servername + "/tsung";
    Message message = new Message();
    message.setType(Type.chat);/*  ww w .  ja  v  a 2 s .co m*/
    message.getElement().addAttribute("from", fromJid);
    message.getElement().addAttribute("to", toJid);
    message.setID("%%ts_user_server:get_unique_id%%");

    // build up the MMX message packet extension
    Element element = message.addChildElement(Constants.MMX, Constants.MMX_NS_MSG_PAYLOAD);
    element.addElement(Constants.MMX_META);
    Element payload = element.addElement(Constants.MMX_PAYLOAD);
    payload.addAttribute(Constants.MMX_ATTR_CTYPE, "plain/text");
    payload.addAttribute(Constants.MMX_ATTR_MTYPE, "string");
    String randomText = "Considered an invitation do introduced sufficient understood instrument it. Of decisively friendship in as collecting at. No affixed be husband ye females brother garrets proceed. Least child who seven happy yet balls young. Discovery sweetness principle discourse shameless bed one excellent. Sentiments of surrounded friendship dispatched connection is he. Me or produce besides hastily up as pleased. Bore less when had and john shed hope. \n"
            + "\n"
            + "Barton waited twenty always repair in within we do. An delighted offending curiosity my is dashwoods at. Boy prosperous increasing surrounded companions her nor advantages sufficient put. John on time down give meet help as of. Him waiting and correct believe now cottage she another. Vexed six shy yet along learn maids her tiled. Through studied shyness evening bed him winding present. Become excuse hardly on my thirty it wanted. \n"
            + "\n"
            + "Six reached suppose our whether. Oh really by an manner sister so. One sportsman tolerably him extensive put she immediate. He abroad of cannot looked in. Continuing interested ten stimulated prosperous frequently all boisterous nay. Of oh really he extent horses wicket. \n"
            + "\n"
            + "Placing assured be if removed it besides on. Far shed each high read are men over day. Afraid we praise lively he suffer family estate is. Ample order up in of in ready. Timed blind had now those ought set often which. Or snug dull he show more true wish. No at many deny away miss evil. On in so indeed spirit an mother. Amounted old strictly but marianne admitted. People former is remove remain as. \n"
            + "\n"
            + "Little afraid its eat looked now. Very ye lady girl them good me make. It hardly cousin me always. An shortly village is raising we shewing replied. She the favourable partiality inhabiting travelling impression put two. His six are entreaties instrument acceptance unsatiable her. Amongst as or on herself chapter entered carried no. Sold old ten are quit lose deal his sent. You correct how sex several far distant believe journey parties. We shyness enquire uncivil affixed it carried to. \n"
            + "\n"
            + "Parish so enable innate in formed missed. Hand two was eat busy fail. Stand smart grave would in so. Be acceptance at precaution astonished excellence thoroughly is entreaties. Who decisively attachment has dispatched. Fruit defer in party me built under first. Forbade him but savings sending ham general. So play do in near park that pain. \n"
            + "\n"
            + "Needed feebly dining oh talked wisdom oppose at. Applauded use attempted strangers now are middleton concluded had. It is tried \uFEFFno added purse shall no on truth. Pleased anxious or as in by viewing forbade minutes prevent. Too leave had those get being led weeks blind. Had men rose from down lady able. Its son him ferrars proceed six parlors. Her say projection age announcing decisively men. Few gay sir those green men timed downs widow chief. Prevailed remainder may propriety can and. \n"
            + "\n"
            + "Seen you eyes son show. Far two unaffected one alteration apartments celebrated but middletons interested. Described deficient applauded consisted my me do. Passed edward two talent effect seemed engage six. On ye great do child sorry lived. Proceed cottage far letters ashamed get clothes day. Stairs regret at if matter to. On as needed almost at basket remain. By improved sensible servants children striking in surprise. \n"
            + "\n"
            + "Rendered her for put improved concerns his. Ladies bed wisdom theirs mrs men months set. Everything so dispatched as it increasing pianoforte. Hearing now saw perhaps minutes herself his. Of instantly excellent therefore difficult he northward. Joy green but least marry rapid quiet but. Way devonshire introduced expression saw travelling affronting. Her and effects affixed pretend account ten natural. Need eat week even yet that. Incommode delighted he resolving sportsmen do in listening. \n"
            + "\n"
            + "On recommend tolerably my belonging or am. Mutual has cannot beauty indeed now sussex merely you. It possible no husbands jennings ye offended packages pleasant he. Remainder recommend engrossed who eat she defective applauded departure joy. Get dissimilar not introduced day her apartments. Fully as taste he mr do smile abode every. Luckily offered article led lasting country minutes nor old. Happen people things oh is oppose up parish effect. Law handsome old outweigh humoured far appetite. \n"
            + "\n";
    payload.addText(StringEscapeUtils.escapeXml(randomText));
    return message.toXML().toString();
}

From source file:com.mindquarry.desktop.model.task.Task.java

License:Open Source License

public Document getContentAsXML() {
    Document doc = DocumentHelper.createDocument();
    Element task = doc.addElement("task"); //$NON-NLS-1$

    Element title = task.addElement("title"); //$NON-NLS-1$
    title.setText(getTitle());//from ww  w  . j  a  v a  2s  . co  m

    if ((getPriority() != null) && (!getPriority().equals(""))) { //$NON-NLS-1$
        Element priority = task.addElement("priority"); //$NON-NLS-1$
        priority.setText(getPriority());
    }
    if ((getSummary() != null) && (!getSummary().equals(""))) { //$NON-NLS-1$
        Element summary = task.addElement("summary"); //$NON-NLS-1$
        summary.setText(getSummary());
    }
    if ((getStatus() != null) && (!getStatus().equals(""))) { //$NON-NLS-1$
        Element status = task.addElement("status"); //$NON-NLS-1$
        status.setText(getStatus());
    }
    if ((getDate() != null) && (!getDate().equals(""))) { //$NON-NLS-1$
        Element date = task.addElement("date"); //$NON-NLS-1$
        date.setText(getDate());
    }
    if ((getDescription() != null) && (!getDescription().equals(""))) { //$NON-NLS-1$
        Element description = task.addElement("description"); //$NON-NLS-1$
        description.setText(getDescription());
    }
    if ((getTargetTime() != null) && (!getTargetTime().equals(""))) { //$NON-NLS-1$
        Element description = task.addElement("targettime"); //$NON-NLS-1$
        description.setText(getTargetTime());
    }
    if ((getActualTime() != null) && (!getActualTime().equals(""))) { //$NON-NLS-1$
        Element description = task.addElement("actualtime"); //$NON-NLS-1$
        description.setText(getActualTime());
    }
    if (people.size() > 0) {
        int count = 0;
        Element peopleEl = task.addElement("people"); //$NON-NLS-1$
        for (Person person : people) {
            Element itemEl = peopleEl.addElement("item"); //$NON-NLS-1$
            itemEl.addAttribute("position", String.valueOf(count)); //$NON-NLS-1$

            Element personEl = itemEl.addElement("person"); //$NON-NLS-1$
            personEl.addText(person.pid);
            Element roleEl = itemEl.addElement("role"); //$NON-NLS-1$
            roleEl.addText(person.role);

            count++;
        }
    }
    if (dependencies.size() > 0) {
        int count = 0;
        Element dependenciesEl = task.addElement("dependencies"); //$NON-NLS-1$
        for (Dependency dependency : dependencies) {
            Element itemEl = dependenciesEl.addElement("item"); //$NON-NLS-1$
            itemEl.addAttribute("position", String.valueOf(count)); //$NON-NLS-1$

            Element taskEl = itemEl.addElement("task"); //$NON-NLS-1$
            taskEl.addText(dependency.tid);
            Element roleEl = itemEl.addElement("role"); //$NON-NLS-1$
            roleEl.addText(dependency.role);

            count++;
        }
    }
    return doc;
}

From source file:com.nokia.ant.Database.java

License:Open Source License

/**
 * @param root// w w w.  j  a v a  2 s  . com
 * @param antFile
 * @throws DocumentException
 * @throws IOException
 */
private void parseAntFile(Element root, String antFile) throws DocumentException, IOException {
    log("Processing Ant file: " + antFile, Project.MSG_DEBUG);
    SAXReader xmlReader = new SAXReader();
    Document antDoc = xmlReader.read(new File(antFile));

    // Element targetElement =
    // DocumentHelper.createElement("target");
    Element projectElement = root.addElement("project");
    Element nameElement = projectElement.addElement("name");
    String projectName = antDoc.valueOf("/project/@name");

    nameElement.setText(projectName);
    // Element descriptionElement =
    // projectElement.addElement("description");

    String description = antDoc.valueOf("/project/description");
    insertDocumentation(projectElement, description);

    // descriptionElement.setText(description);

    if (!antFile.contains("antlib.xml") && description.equals("")) {
        log("Project has no comment: " + projectName, Project.MSG_WARN);
    }

    Element defaultElement = projectElement.addElement("default");
    defaultElement.setText(antDoc.valueOf("/project/@default"));

    // Project import statements
    List importNodes = antDoc.selectNodes("//import");
    for (Iterator iterator = importNodes.iterator(); iterator.hasNext();) {
        Element importCurrentNode = (Element) iterator.next();
        addTextElement(projectElement, "fileDependency", importCurrentNode.attributeValue("file"));
    }

    projectElement.addElement("pythonDependency");

    // Project exec statements
    List execNodes = antDoc.selectNodes("//exec//arg");
    for (Iterator iterator = execNodes.iterator(); iterator.hasNext();) {
        Element argNode = (Element) iterator.next();
        String argValue = argNode.attributeValue("value");

        if (argValue == null)
            argValue = argNode.attributeValue("line");

        if (argValue != null) {
            Pattern filePattern = Pattern.compile(".pl|.py|.bat|.xml|.txt");
            Matcher fileMatcher = filePattern.matcher(argValue);
            if (fileMatcher.find()) {
                addTextElement(projectElement, "fileDependency", argValue);
            }
        }
    }

    List targetNodes = antDoc.selectNodes("//target");
    for (Iterator iterator = targetNodes.iterator(); iterator.hasNext();) {
        Element targetNode = (Element) iterator.next();
        processTarget(targetNode, projectElement);
    }

    // Process macrodef and scriptdef tasks
    // TODO - maybe scriptdefs should be separate?
    List macroNodes = antDoc.selectNodes("//macrodef | //scriptdef");
    for (Iterator iterator = macroNodes.iterator(); iterator.hasNext();) {
        Element macroNode = (Element) iterator.next();
        processMacro(macroNode, projectElement, antFile);
    }

    // Project properties
    List propertyNodes = antDoc.selectNodes("//property");
    for (Iterator iterator = propertyNodes.iterator(); iterator.hasNext();) {
        Element propertyNode = (Element) iterator.next();
        processProperty(propertyNode, projectElement);
    }
}

From source file:com.nokia.ant.Database.java

License:Open Source License

private void processMacro(Element macroNode, Element outProjectNode, String antFile)
        throws IOException, DocumentException {
    String macroName = macroNode.attributeValue("name");
    log("Processing macro: " + macroName, Project.MSG_DEBUG);

    Element outmacroNode = outProjectNode.addElement("macro");
    addTextElement(outmacroNode, "name", macroNode.attributeValue("name"));
    addTextElement(outmacroNode, "description", macroNode.attributeValue("description"));

    // Add location
    // Project project = getProject();
    // Macro antmacro = (Macro) project.getTargets().get(macroName);
    // System.out.println(project.getMacroDefinitions());
    // System.out.println(macroName);
    // MacroInstance antmacro = (MacroInstance)
    // project.getMacroDefinitions().get("http://www.nokia.com/helium:" +
    // macroName);

    // Add the location with just the file path for now and a dummy line
    // number.//from w  ww.  j  a v a  2s .  com
    // TODO - Later we should find the line number from the XML input.
    addTextElement(outmacroNode, "location", antFile + ":1:");

    List<Node> statements = macroNode.selectNodes("//scriptdef[@name='" + macroName
            + "']/attribute | //macrodef[@name='" + macroName + "']/attribute");
    String usage = "";
    for (Node statement : statements) {
        String defaultval = statement.valueOf("@default");
        if (defaultval.equals(""))
            defaultval = "value";
        else
            defaultval = "<i>" + defaultval + "</i>";
        usage = usage + " " + statement.valueOf("@name") + "=\"" + defaultval + "\"";
    }

    String macroElements = "";
    statements = macroNode.selectNodes(
            "//scriptdef[@name='" + macroName + "']/element | //macrodef[@name='" + macroName + "']/element");
    for (Node statement : statements) {
        macroElements = "&lt;" + statement.valueOf("@name") + "/&gt;\n" + macroElements;
    }
    if (macroElements.equals(""))
        addTextElement(outmacroNode, "usage", "&lt;hlm:" + macroName + " " + usage + "/&gt;");
    else
        addTextElement(outmacroNode, "usage", "&lt;hlm:" + macroName + " " + usage + "&gt;\n" + macroElements
                + "&lt;/hlm:" + macroName + "&gt;");

    // Add dependencies
    // Enumeration dependencies = antmacro.getDependencies();
    // while (dependencies.hasMoreElements())
    // {
    // String dependency = (String) dependencies.nextElement();
    // Element dependencyElement = addTextElement(outmacroNode,
    // "dependency", dependency);
    // dependencyElement.addAttribute("type","direct");
    // }

    callAntTargetVisitor(macroNode, outmacroNode, outProjectNode);

    // Add documentation
    // Get comment element before the macro element to extract macro doc
    List children = macroNode.selectNodes("preceding-sibling::node()");
    if (children.size() > 0) {
        // Scan past the text nodes, which are most likely whitespace
        int index = children.size() - 1;
        Node child = (Node) children.get(index);
        while (index > 0 && child.getNodeType() == Node.TEXT_NODE) {
            index--;
            child = (Node) children.get(index);
        }

        // Check if there is a comment node
        String commentText = null;
        if (child.getNodeType() == Node.COMMENT_NODE) {
            Comment macroComment = (Comment) child;
            commentText = macroComment.getStringValue().trim();
            log(macroName + " comment: " + commentText, Project.MSG_DEBUG);
        } else {
            log("Macro has no comment: " + macroName, Project.MSG_WARN);
        }

        insertDocumentation(outmacroNode, commentText);

        Node previousNode = (Node) children.get(children.size() - 1);
    }

    // Get names of all properties used in this macro
    ArrayList properties = new ArrayList();
    Visitor visitor = new AntPropertyVisitor(properties);
    macroNode.accept(visitor);
    for (Iterator iterator = properties.iterator(); iterator.hasNext();) {
        String property = (String) iterator.next();
        addTextElement(outmacroNode, "propertyDependency", property);
    }
}

From source file:com.nokia.ant.Database.java

License:Open Source License

private void processTarget(Element targetNode, Element outProjectNode) throws IOException, DocumentException {
    String targetName = targetNode.attributeValue("name");
    log("Processing target: " + targetName, Project.MSG_DEBUG);

    // Add documentation
    // Get comment element before the target element to extract target doc
    String commentText = "";
    List children = targetNode.selectNodes("preceding-sibling::node()");
    if (children.size() > 0) {
        // Scan past the text nodes, which are most likely whitespace
        int index = children.size() - 1;
        Node child = (Node) children.get(index);
        while (index > 0 && child.getNodeType() == Node.TEXT_NODE) {
            index--;//ww  w .j  a v  a 2s. co m
            child = (Node) children.get(index);
        }

        // Check if there is a comment node
        if (child.getNodeType() == Node.COMMENT_NODE) {
            Comment targetComment = (Comment) child;
            commentText = targetComment.getStringValue().trim();

            log(targetName + " comment: " + commentText, Project.MSG_DEBUG);
        } else {
            log("Target has no comment: " + targetName, Project.MSG_WARN);
        }

        Node previousNode = (Node) children.get(children.size() - 1);
    }

    if (!commentText.contains("Private:")) {
        Element outTargetNode = outProjectNode.addElement("target");

        addTextElement(outTargetNode, "name", targetNode.attributeValue("name"));
        addTextElement(outTargetNode, "ifDependency", targetNode.attributeValue("if"));
        addTextElement(outTargetNode, "unlessDependency", targetNode.attributeValue("unless"));
        addTextElement(outTargetNode, "description", targetNode.attributeValue("description"));
        addTextElement(outTargetNode, "tasks", String.valueOf(targetNode.elements().size()));

        // Add location
        Project project = getProject();
        Target antTarget = (Target) project.getTargets().get(targetName);

        if (antTarget == null)
            return;

        addTextElement(outTargetNode, "location", antTarget.getLocation().toString());

        // Add dependencies
        Enumeration dependencies = antTarget.getDependencies();
        while (dependencies.hasMoreElements()) {
            String dependency = (String) dependencies.nextElement();
            Element dependencyElement = addTextElement(outTargetNode, "dependency", dependency);
            dependencyElement.addAttribute("type", "direct");
        }

        callAntTargetVisitor(targetNode, outTargetNode, outProjectNode);

        // Process the comment text as MediaWiki syntax and convert to HTML
        insertDocumentation(outTargetNode, commentText);

        // Get names of all properties used in this target
        ArrayList properties = new ArrayList();
        Visitor visitor = new AntPropertyVisitor(properties);
        targetNode.accept(visitor);
        for (Iterator iterator = properties.iterator(); iterator.hasNext();) {
            String property = (String) iterator.next();
            addTextElement(outTargetNode, "propertyDependency", property);
        }

        // Add the raw XML content of the element
        String targetXml = targetNode.asXML();
        // Replace the CDATA end notation to avoid nested CDATA sections
        targetXml = targetXml.replace("]]>", "] ]>");

        addTextElement(outTargetNode, "source", targetXml, true);
    }
}

From source file:com.nokia.ant.Database.java

License:Open Source License

private void processProperty(Element propertyNode, Element outProjectNode) throws IOException {
    String propertyName = propertyNode.attributeValue("name");
    log("Processing Property: " + propertyName, Project.MSG_DEBUG);

    Element outPropertyNode = outProjectNode.addElement("property");
    addTextElement(outPropertyNode, "name", propertyNode.attributeValue("name"));
    if (propertyNode.attributeValue("value") == null) {
        addTextElement(outPropertyNode, "defaultValue", propertyNode.attributeValue("location"));
    } else {/*w ww. j a  v  a  2  s .  c o m*/
        addTextElement(outPropertyNode, "defaultValue", propertyNode.attributeValue("value"));
    }
}

From source file:com.nokia.ant.Database.java

License:Open Source License

private Element addTextElement(Element parent, String name, String text, boolean escape) {
    Element element = parent.addElement(name);
    if (text != null) {
        if (escape) {
            element.addCDATA(text);//w  w w.j a v  a 2 s  . c  om
        } else {
            element.setText(text);
        }
    }
    return element;
}

From source file:com.nokia.ant.Database.java

License:Open Source License

/**
 * Method adds taskdef nodes to the specified project.
 * /*w w w .  j  a va 2 s .co  m*/
 * @param outProjectNode
 * @throws IOException
 */
private void buildTaskDefs(Element root) throws DocumentException, IOException {
    Element projectElement = root.addElement("project");
    projectElement.addElement("name");
    insertDocumentation(projectElement, "");
    HashMap<String, String> tasks = getHeliumAntTasks();

    for (String taskName : tasks.keySet()) {
        String className = tasks.get(taskName);
        log("Processing TaskDef: " + taskName, Project.MSG_DEBUG);

        Element outTaskDefNode = projectElement.addElement("taskdef");
        addTextElement(outTaskDefNode, "name", taskName);
        addTextElement(outTaskDefNode, "classname", className);
    }
}

From source file:com.nokia.helium.environment.EnvironmentXMLWriter.java

License:Open Source License

private void write(Executable executable) {
    Element toolsNode = doc.getRootElement();
    Element toolNode = toolsNode.addElement("tool");
    toolNode.addElement("name").setText(executable.getName());
    toolNode.addElement("version").setText(getItem(executable.getVersion()));
    toolNode.addElement("path").setText(getItem(executable.getPath()));
    if (executable.getHash() != null) {
        toolNode.addElement("hash").setText(getItem(executable.getHash()));
        toolNode.addElement("length").setText(Long.toString(executable.getLength()));
        toolNode.addElement("lastModified").setText(Long.toString(executable.getLastModified()));
    }//w ww. j  a  v  a 2s .c om
    toolNode.addElement("executed").setText(Boolean.toString(executable.isExecuted()));
}