Example usage for org.dom4j Node detach

List of usage examples for org.dom4j Node detach

Introduction

In this page you can find the example usage for org.dom4j Node detach.

Prototype

Node detach();

Source Link

Document

Removes this node from its parent if there is one.

Usage

From source file:com.liferay.alloy.tools.builder.taglib.TagBuilder.java

License:Open Source License

protected Document mergeTlds(Document sourceDoc, Document targetDoc) {
    Element targetRoot = targetDoc.getRootElement();

    DocumentFactory factory = SAXReaderUtil.getDocumentFactory();

    XPath xpathTags = factory.createXPath("//tld:tag");

    Map<String, String> namespaceContextMap = new HashMap<String, String>();

    namespaceContextMap.put(_TLD_XPATH_PREFIX, _TLD_XPATH_URI);

    NamespaceContext namespaceContext = new AlloyGeneratorNamespaceContext(namespaceContextMap);

    xpathTags.setNamespaceContext(namespaceContext);

    List<Node> sources = xpathTags.selectNodes(sourceDoc);

    for (Node source : sources) {
        Element sourceElement = (Element) source;

        String sourceName = sourceElement.elementText("name");

        String xpathTagValue = "//tld:tag[tld:name='" + sourceName + "']";

        XPath xpathTag = factory.createXPath(xpathTagValue);

        xpathTag.setNamespaceContext(namespaceContext);

        List<Node> targets = xpathTag.selectNodes(targetDoc);

        if (targets.size() > 0) {
            Element targetElement = (Element) targets.get(0);

            XPath xpathAttributes = factory.createXPath(xpathTagValue + "//tld:attribute");

            Map<String, String> namespaces = new HashMap<String, String>();

            namespaces.put("tld", StringPool.EMPTY);

            xpathAttributes.setNamespaceURIs(namespaces);

            List<Node> sourceAttributes = xpathAttributes.selectNodes(source);

            for (Node sourceAttribute : sourceAttributes) {
                Element sourceAttributeElement = (Element) sourceAttribute;

                String attributeName = sourceAttributeElement.elementText("name");

                String xpathAttributeValue = "//tld:attribute[tld:name='" + attributeName + "']";

                XPath xpathAttribute = factory.createXPath(xpathTagValue + xpathAttributeValue);

                xpathAttribute.setNamespaceContext(namespaceContext);

                Node targetAttribute = xpathAttribute.selectSingleNode(targetElement);

                if (targetAttribute != null) {
                    targetAttribute.detach();
                }//from   www.j a  v  a  2s  .c  om

                targetElement.add(sourceAttributeElement.createCopy());
            }

            Element dynamicAttrElement = targetElement.element("dynamic-attributes");

            if (dynamicAttrElement != null) {
                targetElement.add(dynamicAttrElement.detach());
            }
        } else {
            targetRoot.add(sourceElement.createCopy());
        }
    }

    return targetDoc;
}

From source file:com.noterik.bart.fs.fscommand.CopyCommand.java

License:Open Source License

/**
 * /*from   w w  w.  j  av  a2  s  . com*/
 * @param uri
 * @return
 */
private Document getPropertiesOfUri(String uri, int depth) {
    // refactor uri
    String cp = URIParser.getCurrentUriPart(uri);
    if (cp.equals(FSXMLHelper.XML_PROPERTIES)) {
        uri = URIParser.getParentUri(uri);
    }

    // get complete
    Document pDoc = null;
    if (depth == -1) {
        pDoc = rHandler.getNodeProperties(uri, true);
    } else {
        pDoc = rHandler.getNodeProperties(uri, depth, true);
    }

    // loop through xml and check referid's
    List<Node> rNodes = pDoc.selectNodes("//@referid");
    logger.debug("rNodes: " + rNodes);
    for (Iterator<Node> iter = rNodes.iterator(); iter.hasNext();) {
        // get referid attribute and parent node
        Node node = iter.next();
        String referid = node.getText();
        Element parent = node.getParent();
        logger.debug("parent: " + parent.asXML() + ", refer: " + referid);

        // get properties of referid
        Document rDoc = rHandler.getNodeProperties(referid, 0, false);
        logger.debug("rDoc: " + rDoc.asXML());
        Node properties = rDoc.selectSingleNode("//properties");
        List<Node> pNodes = properties.selectNodes("child::*");
        logger.debug("pNodes: " + pNodes);
        for (Iterator<Node> iter2 = pNodes.iterator(); iter2.hasNext();) {
            // select the same property elements that are in parent element and refer properties
            Node prop = iter2.next();
            List<Node> parentPNodes = parent.selectNodes("properties/child::*");
            for (Node parentPropNode : parentPNodes) {
                if (parentPropNode.getName().equals(prop.getName())
                        && parentPropNode.getText().equals(prop.getText())) {
                    logger.debug("removing: " + parentPropNode.asXML());
                    parentPropNode.detach();
                }
            }
        }
    }

    return pDoc;
}

From source file:com.noterik.bart.fs.fscommand.dynamic.collection.config.wizard.java

License:Open Source License

public String run(String uri, String xml) {
    logger.debug("start dynamic/collection/config/wizard");

    Document doc = XMLHelper.asDocument(xml);

    if (doc == null) {
        return FSXMLBuilder.getErrorMessage("403", "The value you sent is not valid",
                "You have to POST a valid command XML", "http://teamelements.noterik.nl/team");
    }/*from w  w  w.  j a  v a 2 s  .co  m*/

    String user = doc.selectSingleNode("//properties/user") == null ? ""
            : doc.selectSingleNode("//properties/user").getText();
    String ticket = doc.selectSingleNode("//properties/ticket") == null ? ""
            : doc.selectSingleNode("//properties/ticket").getText();

    //TODO: validate user/ticket

    //get collection
    Document collection = FSXMLRequestHandler.instance().getNodeProperties(uri, false);
    logger.debug(collection.asXML());

    //get roles
    Element wizard;
    List<Node> wizards = collection.selectNodes("//config[@id='1']/wizard");
    Node userRole = collection
            .selectSingleNode("//config[@id='roles']/user[@id='" + user + "']/properties/wizard");

    if (userRole == null) {
        logger.debug("user not found --> default wizard");
        // Loop all wizards
        for (Iterator<Node> iter = wizards.iterator(); iter.hasNext();) {
            wizard = (Element) iter.next();

            String wizardId = wizard.attribute("id") == null ? "" : wizard.attribute("id").getText();
            if (!wizardId.equals("1")) {
                logger.debug("detach wizard with id " + wizardId);
                wizard.detach();
            }
        }
    } else {
        logger.debug("user found " + userRole.asXML());
        String roles = userRole.getText();
        String[] results = roles.split(",");

        // Loop all wizards
        for (Iterator<Node> iter = wizards.iterator(); iter.hasNext();) {
            wizard = (Element) iter.next();

            String wizardId = wizard.attribute("id") == null ? "" : wizard.attribute("id").getText();
            if (!inArray(results, wizardId)) {
                logger.debug("detach wizard with id " + wizardId);
                wizard.detach();
            }
        }
    }

    //detach config roles
    Node configRoles = collection.selectSingleNode("//config[@id='roles']");
    configRoles.detach();

    return collection.asXML();
}

From source file:com.noterik.bart.fs.fscommand.dynamic.config.flash.java

License:Open Source License

private void handleIncludeExcludeNodes(Document conf, Document tmpConf) {
    List<Node> includeNodes = tmpConf
            .selectNodes("/fsxml/filesystem[@id='1']/*[@id and not(ends-with(@id,'_exclude'))]");
    List<Node> excludeNodes = tmpConf.selectNodes("/fsxml/filesystem[@id='1']/*[ends-with(@id,'_exclude')]");

    logger.debug("number of includeNodes = " + includeNodes.size());
    for (int j = 0; j < includeNodes.size(); j++) {
        logger.debug(j + " = " + includeNodes.get(j).toString());
    }//from w w w .j  a  v  a 2s.c  om
    logger.debug("number of excludeNodes = " + excludeNodes.size());
    for (int j = 0; j < excludeNodes.size(); j++) {
        logger.debug(j + " = " + excludeNodes.get(j).toString());
    }

    Element base = (Element) conf.selectSingleNode("/fsxml/filesystem[@id='1']");

    if (includeNodes != null) {
        for (int i = 0; i < includeNodes.size(); i++) {
            String nodename = includeNodes.get(i).getName();
            String nodeid = includeNodes.get(i).valueOf("@id");

            logger.debug("check if node exists " + nodename + " id " + nodeid);

            Node existingNode = base.selectSingleNode(nodename + "[@id='" + nodeid + "']");
            if (existingNode != null) {
                logger.debug("node exists, replace");
                List contentOfBase = base.content();
                int index = contentOfBase.indexOf(existingNode);
                contentOfBase.set(index, includeNodes.get(i).detach());
            } else {
                base.add(includeNodes.get(i).detach());
            }
        }
    }

    if (excludeNodes != null) {
        logger.debug("handling exclude nodes for user");
        for (int i = 0; i < excludeNodes.size(); i++) {
            logger.debug("handling exclude node nr " + i);
            String nodename = excludeNodes.get(i).getName();
            String nodeid = excludeNodes.get(i).valueOf("@id");
            nodeid = nodeid.substring(0, nodeid.lastIndexOf("_exclude"));

            logger.debug("about to exclude " + nodename + " with id " + nodeid);

            Node remove = base.selectSingleNode(nodename + "[@id='" + nodeid + "']");
            if (remove != null) {
                logger.debug("node to exclude found, detach");
                remove.detach();
            }
        }
    }
}

From source file:com.noterik.bart.fs.fscommand.dynamic.presentation.playout.flash.java

License:Open Source License

private static void handleIncludeExcludeNodes(Document conf, Document tmpConf) {
    List<Node> includeNodes = tmpConf
            .selectNodes("/fsxml/filesystem[@id='1']/*[@id and not(ends-with(@id,'_exclude'))]");
    List<Node> excludeNodes = tmpConf.selectNodes("/fsxml/filesystem[@id='1']/*[ends-with(@id,'_exclude')]");

    logger.debug("number of includeNodes = " + includeNodes.size());
    for (int j = 0; j < includeNodes.size(); j++) {
        logger.debug(j + " = " + includeNodes.get(j).toString());
    }// ww  w.ja  v a 2 s . c  o  m
    logger.debug("number of excludeNodes = " + excludeNodes.size());
    for (int j = 0; j < excludeNodes.size(); j++) {
        logger.debug(j + " = " + excludeNodes.get(j).toString());
    }

    Element base = (Element) conf.selectSingleNode("/fsxml/filesystem[@id='1']");

    if (includeNodes != null) {
        for (int i = 0; i < includeNodes.size(); i++) {
            String nodename = includeNodes.get(i).getName();
            String nodeid = includeNodes.get(i).valueOf("@id");

            logger.debug("check if node exists " + nodename + " id " + nodeid);

            Node existingNode = base.selectSingleNode(nodename + "[@id='" + nodeid + "']");
            if (existingNode != null) {
                logger.debug("node exists, replace");
                List contentOfBase = base.content();
                int index = contentOfBase.indexOf(existingNode);
                contentOfBase.set(index, includeNodes.get(i).detach());
            } else {
                base.add(includeNodes.get(i).detach());
            }
        }
    }

    if (excludeNodes != null) {
        logger.debug("handling exclude nodes for user");
        for (int i = 0; i < excludeNodes.size(); i++) {
            logger.debug("handling exclude node nr " + i);
            String nodename = excludeNodes.get(i).getName();
            String nodeid = excludeNodes.get(i).valueOf("@id");
            nodeid = nodeid.substring(0, nodeid.lastIndexOf("_exclude"));

            logger.debug("about to exclude " + nodename + " with id " + nodeid);

            Node remove = base.selectSingleNode(nodename + "[@id='" + nodeid + "']");
            if (remove != null) {
                logger.debug("node to exclude found, detach");
                remove.detach();
            }
        }
    }
}

From source file:com.processpuzzle.application.domain.ApplicationRepository.java

License:Open Source License

public void delete(DefaultUnitOfWork work, Application application) {
    Node applicationNode = findApplicationElement(application.getApplicationName());
    if (applicationNode != null) {
        applicationNode.detach();
        try {//  w w  w . ja va 2s. c  om
            writeXmlDocument();
        } catch (IOException e) {
            throw new RepositoryException(this, RepositoryAction.delete, application, e);
        }
    } else
        throw new RepositoryException(this, RepositoryAction.delete, application);
}

From source file:com.ten45.service.aggregator.ConfigurationServiceImpl.java

/**
 * Expand the original configuration document with the referred node.
 * It reads the referred document, finds the referred element in the same 
 * path as the original document, and moves all the children of the 
 * referred element into the original element.
 * /*  www.  j a  va  2s.c  om*/
 * @param doc
 * @param node
 * @return
 * @throws DocumentException
 */
private Document expandReference(Document doc, Node node) throws DocumentException {
    // Find the 'anchor' element that contains the reference declaration.
    Element anchor = node.getParent();
    XPath anchorXPath = DocumentHelper.createXPath(anchor.getPath());

    // Remove the reference declaration node from the document.
    node.detach();

    // Read the new configuration.
    String resourceName = rootPath + node.getText() + ".xml";
    log.debug("Reading resource " + resourceName);
    InputStream in = this.getClass().getResourceAsStream(resourceName);
    SAXReader reader = new SAXReader();
    try {
        Document refDoc = reader.read(in);

        Element refElement = (Element) anchorXPath.selectSingleNode(refDoc);
        if (refElement != null) {
            log.debug("Expanding " + anchorXPath.getText() + " with " + refElement.asXML());
            // Move all elements from the referenced document into the anchor.
            List children = refElement.elements();
            if (children != null && children.size() > 0) {
                for (int i = 0; i < children.size(); i++) {
                    Element child = (Element) children.get(i);
                    XPath refXPath = DocumentHelper.createXPath(child.getPath());
                    if (refXPath.selectSingleNode(doc) == null) {
                        log.debug("Adding element " + refXPath.getText());
                        child.detach();
                        anchor.add(child);
                    } else {
                        log.debug("Ignore pre-existing element " + refXPath.getText());
                    }
                }
            }
        }
    } catch (DocumentException de) {
        throw de;
    }
    return doc;
}

From source file:com.xebia.mojo.dashboard.DashboardMojo.java

License:Apache License

private void createProjectRow(Branch dashboardTable, final MavenProject subProject, int rowNum)
        throws MojoExecutionException {
    final Element tableRow = dashboardTable.addElement("tr");
    String cssClass = (rowNum == 0) ? "a" : "b";
    tableRow.addAttribute("class", cssClass);
    createProjectNameCell(subProject, tableRow);
    doWithReports(new ReportColumnCallback() {
        public void handleReportColumn(DashboardReport report, String col) throws MojoExecutionException {
            if (report.canExecute(subProject)) {
                Node node = report.getContent(subProject, col);

                if (node != null) {
                    Node content = node.detach();
                    Element cell = createTableCell(tableRow, null);
                    String href = report.getLinkLocation();

                    if (href != null) {
                        createLink(cell, DashboardUtil.determineCompletePath(subProject) + href, content);
                    } else {
                        cell.add(content);
                    }/* w ww  . ja  v  a  2  s  . c  o m*/
                } else {
                    createTableCell(tableRow, "-");
                }
            } else {
                createTableCell(tableRow, "-");
            }
        }
    });
}

From source file:cz.fi.muni.xkremser.editor.server.newObject.MonographBuilder.java

License:Open Source License

private void updateDcDoc(Document dcDoc, String pid, String signature, String sysno, DigitalObjectModel model) {
    Element dcRootEl = dcDoc.getRootElement();
    Attribute schemaLoc = dcRootEl.attribute("schemaLocation");
    dcRootEl.remove(schemaLoc);//from  w ww .  ja v  a2s.  c o  m
    Namespace xsi = DocumentHelper.createNamespace("xsi2", FedoraNamespaces.SCHEMA_NAMESPACE_URI);
    dcRootEl.add(xsi);
    dcRootEl.addAttribute(new QName("schemaLocation", xsi),
            "http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd");

    XPath typeXpath = Dom4jUtils.createXPath("/oai_dc:dc/dc:identifier");
    List<? extends Node> nodes = typeXpath.selectNodes(dcDoc);
    for (Node node : nodes) {
        node.detach();
    }
    Element idUuid = dcRootEl.addElement("dc:identifier");
    idUuid.addText(pid);

    for (Node node : nodes) {
        if (node.getText() != null && !"".equals(node.getText().trim())
                && !node.getText().contains(Constants.FEDORA_UUID_PREFIX)) {
            Element temp = dcRootEl.addElement("dc:identifier");
            temp.addText(node.getText());
        }
    }

    if (signature != null) {
        Element idSignature = dcRootEl.addElement("dc:identifier");
        idSignature.addText("signature:" + signature);
    }
    if (sysno != null) {
        Element idSysno = dcRootEl.addElement("dc:identifier");
        idSysno.addText("sysno:" + sysno);
    }
    removeDcTypeElements(dcDoc);
    Element typeEl = dcRootEl.addElement("dc:type");
    typeEl.addText("model:" + model.toString());
    Element rightsEl = dcRootEl.addElement("dc:rights");
    rightsEl.addText("policy:" + Policy.PUBLIC.toString().toLowerCase());
    updateDcLanguages(dcDoc);
}

From source file:cz.fi.muni.xkremser.editor.server.newObject.MonographBuilder.java

License:Open Source License

private void removeDcTypeElements(Document doc) {
    XPath typeXpath = Dom4jUtils.createXPath("/oai_dc:dc/dc:type");
    List<? extends Node> nodes = typeXpath.selectNodes(doc);
    for (Node node : nodes) {
        node.detach();
    }//w  w  w. j  ava2s .  com
}