Example usage for org.dom4j Element remove

List of usage examples for org.dom4j Element remove

Introduction

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

Prototype

boolean remove(Text text);

Source Link

Document

Removes the given Text if the node is an immediate child of this element.

Usage

From source file:org.jage.platform.config.xml.loaders.NestedDefinitionsHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
private void extractFromConstructorsAndProperties(final Document document) throws ConfigurationException {
    for (final Element element : (List<Element>) CTR_PROP_XPATH.selectNodes(document)) {
        final Element ctrOrPropElement = element.getParent();
        final Element componentElement = ctrOrPropElement.getParent();

        // first we replace the element with a reference one
        final String nameAttribute = getRequiredAttribute(element, ConfigAttributes.NAME);
        ctrOrPropElement.remove(element);
        ctrOrPropElement.add(newReferenceElement(nameAttribute));

        // then we append it after the parent element
        final int index = componentElement.elements().indexOf(ctrOrPropElement);
        componentElement.elements().add(index + 1, element);
    }/*from  www  .  j  ava 2 s  .  com*/
}

From source file:org.jage.platform.config.xml.loaders.NestedDefinitionsHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
private void extractFromMaps(final Document document) {
    // We extract from keys later, so that their definitions come first, after the entry itself

    for (final Element element : selectNodes(ENTRY_XPATH, document)) {
        final Element entryElement = element.getParent();
        final Element mapElement = entryElement.getParent();

        // first we replace the element with a reference one
        final String nameAttribute = element.attributeValue(ConfigAttributes.NAME.toString());
        entryElement.remove(element);
        entryElement.add(newReferenceElement(nameAttribute));

        // then we append it after the entry element
        final int index = mapElement.elements().indexOf(entryElement);
        mapElement.elements().add(index + 1, element);
    }//  ww  w  .j  a v a 2  s .co  m

    for (final Element element : selectNodes(KEY_XPATH, document)) {
        final Element keyElement = element.getParent();
        final Element entryElement = keyElement.getParent();
        final Element mapElement = entryElement.getParent();

        // first we replace the element with a reference one
        final String nameAttribute = element.attributeValue(ConfigAttributes.NAME.toString());
        keyElement.remove(element);
        keyElement.add(newReferenceElement(nameAttribute));

        // then we append it after the entry element
        final int index = mapElement.elements().indexOf(entryElement);
        mapElement.elements().add(index + 1, element);
    }
}

From source file:org.jasig.portal.tools.chanpub.UrlChannelPublisher.java

License:Open Source License

public static void publishChannel(Element m) {

    try {/*from  w  w  w.  j a v a  2  s.  c o m*/

        RDBMServices.setGetDatasourceFromJndi(false);

        m.remove(m.attribute("script"));
        Document d = m.getDocument();
        d.addDocType("channel-definition", null, "channelDefinition.dtd");

        String xml = d.asXML();
        InputStream inpt = new ByteArrayInputStream(xml.getBytes());
        ChannelPublisher pub = ChannelPublisher.getCommandLineInstance();
        pub.publishChannel(inpt);

    } catch (Throwable t) {
        String msg = "Error publishing the channel definition.";
        throw new RuntimeException(msg, t);
    }

}

From source file:org.jdbcluster.filter.ClusterSelectImpl.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//w w  w  . j  a v  a  2s . c o m
public void addExtension(String extensionPath) {
    try {
        Document doc = read(extensionPath);
        String xPathClusterType = "//jdbcluster/clustertype";
        String xPath = "//jdbcluster/clustertype/cluster";
        String xPathExtension = "//clustertype/cluster";

        List<Element> nodes = doc.selectNodes(xPathExtension);
        List<Element> rootNodes = document.selectNodes(xPath);
        Element clusterType = (Element) document.selectSingleNode(xPathClusterType);

        for (Element node : nodes) {
            for (Element rootNode : rootNodes) {
                String clusterExtensionName = node.valueOf("@id");
                String clusterRootName = rootNode.valueOf("@id");
                String nodeExistenceXPath = "//jdbcluster/clustertype/cluster[@id='" + clusterExtensionName
                        + "']";
                Node node2 = document.selectSingleNode(nodeExistenceXPath);
                if (node2 == null) {
                    node.detach();
                    clusterType.add(node);
                    break;
                } else if (clusterRootName.equals(clusterExtensionName)) {
                    String xPathFilter = "//jdbcluster/clustertype/cluster[@id='" + clusterRootName + "']"
                            + "/select";
                    String xPathFilterExtensions = "//clustertype/cluster[@id='" + clusterRootName + "']"
                            + "/select";
                    List<Element> extensionFilterNodes = doc.selectNodes(xPathFilterExtensions);
                    List<Element> filterNodes = document.selectNodes(xPathFilter);
                    for (Element extensionFilter : extensionFilterNodes) {
                        for (Element rootFilter : filterNodes) {
                            if (extensionFilter.valueOf("@id").equals(rootFilter.valueOf("@id"))) {
                                rootNode.remove(rootFilter);
                            }
                        }
                        extensionFilter.detach();
                        rootNode.add(extensionFilter);
                    }
                    break;
                }
            }
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:org.jenkins.tools.test.model.MavenPom.java

License:Open Source License

public void addDependencies(Map<String, VersionNumber> toAdd, Map<String, VersionNumber> toReplace,
        VersionNumber coreDep, Map<String, String> pluginGroupIds) throws IOException {
    File pom = new File(rootDir.getAbsolutePath() + "/" + pomFileName);
    Document doc;// w w w .  j a  v a  2s .c  o m
    try {
        doc = new SAXReader().read(pom);
    } catch (DocumentException x) {
        throw new IOException(x);
    }
    Element dependencies = doc.getRootElement().element("dependencies");
    if (dependencies == null) {
        dependencies = doc.getRootElement().addElement("dependencies");
    }
    for (Element mavenDependency : (List<Element>) dependencies.elements("dependency")) {
        Element artifactId = mavenDependency.element("artifactId");
        if (artifactId == null || !"maven-plugin".equals(artifactId.getTextTrim())) {
            continue;
        }
        Element version = mavenDependency.element("version");
        if (version == null || version.getTextTrim().startsWith("${")) {
            // Prior to 1.532, plugins sometimes assumed they could pick up the Maven plugin version from their parent POM.
            if (version != null) {
                mavenDependency.remove(version);
            }
            version = mavenDependency.addElement("version");
            version.addText(coreDep.toString());
        }
    }
    for (Element mavenDependency : (List<Element>) dependencies.elements("dependency")) {
        Element artifactId = mavenDependency.element("artifactId");
        if (artifactId == null) {
            continue;
        }
        excludeSecurity144Compat(mavenDependency);
        VersionNumber replacement = toReplace.get(artifactId.getTextTrim());
        if (replacement == null) {
            continue;
        }
        Element version = mavenDependency.element("version");
        if (version != null) {
            mavenDependency.remove(version);
        }
        version = mavenDependency.addElement("version");
        version.addText(replacement.toString());
    }
    dependencies.addComment("SYNTHETIC");
    for (Map.Entry<String, VersionNumber> dep : toAdd.entrySet()) {
        Element dependency = dependencies.addElement("dependency");
        String group = pluginGroupIds.get(dep.getKey());

        // Handle cases where plugin isn't under default groupId
        if (group != null && !group.isEmpty()) {
            dependency.addElement("groupId").addText(group);
        } else {
            dependency.addElement("groupId").addText("org.jenkins-ci.plugins");
        }
        dependency.addElement("artifactId").addText(dep.getKey());
        dependency.addElement("version").addText(dep.getValue().toString());
        excludeSecurity144Compat(dependency);
    }
    FileWriter w = new FileWriter(pom);
    try {
        doc.write(w);
    } finally {
        w.close();
    }
}

From source file:org.jfrog.jade.plugins.idea.IdeaModuleMojo.java

License:Apache License

private void rewriteDependencies(Element component) {
    Map<String, Element> modulesByName = new HashMap<String, Element>();
    Map<String, Element> modulesByUrl = new HashMap<String, Element>();
    Set<Element> unusedModules = new HashSet<Element>();
    for (Iterator children = component.elementIterator("orderEntry"); children.hasNext();) {
        Element orderEntry = (Element) children.next();

        String type = orderEntry.attributeValue("type");
        if ("module".equals(type)) {
            modulesByName.put(orderEntry.attributeValue("module-name"), orderEntry);
        } else if ("module-library".equals(type)) {
            // keep track for later so we know what is left
            unusedModules.add(orderEntry);

            Element lib = orderEntry.element("library");
            String name = lib.attributeValue("name");
            if (name != null) {
                modulesByName.put(name, orderEntry);
            } else {
                Element classesChild = lib.element("CLASSES");
                if (classesChild != null) {
                    Element rootChild = classesChild.element("root");
                    if (rootChild != null) {
                        String url = rootChild.attributeValue("url");
                        if (url != null) {
                            // Need to ignore case because of Windows drive letters
                            modulesByUrl.put(url.toLowerCase(), orderEntry);
                        }/*from w  w  w .  j  av  a2  s  .  com*/
                    }
                }
            }
        }
    }

    List testClasspathElements = getExecutedProject().getTestArtifacts();
    for (Iterator i = testClasspathElements.iterator(); i.hasNext();) {
        Artifact a = (Artifact) i.next();

        Library library = findLibrary(a);
        if (library != null && library.isExclude()) {
            continue;
        }

        String moduleName;
        if (isUseFullNames()) {
            moduleName = a.getGroupId() + ':' + a.getArtifactId() + ':' + a.getType() + ':' + a.getVersion();
        } else {
            moduleName = getNameProvider().getProjectName(a);
        }

        Element dep = (Element) modulesByName.get(moduleName);

        if (dep == null) {
            // Need to ignore case because of Windows drive letters
            dep = (Element) modulesByUrl.get(getLibraryUrl(a).toLowerCase());
        }

        if (dep != null) {
            unusedModules.remove(dep);
        } else {
            dep = createElement(component, "orderEntry");
        }

        boolean isIdeaModule = false;
        if (isLinkModules()) {
            isIdeaModule = isReactorProject(a.getGroupId(), a.getArtifactId());

            if (isIdeaModule) {
                dep.addAttribute("type", "module");
                dep.addAttribute("module-name", moduleName);
            }
        }

        if (a.getFile() != null && !isIdeaModule) {
            dep.addAttribute("type", "module-library");

            Element lib = dep.element("library");

            if (lib == null) {
                lib = createElement(dep, "library");
            }

            if (isDependenciesAsLibraries()) {
                lib.addAttribute("name", moduleName);
            }

            // replace classes
            removeOldElements(lib, "CLASSES");
            Element classes = createElement(lib, "CLASSES");
            if (library != null && library.getSplitClasses().length > 0) {
                lib.addAttribute("name", moduleName);
                String[] libraryClasses = library.getSplitClasses();
                for (int k = 0; k < libraryClasses.length; k++) {
                    String classpath = libraryClasses[k];
                    extractMacro(classpath);
                    Element classEl = createElement(classes, "root");
                    classEl.addAttribute("url", classpath);
                }
            } else {
                createElement(classes, "root").addAttribute("url", getLibraryUrl(a));
            }

            if (library != null && library.getSplitSources().length > 0) {
                removeOldElements(lib, "SOURCES");
                Element sourcesElement = createElement(lib, "SOURCES");
                String[] sources = library.getSplitSources();
                for (int k = 0; k < sources.length; k++) {
                    String source = sources[k];
                    extractMacro(source);
                    Element sourceEl = createElement(sourcesElement, "root");
                    sourceEl.addAttribute("url", source);
                }
            } else if (isDownloadSources()) {
                resolveClassifier(createOrGetElement(lib, "SOURCES"), a, getSourceClassifier());
            }

            if (isDownloadJavadocs()) {
                resolveClassifier(createOrGetElement(lib, "JAVADOC"), a, getJavadocClassifier());
            }
        }
    }

    for (Iterator i = unusedModules.iterator(); i.hasNext();) {
        Element orderEntry = (Element) i.next();

        component.remove(orderEntry);
    }
}

From source file:org.jivesoftware.openfire.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;
    }//w w w  .  ja va2s  .  c om

    // Look for a DiscoItemsProvider associated with the requested entity.
    // We consider the host of the recipient JID of the packet as the entity. It's the 
    // DiscoItemsProvider responsibility to provide the items associated with the JID's name  
    // together with any possible requested node.
    DiscoItemsProvider 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 DiscoItemsProvider
                Element item;
                while (itemsItr.hasNext()) {
                    item = itemsItr.next().getElement();
                    item.setQName(new QName(item.getName(), queryElement.getNamespace()));
                    queryElement.add(item.createCopy());
                }
            }
        } else {
            // If the DiscoItemsProvider 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 DiscoItemsProvider then answer a not found error
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.item_not_found);
    }

    return reply;
}

From source file:org.jivesoftware.openfire.fastpath.settings.SettingsManager.java

License:Open Source License

public void setMap(Map map) {
    Element element = DocumentHelper.createElement(namespace);
    final Iterator i = element.elementIterator();
    while (i.hasNext()) {
        element.remove((Element) i.next());
    }/*  w  w  w .jav a2  s.  com*/
    final Iterator iter = map.keySet().iterator();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        String value = (String) map.get(key);

        Element elem = DocumentHelper.createElement("entry");
        elem.addElement(key).setText(value);
        element.add(elem);
    }

    try {
        workgroupSettings.add(workgroup.getJID().toBareJID(), element);
    } catch (Exception ex) {
        Log.error(ex.getMessage(), ex);
    }
}

From source file:org.jivesoftware.openfire.handler.IQBlockingHandler.java

License:Open Source License

/**
 * Removes all JIDs from the blocklist of the provided user.
 *
 * This method removes the JIDs to the default privacy list. When no default privacy list exists for this user, this
 * method does nothing.//w  w  w .  j  a  v  a  2s .co m
 *
 * @param user The owner of the blocklist to which JIDs are to be added (cannot be null).
 * @return The JIDs that are removed (never null, possibly empty).
 */
private Set<JID> removeAllFromBlocklist(User user) {
    Log.debug("Obtain the default privacy list for '{}'", user.getUsername());
    final Set<JID> result = new HashSet<>();
    PrivacyList defaultPrivacyList = PrivacyListManager.getInstance().getDefaultPrivacyList(user.getUsername());
    if (defaultPrivacyList == null) {
        return result;
    }

    Log.debug("Removing all JIDs from blocklist '{}' (belonging to '{}')", defaultPrivacyList.getName(),
            user.getUsername());
    final Element listElement = defaultPrivacyList.asElement();
    final Set<Element> toRemove = new HashSet<>();
    for (final Element element : listElement.elements("item")) {
        if ("jid".equals(element.attributeValue("type")) && "deny".equals(element.attributeValue("action"))) {
            toRemove.add(element);
            result.add(new JID(element.attributeValue("value")));
        }
    }

    if (!toRemove.isEmpty()) {
        for (final Element remove : toRemove) {
            listElement.remove(remove);
        }

        defaultPrivacyList.updateList(listElement);
        PrivacyListProvider.getInstance().updatePrivacyList(user.getUsername(), defaultPrivacyList);
    }
    return result;
}

From source file:org.jivesoftware.openfire.handler.IQBlockingHandler.java

License:Open Source License

/**
 * Removes a collection of JIDs from the blocklist of the provided user.
 *
 * This method removes the JIDs to the default privacy list. When no default privacy list exists for this user, this
 * method does nothing.//from  w w  w .  j a va 2 s.  c o  m
 *
 * @param user       The owner of the blocklist to which JIDs are to be added (cannot be null).
 * @param toUnblocks The JIDs to be removed (can be null, which results in a noop).
 * @return The JIDs that are removed (never null, possibly empty).
 */
protected Set<JID> removeFromBlockList(User user, Collection<JID> toUnblocks) {
    final Set<JID> result = new HashSet<>();
    if (toUnblocks == null || toUnblocks.isEmpty()) {
        return result;
    }

    Log.debug("Obtain the default privacy list for '{}'", user.getUsername());
    PrivacyList defaultPrivacyList = PrivacyListManager.getInstance().getDefaultPrivacyList(user.getUsername());
    if (defaultPrivacyList == null) {
        return result;
    }

    Log.debug("Removing {} JIDs as blocked items from list '{}' (belonging to '{}')", toUnblocks.size(),
            defaultPrivacyList.getName(), user.getUsername());
    final Element listElement = defaultPrivacyList.asElement();
    final Set<Element> toRemove = new HashSet<>();
    for (final Element element : listElement.elements("item")) {
        final JID jid = new JID(element.attributeValue("value"));
        if ("jid".equals(element.attributeValue("type")) && "deny".equals(element.attributeValue("action"))
                && toUnblocks.contains(jid)) {
            toRemove.add(element);
            result.add(jid);
        }
    }

    if (!toRemove.isEmpty()) {
        for (final Element remove : toRemove) {
            listElement.remove(remove);
        }

        defaultPrivacyList.updateList(listElement);
        PrivacyListProvider.getInstance().updatePrivacyList(user.getUsername(), defaultPrivacyList);
    }

    return result;
}