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:org.b5chat.crossfire.xmpp.disco.IQDiscoInfoHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) {
    // Create a copy of the sent pack that will be used as the reply
    // we only need to add the requested info to the reply if any otherwise add 
    // a not found error
    IQ reply = IQ.createResultIQ(packet);

    // Look for a IDiscoInfoProvider associated with the requested entity.
    // We consider the host of the recipient JID of the packet as the entity. It's the 
    // IDiscoInfoProvider responsibility to provide information about the JID's name together 
    // with any possible requested node.  
    IDiscoInfoProvider infoProvider = getProvider(
            packet.getTo() == null ? XmppServer.getInstance().getServerInfo().getXMPPDomain()
                    : packet.getTo().getDomain());
    if (infoProvider != null) {
        // Get the JID's name
        String name = packet.getTo() == null ? null : packet.getTo().getNode();
        if (name == null || name.trim().length() == 0) {
            name = null;/* w  w  w  .  java 2 s.  com*/
        }
        // Get the requested node
        Element iq = packet.getChildElement();
        String node = iq.attributeValue("node");
        //String node = metaData.getProperty("query:node");

        // Check if we have information about the requested name and node
        if (infoProvider.hasInfo(name, node, packet.getFrom())) {
            reply.setChildElement(iq.createCopy());
            Element queryElement = reply.getChildElement();

            // Add to the reply all the identities provided by the IDiscoInfoProvider
            Element identity;
            Iterator<Element> identities = infoProvider.getIdentities(name, node, packet.getFrom());
            while (identities.hasNext()) {
                identity = identities.next();
                identity.setQName(new QName(identity.getName(), queryElement.getNamespace()));
                queryElement.add((Element) identity.clone());
            }

            // Add to the reply all the features provided by the IDiscoInfoProvider
            Iterator<String> features = infoProvider.getFeatures(name, node, packet.getFrom());
            boolean hasDiscoInfoFeature = false;
            boolean hasDiscoItemsFeature = false;
            boolean hasResultSetManagementFeature = false;

            while (features.hasNext()) {
                final String feature = features.next();
                queryElement.addElement("feature").addAttribute("var", feature);
                if (feature.equals(NAMESPACE_DISCO_INFO)) {
                    hasDiscoInfoFeature = true;
                } else if (feature.equals("http://jabber.org/protocol/disco#items")) {
                    hasDiscoItemsFeature = true;
                } else if (feature.equals(ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)) {
                    hasResultSetManagementFeature = true;
                }
            }

            if (hasDiscoItemsFeature && !hasResultSetManagementFeature) {
                // IQDiscoItemsHandler provides result set management
                // support.
                queryElement.addElement("feature").addAttribute("var",
                        ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT);
            }

            if (!hasDiscoInfoFeature) {
                // XEP-0030 requires that every entity that supports service
                // discovery broadcasts the disco#info feature.
                queryElement.addElement("feature").addAttribute("var", NAMESPACE_DISCO_INFO);
            }

            // Add to the reply the extended info (XDataForm) provided by the IDiscoInfoProvider
            DataForm dataForm = infoProvider.getExtendedInfo(name, node, packet.getFrom());
            if (dataForm != null) {
                queryElement.add(dataForm.getElement());
            }
        } else {
            // If the IDiscoInfoProvider has no information for the requested name and node 
            // then answer a not found error
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.item_not_found);
        }
    } else {
        // If we didn't find a IDiscoInfoProvider then answer a not found error
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.item_not_found);
    }

    return reply;
}

From source file:org.b5chat.crossfire.xmpp.disco.IQDiscoItemsHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) {
    // Create a copy of the sent pack that will be used as the reply
    // we only need to add the requested items to the reply if any otherwise add 
    // a not found error
    IQ reply = IQ.createResultIQ(packet);

    // TODO Implement publishing client items
    if (IQ.Type.set == packet.getType()) {
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.feature_not_implemented);
        return reply;
    }/*from   w w w. ja  va2  s .c  om*/

    // Look for a IDiscoItemsProvider associated with the requested entity.
    // We consider the host of the recipient JID of the packet as the entity. It's the 
    // IDiscoItemsProvider responsibility to provide the items associated with the JID's name  
    // together with any possible requested node.
    IDiscoItemsProvider itemsProvider = getProvider(
            packet.getTo() == null ? XmppServer.getInstance().getServerInfo().getXMPPDomain()
                    : packet.getTo().getDomain());
    if (itemsProvider != null) {
        // Get the JID's name
        String name = packet.getTo() == null ? null : packet.getTo().getNode();
        if (name == null || name.trim().length() == 0) {
            name = null;
        }
        // Get the requested node
        Element iq = packet.getChildElement();
        String node = iq.attributeValue("node");

        // Check if we have items associated with the requested name and node
        Iterator<DiscoItem> itemsItr = itemsProvider.getItems(name, node, packet.getFrom());
        if (itemsItr != null) {
            reply.setChildElement(iq.createCopy());
            Element queryElement = reply.getChildElement();

            // See if the requesting entity would like to apply 'result set
            // management'
            final Element rsmElement = packet.getChildElement()
                    .element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));

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

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

                // Calculate which results to include.
                final List<DiscoItem> rsmResults;
                final List<DiscoItem> allItems = new ArrayList<DiscoItem>();
                while (itemsItr.hasNext()) {
                    allItems.add(itemsItr.next());
                }
                final ResultSet<DiscoItem> rs = new ResultSetImpl<DiscoItem>(allItems);
                try {
                    rsmResults = rs.applyRSMDirectives(rsmElement);
                } catch (NullPointerException e) {
                    final IQ itemNotFound = IQ.createResultIQ(packet);
                    itemNotFound.setError(PacketError.Condition.item_not_found);
                    return itemNotFound;
                }

                // add the applicable results to the IQ-result
                for (DiscoItem item : rsmResults) {
                    final Element resultElement = item.getElement();
                    resultElement.setQName(new QName(resultElement.getName(), queryElement.getNamespace()));
                    queryElement.add(resultElement.createCopy());
                }

                // overwrite the 'set' element.
                queryElement.remove(
                        queryElement.element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)));
                queryElement.add(rs.generateSetElementFromResults(rsmResults));
            } else {
                // don't apply RSM:
                // Add to the reply all the items provided by the IDiscoItemsProvider
                Element item;
                while (itemsItr.hasNext()) {
                    item = itemsItr.next().getElement();
                    item.setQName(new QName(item.getName(), queryElement.getNamespace()));
                    queryElement.add(item.createCopy());
                }
            }
        } else {
            // If the IDiscoItemsProvider has no items for the requested name and node 
            // then answer a not found error
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.item_not_found);
        }
    } else {
        // If we didn't find a IDiscoItemsProvider then answer a not found error
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.item_not_found);
    }

    return reply;
}

From source file:org.b5chat.crossfire.xmpp.privacy.PrivacyItem.java

License:Open Source License

PrivacyItem(Element itemElement) {
    this.allow = "allow".equals(itemElement.attributeValue("action"));
    this.order = Integer.parseInt(itemElement.attributeValue("order"));
    String typeAttribute = itemElement.attributeValue("type");
    if (typeAttribute != null) {
        this.type = Type.valueOf(typeAttribute);
        // Decode the proper value based on the rule type
        String value = itemElement.attributeValue("value");
        if (type == Type.jid) {
            // Decode the specified JID
            this.jidValue = new JID(value);
        } else if (type == Type.subscription) {
            // Decode the specified subscription type
            if ("both".equals(value)) {
                this.subscriptionValue = RosterItem.SUB_BOTH;
            } else if ("to".equals(value)) {
                this.subscriptionValue = RosterItem.SUB_TO;
            } else if ("from".equals(value)) {
                this.subscriptionValue = RosterItem.SUB_FROM;
            } else {
                this.subscriptionValue = RosterItem.SUB_NONE;
            }//from   ww  w  .java2  s  .  c o m
        } else {
            // Decode the specified group name
            this.groupValue = value;
        }
    }
    // Set what type of stanzas should be filters (i.e. blocked or allowed)
    this.filterIQ = itemElement.element("iq") != null;
    this.filterMessage = itemElement.element("message") != null;
    this.filterPresence_in = itemElement.element("presence-in") != null;
    this.filterPresence_out = itemElement.element("presence-out") != null;
    if (!filterIQ && !filterMessage && !filterPresence_in && !filterPresence_out) {
        // If none was defined then block all stanzas
        filterEverything = true;
    }
    // Keep a copy of the item element that defines this item
    this.itemElement = itemElement.createCopy();
}

From source file:org.collectionspace.services.id.IDResource.java

License:Educational Community License

/**
 * Appends detailed information about an ID generator instance,
 * to an element representing that ID generator instance.
 *
 * @param   instanceElement    An XML element representing an
 *                             ID generator instance.
 *
 * @param   generatorInstance  An instance of an ID generator.
 *
 * @return  The XML element representing an ID generator instance,
 *          with detailed information appended.
 *///w w w .ja  v  a  2  s  .c o  m
private Element appendDetailedIDGeneratorInformation(Element instanceElement,
        IDGeneratorInstance generatorInstance) {

    // Append description information.
    Element description = instanceElement.addElement("description");
    description.addText(generatorInstance.getDescription());

    // Append a representative, or sample, ID - of a type that
    // can be generated by this ID generator instance - for display.
    Element displayid = instanceElement.addElement("displayid");
    // Return the last generated ID as a representative ID.
    // If no ID has ever been generated by this ID generator instance,
    // return the current ID instead.
    //
    // @TODO This is a short-term kludge.  We may wish to instead
    // generate a static, sample ID, at system initialization
    // or launch time; or generate or load this value once, at the
    // time that an ID generator instance is created.
    String lastgenerated = generatorInstance.getLastGeneratedID();
    if (lastgenerated != null & !lastgenerated.trim().isEmpty()) {
        displayid.addText(lastgenerated);
    } else {
        SettableIDGenerator gen;
        try {
            gen = IDGeneratorSerializer.deserialize(generatorInstance.getGeneratorState());
            String current = gen.getCurrentID();
            if (current != null & !current.trim().isEmpty()) {
                displayid.addText(current);
            }
        } catch (Exception e) {
            // Do nothing here.
            // @TODO
            // Could potentially return an error message, akin to:
            // displayid.addText("No ID available for display");
        }
    }

    // Append components information.
    Element generator = instanceElement.addElement(ID_GENERATOR_COMPONENTS_NAME);
    // Get an XML string representation of the ID generator's components.
    String generatorStr = generatorInstance.getGeneratorState();
    // Convert the XML string representation of the ID generator's
    // components to a new XML document, copy its root element, and
    // append it to the relevant location within the current element.
    try {
        Document generatorDoc = XmlTools.textToXMLDocument(generatorStr);
        Element generatorRoot = generatorDoc.getRootElement();
        generator.add(generatorRoot.createCopy());
        // If an error occurs parsing the XML string representation,
        // the text of the components element will remain empty.
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Error parsing XML text: " + generatorStr);
        }
    }

    return instanceElement;
}

From source file:org.craftercms.cstudio.alfresco.dm.service.impl.DmContentTypeServiceImpl.java

License:Open Source License

/**
 * merge new elemetns from the template document to target document
 *
 * @param template/*from  w  w w . java2  s  .c  o  m*/
 * @param target
 */
@SuppressWarnings("unchecked")
protected void mergeTemplate(Document template, Document target, String templateVersion) {
    if (template != null && target != null) {
        Element root = template.getRootElement();
        Element targetRoot = target.getRootElement();
        List<Element> elements = root.elements();
        if (elements != null && elements.size() > 0) {
            for (Element element : elements) {
                String path = element.getName();
                List<Node> nodes = targetRoot.selectNodes(path);
                if (nodes != null && nodes.size() > 0) {
                    // for each existing element, walk down the structure and copy it over as needed
                    for (Node node : nodes) {
                        mergeChildElement(element, node);
                    }
                } else {
                    Element copiedElement = element.createCopy();
                    targetRoot.add(copiedElement);
                }
            }
        }
        // add the latest version label so it can be extracted when the content is saved
        Node versionNode = targetRoot.selectSingleNode(DmXmlConstants.ELM_TEMPLATE_VERSION);
        Element versionElement = (versionNode != null) ? (Element) versionNode
                : targetRoot.addElement(DmXmlConstants.ELM_TEMPLATE_VERSION);
        versionElement.setText(templateVersion);
    }
}

From source file:org.craftercms.cstudio.alfresco.dm.service.impl.DmContentTypeServiceImpl.java

License:Open Source License

/**
 * merge the given template child element to the node
 *
 * @param templateElement/*from  w  w w . j  ava  2s  . c  o m*/
 * @param targetNode
 */
@SuppressWarnings("unchecked")
protected void mergeChildElement(Element templateElement, Node targetNode) {
    List<Element> elements = templateElement.elements();
    if (elements != null && elements.size() > 0) {
        for (Element element : elements) {
            String path = element.getName();
            List<Node> nodes = targetNode.selectNodes(path);
            if (nodes != null && nodes.size() > 0) {
                for (Node childNode : nodes) {
                    mergeChildElement(element, childNode);
                }
            } else {
                Element copiedElement = element.createCopy();
                Element targetElement = (Element) targetNode;
                targetElement.add(copiedElement);
            }
        }
    }
}

From source file:org.esupportail.lecture.domain.model.ChannelConfig.java

/**
 * Check syntax file that cannot be checked by DTD.
 * @param xmlFileChecked/*from www . j  av a2s .  c  o  m*/
 * @return xmlFileLoading
 */
@SuppressWarnings("unchecked")
private synchronized static Document checkConfigFile(Document xmlFileChecked) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("checkXmlFile()");
    }
    // Merge categoryProfilesUrl and check number of contexts + categories
    Document xmlFileLoading = xmlFileChecked;
    Element channelConfig = xmlFileLoading.getRootElement();
    List<Element> contexts = channelConfig.selectNodes("context");
    nbContexts = contexts.size();
    if (nbContexts == 0) {
        LOG.warn("No context declared in channel config (esup-lecture.xml)");
    }

    // 1. merge categoryProfilesUrls and refCategoryProfile
    for (Element context : contexts) {
        List<Node> nodes = context.selectNodes("categoryProfilesUrl|refCategoryProfile");
        for (Node node : nodes) {
            //Is a refCategoryProfile ?
            if (node.getName().equals("refCategoryProfile")) {
                //remove from context (from its current place in original XML file)
                context.remove(node);
                //add to context (at the end of new constructed context: With merged refCategoryProfile from categoryProfilesUrl)
                context.add(node);
            } else {
                String categoryProfilesUrlPath = node.valueOf("@url");
                //URL url = ChannelConfig.class.getResource(categoryProfilesUrlPath);
                String idPrefix = node.valueOf("@idPrefix");
                if ((categoryProfilesUrlPath == null) || (categoryProfilesUrlPath == "")) {
                    String errorMsg = "URL of : categoryProfilesUrl with prefix " + idPrefix
                            + " is null or empty.";
                    LOG.warn(errorMsg);
                } else {
                    Document categoryProfilesFile = getFreshConfigFile(categoryProfilesUrlPath);
                    if (categoryProfilesFile == null) {
                        String errorMsg = "Impossible to load categoryProfilesUrl " + categoryProfilesUrlPath;
                        LOG.warn(errorMsg);
                    } else {
                        // merge one categoryProfilesUrl
                        // add categoryProfile
                        Element rootCategoryProfilesFile = categoryProfilesFile.getRootElement();
                        // replace ids with IdPrefix + "-" + id
                        List<Element> categoryProfiles = rootCategoryProfilesFile.elements();
                        for (Element categoryProfile : categoryProfiles) {
                            String categoryProfileId = idPrefix + "-" + categoryProfile.valueOf("@id");
                            //String categoryProfileName = categoryProfile.valueOf("@name");
                            categoryProfile.addAttribute("id", categoryProfileId);
                            Element categoryProfileAdded = categoryProfile.createCopy();
                            channelConfig.add(categoryProfileAdded);
                            // delete node categoryProfilesUrl ?
                            // add refCategoryProfile
                            context.addElement("refCategoryProfile").addAttribute("refId", categoryProfileId);
                        }
                    }
                }
                //remove now unneeded categoryProfilesUrl
                context.remove(node);
            }
        }
    }
    List<Node> categoryProfiles = channelConfig.selectNodes("categoryProfile");
    nbProfiles = categoryProfiles.size();
    if (nbProfiles == 0) {
        LOG.warn("checkXmlConfig :: No managed category profile declared in channel config");
    }
    return xmlFileLoading;

}

From source file:org.etudes.component.app.melete.MeleteAbstractExportServiceImpl.java

License:Apache License

/**
 * creates document root element "manifest" from the default manifest file
 * and adds the namespaces/*  www.j a  va  2s .  c  o  m*/
 * @param xmlFile - Default manifest file
 * @return returns the manifest element
 * @throws  Exception
 */
public Element getManifest(File xmlFile) throws Exception {
    try {
        Document document = XMLHelper.getSaxReader().read(xmlFile);
        Element root = document.getRootElement();
        Element rootnew = root.createCopy();
        List childEleList = rootnew.elements();
        childEleList.clear();

        this.DEFAULT_NAMESPACE_URI = rootnew.getNamespaceURI();

        List nslist = rootnew.declaredNamespaces();

        for (int i = 0; i < nslist.size(); i++) {
            if (((Namespace) nslist.get(i)).getPrefix().equals("imsmd")) {
                setMetaDataNameSpace(((Namespace) nslist.get(i)).getURI());
                break;
            }
        }
        rootnew.addAttribute("identifier", "Manifest-" + getUUID());
        return rootnew;
    } catch (DocumentException de) {
        throw de;
    } catch (SAXException se) {
        throw se;
    } catch (Exception e) {
        throw e;
    }
}

From source file:org.etudes.component.app.melete.MeleteImportServiceImpl.java

License:Apache License

private org.dom4j.Element checkModuleItem(org.dom4j.Element eleItem, org.dom4j.Element eleParentOrganization)
        throws Exception {
    org.dom4j.Attribute identifierref = eleItem.attribute("identifierref");
    if (identifierref == null)
        return null;
    List elements = eleParentOrganization.elements();
    org.dom4j.Element newModuleElement = eleParentOrganization.addElement("item");
    for (Iterator iter = elements.iterator(); iter.hasNext();) {
        org.dom4j.Element e = (org.dom4j.Element) iter.next();
        newModuleElement.add(e.createCopy());
        eleParentOrganization.remove(e);
    }/* w  ww  . ja v  a 2s. c om*/
    return newModuleElement;
}

From source file:org.etudes.jforum.view.admin.ImportExportAction.java

License:Apache License

/**
 * creates document root element "manifest" from the default manifest file
 * and adds the namespaces/*from ww w.j a  v  a  2s . co  m*/
 * 
 * @param xmlFile
 *            - Default manifest file
 * @return returns the manifest element
 * @throws Exception
 */
private Element getManifest(File xmlFile) throws Exception {
    try {
        Document document = XMLHelper.getSaxReader().read(xmlFile);
        Element root = document.getRootElement();
        Element rootnew = root.createCopy();
        List childEleList = rootnew.elements();
        childEleList.clear();

        this.DEFAULT_NAMESPACE_URI = rootnew.getNamespaceURI();

        List nslist = rootnew.declaredNamespaces();

        for (int i = 0; i < nslist.size(); i++) {
            if (((Namespace) nslist.get(i)).getPrefix().equals("imsmd")) {
                this.IMSMD_NAMESPACE_URI = ((Namespace) nslist.get(i)).getURI();
                break;
            }
        }
        rootnew.addAttribute("identifier", "Manifest-" + IdManager.createUuid());
        return rootnew;
    } catch (DocumentException de) {
        throw de;
    } catch (SAXException se) {
        throw se;
    } catch (Exception e) {
        throw e;
    }
}