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:mesquite.lib.PhoneHomeUtil.java

License:Open Source License

public static void writePhoneRecords(String path, ListableVector phoneRecords) {
    if (StringUtil.blank(path))
        return;/*from  ww w.ja v  a  2  s  .co  m*/
    Element mesquiteElement = DocumentHelper.createElement("mesquite");
    Document doc = DocumentHelper.createDocument(mesquiteElement);
    Element phoneRecordElement = DocumentHelper.createElement("phoneRecords");
    mesquiteElement.add(phoneRecordElement);
    Element versionElement = DocumentHelper.createElement("version");
    versionElement.addText("1");
    phoneRecordElement.add(versionElement);

    for (int i = 0; i < phoneRecords.size(); i++) {
        Element recordElement = DocumentHelper.createElement("record");
        phoneRecordElement.add(recordElement);
        PhoneHomeRecord phoneRecord = (PhoneHomeRecord) phoneRecords.elementAt(i);
        Element element = DocumentHelper.createElement("module");
        element.add(DocumentHelper.createCDATA(phoneRecord.getModuleName()));
        recordElement.add(element);
        MesquiteModuleInfo mmi = MesquiteTrunk.mesquiteModulesInfoVector.findModule(MesquiteModule.class,
                phoneRecord.getModuleName());
        XMLUtil.addFilledElement(recordElement, "lastVersionUsed",
                MesquiteInteger.toString(phoneRecord.getLastVersionUsed()));
        XMLUtil.addFilledElement(recordElement, "lastNotice",
                MesquiteInteger.toString(phoneRecord.getLastNotice()));
        XMLUtil.addFilledElement(recordElement, "lastNoticeForMyVersion",
                MesquiteInteger.toString(phoneRecord.getLastNoticeForMyVersion()));
        XMLUtil.addFilledElement(recordElement, "lastVersionNoticed",
                MesquiteInteger.toString(phoneRecord.getLastVersionNoticed()));
        XMLUtil.addFilledElement(recordElement, "lastNewerVersionReported",
                MesquiteInteger.toString(phoneRecord.getLastNewerVersionReported()));
    }
    String xml = XMLUtil.getDocumentAsXMLString(doc);
    if (!StringUtil.blank(xml))
        MesquiteFile.putFileContents(path, xml, true);

}

From source file:mesquite.lib.XMLUtil.java

License:Open Source License

public static Element addFilledElement(Element containingElement, String name, String content) {
    if (content == null || name == null)
        return null;
    Element element = DocumentHelper.createElement(name);
    element.addText(content);/*from   ww  w . j av a 2 s  .  c  o  m*/
    containingElement.add(element);
    return element;
}

From source file:mesquite.lib.XMLUtil.java

License:Open Source License

public static Element addFilledElement(Element containingElement, String name, CDATA cdata) {
    if (cdata == null || name == null)
        return null;
    Element element = DocumentHelper.createElement(name);
    element.add(cdata);
    containingElement.add(element);//from   w  w  w  . j  a v  a  2 s.c om
    return element;
}

From source file:mesquite.minimal.Simplicity.Simplicity.java

License:Open Source License

public void renameSettingsFile(int i, String newName) {
    if (!MesquiteInteger.isCombinable(i) || i < 0 || i >= InterfaceManager.settingsFiles.size())
        return;/*from  w w w  .j a v a 2  s . co m*/
    StringArray s = (StringArray) InterfaceManager.settingsFiles.elementAt(i);
    String path = s.getValue(PATH);
    String settingsXML = s.getValue(XML);
    Element root = XMLUtil.getRootXMLElementFromString("mesquite", settingsXML);
    if (root == null)
        return;
    Element element = root.element("simplicitySettings");
    if (element != null) {
        Element versionElement = element.element("version");
        if (versionElement == null)
            return;
        else {
            int version = MesquiteInteger.fromString(element.elementText("version"));
            boolean acceptableVersion = version == 1;
            if (acceptableVersion) {
                Element name = element.element("name");

                Element settingsFile = DocumentHelper.createElement("mesquite");
                Document doc = DocumentHelper.createDocument(settingsFile);
                Element hidden = DocumentHelper.createElement("simplicitySettings");
                settingsFile.add(hidden);
                XMLUtil.addFilledElement(hidden, "version", "1");
                XMLUtil.addFilledElement(hidden, "name", newName);
                Element hp = element.element("hiddenPackages");
                element.remove(hp);
                hidden.add(hp);
                hp = element.element("hiddenMenuItems");
                element.remove(hp);
                hidden.add(hp);
                hp = element.element("hiddenTools");
                element.remove(hp);
                hidden.add(hp);
                s.setName(newName);
                MesquiteFile.putFileContents(path, XMLUtil.getDocumentAsXMLString(doc), false);
            }
        }
    }
}

From source file:mesquite.minimal.Simplicity.Simplicity.java

License:Open Source License

public String makeSettingsFile(String name) {
    Element settingsFile = DocumentHelper.createElement("mesquite");
    Document doc = DocumentHelper.createDocument(settingsFile);
    Element hidden = DocumentHelper.createElement("simplicitySettings");
    settingsFile.add(hidden);
    XMLUtil.addFilledElement(hidden, "version", "1");
    XMLUtil.addFilledElement(hidden, "name", name);

    Element hiddenPkgs = DocumentHelper.createElement("hiddenPackages");
    hidden.add(hiddenPkgs);//  w ww .j a v a 2s. c  om
    for (int i = 0; i < InterfaceManager.hiddenPackages.size(); i++) {
        MesquiteString ms = (MesquiteString) InterfaceManager.hiddenPackages.elementAt(i);
        Element elem = DocumentHelper.createElement("package");
        hiddenPkgs.add(elem);
        XMLUtil.addFilledElement(elem, "name", ms.getName());
    }

    Element hiddenMs = DocumentHelper.createElement("hiddenMenuItems");
    hidden.add(hiddenMs);
    for (int i = 0; i < InterfaceManager.hiddenMenuItems.size(); i++) {
        MenuVisibility mv = (MenuVisibility) InterfaceManager.hiddenMenuItems.elementAt(i);
        Element elem = DocumentHelper.createElement("menuItem");
        hiddenMs.add(elem);
        XMLUtil.addFilledElement(elem, "label", mv.label);
        if (mv.arguments != null)
            XMLUtil.addFilledElement(elem, "arguments", mv.arguments);
        XMLUtil.addFilledElement(elem, "command", mv.command);
        XMLUtil.addFilledElement(elem, "commandableClass", mv.commandableClassName);
        XMLUtil.addFilledElement(elem, "dutyClass", mv.dutyClass);
    }
    Element hiddenT = DocumentHelper.createElement("hiddenTools");
    hidden.add(hiddenT);
    for (int i = 0; i < InterfaceManager.hiddenTools.size(); i++) {
        MesquiteString s = (MesquiteString) InterfaceManager.hiddenTools.elementAt(i);
        Element elem = DocumentHelper.createElement("tool");
        hiddenT.add(elem);
        XMLUtil.addFilledElement(elem, "name", s.getName());
        XMLUtil.addFilledElement(elem, "description", s.getValue());
    }
    return XMLUtil.getDocumentAsXMLString(doc);
}

From source file:nc.noumea.mairie.organigramme.services.exportGraphML.impl.AbstractExportGraphMLService.java

License:Open Source License

/**
 * Initialise l entete du graphML//www.j  ava 2s .  c o  m
 * 
 * @param root
 *            Element
 */
protected void initHeader(Element root) {

    root.addAttribute("xmlns", "http://graphml.graphdrawing.org/xmlns");
    root.addAttribute("xsi:schemaLocation",
            "http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd");
    root.add(new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"));
    root.add(new Namespace("y", "http://www.yworks.com/xml/graphml"));
    root.addElement("key").addAttribute("yfiles.type", "nodegraphics").addAttribute("for", "node")
            .addAttribute("id", "d6");
    root.addElement("key").addAttribute("yfiles.type", "edgegraphics").addAttribute("for", "edge")
            .addAttribute("id", "d7");
    root.addElement("key").addAttribute("yfiles.type", "resources").addAttribute("for", "graphml")
            .addAttribute("id", "d13");
}

From source file:nc.noumea.mairie.organigramme.services.impl.ExportGraphMLServiceImpl.java

License:Open Source License

private void initHeader(Element root) {
    root.addAttribute("xmlns", "http://graphml.graphdrawing.org/xmlns");
    root.addAttribute("xsi:schemaLocation",
            "http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd");
    root.add(new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"));
    root.add(new Namespace("y", "http://www.yworks.com/xml/graphml"));
    root.addElement("key").addAttribute("attr.name", "sigle").addAttribute("attr.type", "string")
            .addAttribute("for", "node").addAttribute("id", "d4");
    root.addElement("key").addAttribute("attr.name", "label").addAttribute("attr.type", "string")
            .addAttribute("for", "node").addAttribute("id", "d5");
    root.addElement("key").addAttribute("yfiles.type", "nodegraphics").addAttribute("for", "node")
            .addAttribute("id", "d6");
    root.addElement("key").addAttribute("yfiles.type", "edgegraphics").addAttribute("for", "edge")
            .addAttribute("id", "d7");
}

From source file:net.contextfw.web.application.internal.WebResponder.java

License:Apache License

protected Document getXSLDocument() {

    List<ResourceEntry> rootResources = ResourceScanner.findResources(rootResourcePaths, XSL_ACCEPTOR);

    ResourceEntry root = null;/*from   w w w .  j a v  a  2  s.  c  om*/

    Iterator<ResourceEntry> iter = rootResources.iterator();
    if (iter != null) {
        while (iter.hasNext()) {
            ResourceEntry next = iter.next();
            if (next.getPath().endsWith("root.xsl")) {
                iter.remove();
                root = next;
                break;
            }
        }
    }

    if (root == null) {
        throw new InternalWebApplicationException("root.xsl was not found");
    }

    List<ResourceEntry> resources = ResourceScanner.findResources(resourcePaths, XSL_ACCEPTOR);

    InputStream stream;
    SAXReader reader = new SAXReader();
    try {
        stream = root.getInputStream();
        Document document = reader.read(stream);
        stream.close();
        for (KeyValue<String, String> entry : namespaces) {
            document.getRootElement().addNamespace(entry.getKey(), entry.getValue());
        }

        Element stylesheet = (Element) document.selectSingleNode("//stylesheet");

        // Adding other stylesheets

        for (ResourceEntry file : resources) {
            if (file.getPath().endsWith(".xsl")) {
                reader = new SAXReader();
                stream = file.getInputStream();

                try {
                    Document child = reader.read(stream);
                    for (Object el : child.getRootElement().elements()) {
                        if (el instanceof Node) {
                            stylesheet.add(((Node) el).detach());
                        }
                    }
                } catch (DocumentException de) {
                    transformers.invalidate();
                    throw new WebApplicationException("Xsl-file " + file.getPath() + " contains errors", de);
                } finally {
                    stream.close();
                }

            }
        }

        if (xslPostProcessor != null) {
            xslPostProcessor.process(document);
        }
        return document;
    } catch (DocumentException e) {
        throw new WebApplicationException(e);
    } catch (UnsupportedEncodingException e) {
        throw new WebApplicationException(e);
    } catch (IOException e) {
        throw new WebApplicationException(e);
    }
}

From source file:net.emiva.crossfire.plugin.muc.spi.IQMUCSearchHandler.java

License:Open Source License

/**
 * Utility method that returns a 'jabber:iq:search' child element filled
 * with a blank dataform.//from   w ww  .j  ava2 s .  c  o m
 * 
 * @return Element, named 'query', escaped by the 'jabber:iq:search'
 *         namespace, filled with a blank dataform.
 */
private static Element getDataElement() {
    final DataForm searchForm = new DataForm(DataForm.Type.form);
    searchForm.setTitle("Chat Rooms Search");
    searchForm.addInstruction("Instructions");

    final FormField typeFF = searchForm.addField();
    typeFF.setVariable("FORM_TYPE");
    typeFF.setType(FormField.Type.hidden);
    typeFF.addValue("jabber:iq:search");

    final FormField nameFF = searchForm.addField();
    nameFF.setVariable("name");
    nameFF.setType(FormField.Type.text_single);
    nameFF.setLabel("Name");
    nameFF.setRequired(false);

    final FormField matchFF = searchForm.addField();
    matchFF.setVariable("name_is_exact_match");
    matchFF.setType(FormField.Type.boolean_type);
    matchFF.setLabel("Name must match exactly");
    matchFF.setRequired(false);

    final FormField subjectFF = searchForm.addField();
    subjectFF.setVariable("subject");
    subjectFF.setType(FormField.Type.text_single);
    subjectFF.setLabel("Subject");
    subjectFF.setRequired(false);

    final FormField userAmountFF = searchForm.addField();
    userAmountFF.setVariable("num_users");
    userAmountFF.setType(FormField.Type.text_single);
    userAmountFF.setLabel("Number of users");
    userAmountFF.setRequired(false);

    final FormField maxUsersFF = searchForm.addField();
    maxUsersFF.setVariable("num_max_users");
    maxUsersFF.setType(FormField.Type.text_single);
    maxUsersFF.setLabel("Max number allowed of users");
    maxUsersFF.setRequired(false);

    final FormField includePasswordProtectedFF = searchForm.addField();
    includePasswordProtectedFF.setVariable("include_password_protected");
    includePasswordProtectedFF.setType(FormField.Type.boolean_type);
    includePasswordProtectedFF.setLabel("Include password protected rooms");
    includePasswordProtectedFF.setRequired(false);

    final Element probeResult = DocumentHelper.createElement(QName.get("query", "jabber:iq:search"));
    probeResult.add(searchForm.getElement());
    return probeResult;
}

From source file:net.emiva.crossfire.plugin.muc.spi.IQMUCSearchHandler.java

License:Open Source License

/**
 * Constructs an answer on a IQ stanza that contains a search request. The
 * answer will be an IQ stanza of type 'result' or 'error'.
 * /*from   w w  w . ja v a2s .co  m*/
 * @param iq
 *            The IQ stanza that is the search request.
 * @return An answer to the provided request.
 */
public IQ handleIQ(IQ iq) {
    final IQ reply = IQ.createResultIQ(iq);
    final Element formElement = iq.getChildElement().element(QName.get("x", "jabber:x:data"));
    if (formElement == null) {
        reply.setChildElement(getDataElement());
        return reply;
    }

    // parse params from request.
    final DataForm df = new DataForm(formElement);
    boolean name_is_exact_match = false;
    String subject = null;
    int numusers = -1;
    int numaxusers = -1;
    boolean includePasswordProtectedRooms = true;

    final Set<String> names = new HashSet<String>();
    for (final FormField field : df.getFields()) {
        if (field.getVariable().equals("name")) {
            names.add(field.getFirstValue());
        }
    }

    final FormField matchFF = df.getField("name_is_exact_match");
    if (matchFF != null) {
        final String b = matchFF.getFirstValue();
        if (b != null) {
            name_is_exact_match = b.equals("1") || b.equalsIgnoreCase("true") || b.equalsIgnoreCase("yes");
        }
    }

    final FormField subjectFF = df.getField("subject");
    if (subjectFF != null) {
        subject = subjectFF.getFirstValue();
    }

    try {
        final FormField userAmountFF = df.getField("num_users");
        if (userAmountFF != null) {
            String value = userAmountFF.getFirstValue();
            if (value != null && !"".equals(value)) {
                numusers = Integer.parseInt(value);
            }
        }

        final FormField maxUsersFF = df.getField("num_max_users");
        if (maxUsersFF != null) {
            String value = maxUsersFF.getFirstValue();
            if (value != null && !"".equals(value)) {
                numaxusers = Integer.parseInt(value);
            }
        }
    } catch (NumberFormatException e) {
        reply.setError(PacketError.Condition.bad_request);
        return reply;
    }

    final FormField includePasswordProtectedRoomsFF = df.getField("include_password_protected");
    if (includePasswordProtectedRoomsFF != null) {
        final String b = includePasswordProtectedRoomsFF.getFirstValue();
        if (b != null) {
            if (b.equals("0") || b.equalsIgnoreCase("false") || b.equalsIgnoreCase("no")) {
                includePasswordProtectedRooms = false;
            }
        }
    }

    // search for chatrooms matching the request params.
    final List<MUCRoom> mucs = new ArrayList<MUCRoom>();
    for (MUCRoom room : mucService.getChatRooms()) {
        boolean find = false;

        if (names.size() > 0) {
            for (final String name : names) {
                if (name_is_exact_match) {
                    if (name.equalsIgnoreCase(room.getNaturalLanguageName())) {
                        find = true;
                        break;
                    }
                } else {
                    if (room.getNaturalLanguageName().toLowerCase().indexOf(name.toLowerCase()) != -1) {
                        find = true;
                        break;
                    }
                }
            }
        }

        if (subject != null && room.getSubject().toLowerCase().indexOf(subject.toLowerCase()) != -1) {
            find = true;
        }

        if (numusers > -1 && room.getParticipants().size() < numusers) {
            find = false;
        }

        if (numaxusers > -1 && room.getMaxUsers() < numaxusers) {
            find = false;
        }

        if (!includePasswordProtectedRooms && room.isPasswordProtected()) {
            find = false;
        }

        if (find && canBeIncludedInResult(room)) {
            mucs.add(room);
        }
    }

    final ResultSet<MUCRoom> searchResults = new ResultSetImpl<MUCRoom>(sortByUserAmount(mucs));

    // See if the requesting entity would like to apply 'result set
    // management'
    final Element set = iq.getChildElement()
            .element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));
    final List<MUCRoom> mucrsm;

    // apply RSM only if the element exists, and the (total) results
    // set is not empty.
    final boolean applyRSM = set != null && !mucs.isEmpty();

    if (applyRSM) {
        if (!ResultSet.isValidRSMRequest(set)) {
            reply.setError(Condition.bad_request);
            return reply;
        }

        try {
            mucrsm = searchResults.applyRSMDirectives(set);
        } catch (NullPointerException e) {
            final IQ itemNotFound = IQ.createResultIQ(iq);
            itemNotFound.setError(Condition.item_not_found);
            return itemNotFound;
        }
    } else {
        // if no rsm, all found rooms are part of the result.
        mucrsm = new ArrayList<MUCRoom>(searchResults);
    }

    final Element res = DocumentHelper.createElement(QName.get("query", "jabber:iq:search"));

    final DataForm resultform = new DataForm(DataForm.Type.result);
    boolean atLeastoneResult = false;
    for (MUCRoom room : mucrsm) {
        final Map<String, Object> fields = new HashMap<String, Object>();
        fields.put("name", room.getNaturalLanguageName());
        fields.put("subject", room.getSubject());
        fields.put("num_users", room.getOccupantsCount());
        fields.put("num_max_users", room.getMaxUsers());
        fields.put("is_password_protected", room.isPasswordProtected());
        fields.put("is_member_only", room.isMembersOnly());
        fields.put("jid", room.getRole().getRoleAddress().toString());
        resultform.addItemFields(fields);
        atLeastoneResult = true;
    }
    if (atLeastoneResult) {
        resultform.addReportedField("name", "Name", FormField.Type.text_single);
        resultform.addReportedField("subject", "Subject", FormField.Type.text_single);
        resultform.addReportedField("num_users", "Number of users", FormField.Type.text_single);
        resultform.addReportedField("num_max_users", "Max number allowed of users", FormField.Type.text_single);
        resultform.addReportedField("is_password_protected", "Is a password protected room.",
                FormField.Type.boolean_type);
        resultform.addReportedField("is_member_only", "Is a member only room.", FormField.Type.boolean_type);
        resultform.addReportedField("jid", "JID", FormField.Type.jid_single);
    }
    res.add(resultform.getElement());
    if (applyRSM) {
        res.add(searchResults.generateSetElementFromResults(mucrsm));
    }

    reply.setChildElement(res);

    return reply;
}