Example usage for org.dom4j Element createCopy

List of usage examples for org.dom4j Element createCopy

Introduction

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

Prototype

Element createCopy();

Source Link

Document

Creates a deep copy of this element The new element is detached from its parent, and getParent() on the clone will return null.

Usage

From source file:cc.warlock.core.configuration.WarlockConfiguration.java

License:Open Source License

public void save() {
    Document document = DocumentHelper.createDocument();
    Element warlockConfig = DocumentHelper.createElement("warlock-config");

    document.setRootElement(warlockConfig);

    for (IConfigurationProvider provider : providers) {
        List<Element> elements = provider.getTopLevelElements();

        for (Element element : elements) {
            warlockConfig.add(element);//from  w  w  w .j  a v  a  2 s . c om
        }
    }

    for (Element unhandled : unhandledElements) {
        // Make sure to resave unhandled elements, just in case the corresponding handler wasn't instantiated
        warlockConfig.add(unhandled.createCopy());
    }

    try {
        if (configFile.exists()) {
            File backupFile = new File(configFile.getPath() + ".bak");
            if (backupFile.exists())
                backupFile.renameTo(new File(backupFile.getPath() + ".1"));
            configFile.renameTo(backupFile);
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        FileOutputStream stream = new FileOutputStream(configFile);
        XMLWriter writer = new XMLWriter(stream, format);
        writer.write(document);
        stream.close();

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:ch.javasoft.xml.config.XmlConfig.java

License:BSD License

@SuppressWarnings("unchecked")
public Document getConfigDocument(String name) throws XmlConfigException {
    if (name == null)
        throw new NullPointerException("name argument is required");
    Iterator<Element> it = getRootElement().elementIterator(XmlElement.config.getXmlName());
    while (it.hasNext()) {
        Element cfg = it.next();
        String cfgName = cfg.attributeValue(XmlAttribute.name.getXmlName());
        if (name.equals(cfgName)) {
            final Element copy = cfg.createCopy();
            List<Element> resolved = resolve(copy, XmlUtil.getElementPath(copy, false /*recurseParents*/));
            if (resolved.size() != 1) {
                throw new XmlConfigException("resolved config not unique", cfg);
            }/* www . ja  va 2  s  .c o  m*/
            return createDocument(resolved.get(0), name);
        }
    }
    throw new IllegalArgumentException("no such config: " + name);
}

From source file:ch.javasoft.xml.config.XmlConfig.java

License:BSD License

@SuppressWarnings("unchecked")
protected List<Element> resolve(Element element, String path) throws XmlConfigException {
    final List<Element> resolved = new ArrayList<Element>();
    Attribute refAtt = element.attribute(XmlAttribute.ref.getXmlName());
    if (refAtt == null) {
        resolved.add(element);//from   w ww .j  a  v  a2s  . c  o m
    } else {
        resolveAttributeValue(refAtt, path);
        List<Element> refElCont = getReferredElementContent(refAtt.getValue(), path);
        for (final Element el : refElCont) {
            final Element newEl = el.createCopy();
            element.getParent().add(newEl);
            resolved.addAll(resolve(newEl, XmlUtil.getElementPath(el, true/*recurseParents*/)));
        }
        if (!element.getParent().remove(element)) {
            throw new RuntimeException("internal error: should have been removed");
        }
    }

    for (Element elem : resolved) {
        Iterator<Attribute> itA = elem.attributeIterator();
        while (itA.hasNext()) {
            Attribute att = itA.next();
            resolveAttributeValue(att, path);
        }

        //         resolve(elem.elementIterator(), path);
        Iterator<Element> itE = elem.elementIterator();
        while (itE.hasNext()) {
            Element child = itE.next();
            resolve(child, path + "/" + XmlUtil.getElementPath(child, false /*recurseParents*/));
        }
        if (elem.attribute(XmlAttribute.ref.getXmlName()) != null) {
            throw new RuntimeException("internal error: should have been resolved");
        }
    }
    return resolved;
}

From source file:ch.javasoft.xml.config.XmlConfig.java

License:BSD License

@SuppressWarnings("unchecked")
private void printUsageLines(PrintStream stream, Iterator<Element> usageChildIt) throws XmlConfigException {
    while (usageChildIt.hasNext()) {
        Element el = usageChildIt.next();
        if (XmlUtil.isExpectedElementName(el, XmlElement.line)) {
            Element copy = el.createCopy();
            List<Element> res = resolve(copy, XmlUtil.getElementPath(copy, true /*recurseParents*/));
            for (Element r : res) {
                stream.println(r.attributeValue(XmlAttribute.value.getXmlName()));
            }/*from w ww  .  j  a v a  2s .  co m*/
        } else if (XmlUtil.isExpectedElementName(el, XmlElement.usage)) {
            Element parentCopy = el.getParent().createCopy();
            Element copy = el.createCopy();
            parentCopy.add(copy);
            List<Element> res = resolve(copy, XmlUtil.getElementPath(copy, true /*recurseParents*/));
            for (Element r : res) {
                printUsageLines(stream, r.elementIterator());
            }
        }

    }
}

From source file:com.adspore.splat.xep0060.PubSubEngine.java

License:Open Source License

private static IQ getSubscriptionConfiguration(PubSubService service, IQ iq, Element childElement,
        Element optionsElement) {
    String nodeID = optionsElement.attributeValue("node");
    String subID = optionsElement.attributeValue("subid");
    Node node;/* w w  w. jav a2s .  c  om*/
    if (nodeID == null) {
        if (service.isCollectionNodesSupported()) {
            // Entity requests subscription options of root collection node
            node = service.getRootCollectionNode();
        } else {
            // Service does not have a root collection node so return a nodeid-required error
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("nodeid-required", "http://jabber.org/protocol/pubsub#errors"));
            return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
        }
    } else {
        // Look for the specified node
        node = service.getNode(nodeID);
        if (node == null) {
            // Node does not exist. Return item-not-found error
            return createErrorPacket(iq, PacketError.Condition.item_not_found, null);
        }
    }
    NodeSubscription subscription;
    if (node.isMultipleSubscriptionsEnabled()) {
        if (subID == null) {
            // No subid was specified and the node supports multiple subscriptions
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("subid-required", "http://jabber.org/protocol/pubsub#errors"));
            return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
        } else {
            // Check if the specified subID belongs to an existing node subscription
            subscription = node.getSubscription(subID);
            if (subscription == null) {
                Element pubsubError = DocumentHelper
                        .createElement(QName.get("invalid-subid", "http://jabber.org/protocol/pubsub#errors"));
                return createErrorPacket(iq, PacketError.Condition.not_acceptable, pubsubError);
            }
        }
    } else {
        // Check if the specified JID has a subscription with the node
        String jidAttribute = optionsElement.attributeValue("jid");
        if (jidAttribute == null) {
            // No JID was specified so return an error indicating that jid is required
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("jid-required", "http://jabber.org/protocol/pubsub#errors"));
            return createErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
        }
        JID subscriberJID = new JID(jidAttribute);
        subscription = node.getSubscription(subscriberJID);
        if (subscription == null) {
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("not-subscribed", "http://jabber.org/protocol/pubsub#errors"));
            return createErrorPacket(iq, PacketError.Condition.unexpected_request, pubsubError);
        }
    }

    // A subscription was found so check if the user is allowed to get the subscription options
    if (!subscription.canModify(iq.getFrom())) {
        // Requestor is prohibited from getting the subscription options
        return createErrorPacket(iq, PacketError.Condition.forbidden, null);
    }

    // Return data form containing subscription configuration to the subscriber
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    replyChildElement.element("options").add(subscription.getConfigurationForm().getElement());
    return reply;
}

From source file:com.adspore.splat.xep0060.PubSubEngine.java

License:Open Source License

private static IQ getSubscriptions(PubSubService service, IQ iq, Element childElement) {
    // TODO Assuming that owner is the bare JID (as defined in the JEP). This can be replaced with an explicit owner specified in the packet
    JID owner = new JID(iq.getFrom().getNode(), iq.getFrom().getDomain(), null, true);
    Element subscriptionsElement = childElement.element("subscriptions");

    String nodeID = subscriptionsElement.attributeValue("node");
    Collection<NodeSubscription> subscriptions = new ArrayList<NodeSubscription>();

    if (nodeID == null) {
        // Collect subscriptions of owner for all nodes at the service
        for (Node node : service.getNodes()) {
            subscriptions.addAll(node.getSubscriptions(owner));
        }//from  w ww .j a v a  2s  .  c o  m
    } else {
        subscriptions.addAll(service.getNode(nodeID).getSubscriptions(owner));
    }

    // Create reply to send
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    Element affiliationsElement = replyChildElement.element("subscriptions");
    // Add information about subscriptions including existing affiliations
    for (NodeSubscription subscription : subscriptions) {
        Element subElement = affiliationsElement.addElement("subscription");
        Node node = subscription.getNode();
        NodeAffiliate nodeAffiliate = subscription.getAffiliate();
        // Do not include the node id when node is the root collection node
        // or the results are for a specific node
        if (!node.isRootCollectionNode() && (nodeID == null)) {
            subElement.addAttribute("node", node.getNodeID());
        }
        subElement.addAttribute("jid", subscription.getJID().toString());
        subElement.addAttribute("subscription", subscription.getState().name());
        if (node.isMultipleSubscriptionsEnabled()) {
            subElement.addAttribute("subid", subscription.getID());
        }
    }
    return reply;
}

From source file:com.adspore.splat.xep0060.PubSubEngine.java

License:Open Source License

private static IQ getAffiliations(PubSubService service, IQ iq, Element childElement) {
    // TODO Assuming that owner is the bare JID (as defined in the JEP). This can be replaced with an explicit owner specified in the packet
    JID owner = new JID(iq.getFrom().getNode(), iq.getFrom().getDomain(), null, true);
    // Collect affiliations of owner for all nodes at the service
    Collection<NodeAffiliate> affiliations = new ArrayList<NodeAffiliate>();
    for (Node node : service.getNodes()) {
        NodeAffiliate nodeAffiliate = node.getAffiliate(owner);
        if (nodeAffiliate != null) {
            affiliations.add(nodeAffiliate);
        }/*ww w.ja v a 2  s .c  o  m*/
    }
    // Create reply to send
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    if (affiliations.isEmpty()) {
        // User does not have any affiliation or subscription with the pubsub service
        reply.setError(PacketError.Condition.item_not_found);
    } else {
        Element affiliationsElement = replyChildElement.element("affiliations");
        // Add information about affiliations without subscriptions
        for (NodeAffiliate affiliate : affiliations) {
            Element affiliateElement = affiliationsElement.addElement("affiliation");
            // Do not include the node id when node is the root collection node
            if (!affiliate.getNode().isRootCollectionNode()) {
                affiliateElement.addAttribute("node", affiliate.getNode().getNodeID());
            }
            affiliateElement.addAttribute("jid", affiliate.getJID().toString());
            affiliateElement.addAttribute("affiliation", affiliate.getAffiliation().name());
        }
    }
    return reply;
}

From source file:com.adspore.splat.xep0060.PubSubEngine.java

License:Open Source License

private static IQ getNodeConfiguration(PubSubService service, IQ iq, Element childElement, String nodeID) {
    Node node = service.getNode(nodeID);
    if (node == null) {
        // Node does not exist. Return item-not-found error
        return createErrorPacket(iq, PacketError.Condition.item_not_found, null);
    }//from www  . jav a 2  s.  co m
    if (!node.isAdmin(iq.getFrom())) {
        // Requesting entity is prohibited from configuring this node. Return forbidden error
        return createErrorPacket(iq, PacketError.Condition.forbidden, null);
    }

    // Return data form containing node configuration to the owner
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    replyChildElement.element("configure").add(node.getConfigurationForm().getElement());
    return reply;
}

From source file:com.adspore.splat.xep0060.PubSubEngine.java

License:Open Source License

private static IQ getDefaultNodeConfiguration(PubSubService service, IQ iq, Element childElement,
        Element defaultElement) {
    String type = defaultElement.attributeValue("type");
    type = type == null ? "leaf" : type;

    boolean isLeafType = "leaf".equals(type);
    DefaultNodeConfiguration config = service.getDefaultNodeConfiguration(isLeafType);
    if (config == null) {
        // Service does not support the requested node type so return an error
        Element pubsubError = DocumentHelper
                .createElement(QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", isLeafType ? "leaf" : "collections");
        return createErrorPacket(iq, PacketError.Condition.feature_not_implemented, pubsubError);
    }//from  w  w w  .ja va2 s  .  co m

    // Return data form containing default node configuration
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    replyChildElement.element("default").add(config.getConfigurationForm().getElement());
    return reply;
}

From source file:com.ctvit.vdp.services.sysconfiguration.user.UserService.java

/**
 * ?????XML/*from   w  w  w . j  a va 2s  .co m*/
 **/
public Map<String, String> getXML(Map xmlRightIds, Map thirdRightIds) throws DocumentException {
    String baseXML = systemConfigDao.selectByPrimaryKey("Rights").getValue();//??XML
    Document doc = DocumentHelper.parseText(baseXML);
    Document topDoc = DocumentHelper.createDocument();

    Element baseElement = doc.getRootElement();
    Element topEl = topDoc.addElement("Rights");//?XML
    List<Element> secMenuList = new ArrayList<Element>();
    String topIdFlag = "";

    Iterator elementIter = baseElement.elementIterator();
    while (elementIter.hasNext()) {//??
        Element element01 = (Element) elementIter.next();
        Iterator elementIter01 = element01.elementIterator();
        while (elementIter01.hasNext()) {//??
            Element element02 = (Element) elementIter01.next();
            Iterator elementIter02 = element02.elementIterator();
            String idFlag = "";
            if (xmlRightIds.get(element02.attributeValue("id")) != null) {//??ID?ID
                Element tempEl = element02.getParent();//?
                if (topEl.nodeCount() > 0 && !topIdFlag.equals(tempEl.attributeValue("id"))) {
                    topEl.addElement(tempEl.getName()).addAttribute("id", element01.attributeValue("id"))
                            .addAttribute("name", element01.attributeValue("name"));
                }
                if (topEl.nodeCount() == 0) {
                    topEl.addElement(tempEl.getName()).addAttribute("id", element01.attributeValue("id"))
                            .addAttribute("name", element01.attributeValue("name"));
                }
                topIdFlag = tempEl.attributeValue("id");
                secMenuList.add(element02);
            }
        }
    }

    StringBuffer secXML = new StringBuffer();
    secXML.append("<Rights>");
    Element tempTopEl = topEl.createCopy();
    //      System.out.println("tempTopEl: "+tempTopEl.asXML());
    Iterator secIt = tempTopEl.elementIterator();//????
    String flag = "";
    while (secIt.hasNext()) {
        Element op = (Element) secIt.next();
        for (Element eo : secMenuList) {//eo?? 
            if (eo.attributeValue("id").substring(0, 2).equals(op.attributeValue("id"))
                    && !flag.equals(eo.attributeValue("id"))) {
                flag = eo.attributeValue("id");
                Document secDoc = DocumentHelper.createDocument();
                Element secEle = secDoc.addElement("SecMenu");
                secEle.addAttribute("id", eo.attributeValue("id"));
                secEle.addAttribute("name", eo.attributeValue("name"));
                secEle.addAttribute("source", eo.attributeValue("source"));

                Iterator eoIter = eo.elementIterator();
                while (eoIter.hasNext()) {//??
                    Element thirdEl = (Element) eoIter.next();
                    if (thirdRightIds.get(thirdEl.attributeValue("id")) != null) {
                        Document document = DocumentHelper.createDocument();
                        Element tempEle = document.addElement("ThirdMenu");
                        tempEle.addAttribute("id", thirdEl.attributeValue("id"));
                        tempEle.addAttribute("name", thirdEl.attributeValue("name"));
                        tempEle.addAttribute("source", thirdEl.attributeValue("source"));
                        secEle.add(tempEle);//
                    }
                }
                op.add(secEle);//
            }
            //System.out.println("************ op: "+op.asXML());
        }
        secXML.append(op.asXML());
    }
    secXML.append("</Rights>");
    Map<String, String> xmlMap = new HashMap<String, String>();

    xmlMap.put("topMenu", topEl.asXML());
    xmlMap.put("treeMenu", secXML.toString());
    xmlMap.put("baseXML", baseElement.asXML());
    //      this.getElementList(baseElement,xmlRightIds);
    return xmlMap;
}