Example usage for org.w3c.dom Node cloneNode

List of usage examples for org.w3c.dom Node cloneNode

Introduction

In this page you can find the example usage for org.w3c.dom Node cloneNode.

Prototype

public Node cloneNode(boolean deep);

Source Link

Document

Returns a duplicate of this node, i.e., serves as a generic copy constructor for nodes.

Usage

From source file:org.kuali.rice.kns.workflow.attribute.KualiXmlAttributeHelper.java

/**
 * This method overrides the super class and modifies the XML that it operates on to put the name and the title in the place
 * where the super class expects to see them, overwriting the original title in the XML.
 *
 * @see org.kuali.rice.kew.rule.xmlrouting.StandardGenericXMLRuleAttribute#getConfigXML()
 *//*w w  w  . j a  v a 2  s . c om*/

public Element processConfigXML(Element root, String[] xpathExpressionElements) {

    NodeList fields = root.getElementsByTagName("fieldDef");
    Element theTag = null;
    String docContent = "";

    /**
     * This section will check to see if document content has been defined in the configXML for the document type, by running an
     * XPath. If this is an empty list the xpath expression in the fieldDef is used to define the xml document content that is
     * added to the configXML. The xmldocument content is of this form, when in the document configXML. <xmlDocumentContent>
     * <org.kuali.rice.krad.bo.SourceAccountingLine> <amount> <value>%totaldollarAmount%</value> </amount>
     * </org.kuali.rice.krad.bo.SourceAccountingLine> </xmlDocumentContent> This class generates this on the fly, by creating an XML
     * element for each term in the XPath expression. When this doesn't apply XML can be coded in the configXML for the
     * ruleAttribute.
     *
     * @see org.kuali.rice.kew.plugin.attributes.WorkflowAttribute#getDocContent()
     */

    org.w3c.dom.Document xmlDoc = null;
    if (!xmlDocumentContentExists(root)) { // XML Document content is given because the xpath is non standard
        fields = root.getElementsByTagName("fieldDef");
        xmlDoc = root.getOwnerDocument();
    }
    for (int i = 0; i < fields.getLength(); i++) { // loop over each fieldDef
        String name = null;
        if (!xmlDocumentContentExists(root)) {
            theTag = (Element) fields.item(i);

            /*
             * Even though there may be multiple xpath test, for example one for source lines and one for target lines, the
             * xmlDocumentContent only needs one, since it is used for formatting. The first one is arbitrarily selected, since
             * they are virtually equivalent in structure, most of the time.
             */

            List<String> xPathTerms = getXPathTerms(theTag);
            if (xPathTerms.size() != 0) {
                Node iterNode = xmlDoc.createElement("xmlDocumentContent");

                xmlDoc.normalize();

                iterNode.normalize();

                /*
                 * Since this method is run once per attribute and there may be multiple fieldDefs, the first fieldDef is used
                 * to create the configXML.
                 */
                for (int j = 0; j < xPathTerms.size(); j++) {// build the configXML based on the Xpath
                    // TODO - Fix the document content element generation
                    iterNode.appendChild(xmlDoc.createElement(xPathTerms.get(j)));
                    xmlDoc.normalize();

                    iterNode = iterNode.getFirstChild();
                    iterNode.normalize();

                }
                iterNode.setTextContent("%" + xPathTerms.get(xPathTerms.size() - 1) + "%");
                root.appendChild(iterNode);
            }
        }
        theTag = (Element) fields.item(i);
        // check to see if a values finder is being used to set valid values for a field
        NodeList displayTagElements = theTag.getElementsByTagName("display");
        if (displayTagElements.getLength() == 1) {
            Element displayTag = (Element) displayTagElements.item(0);
            List valuesElementsToAdd = new ArrayList();
            for (int w = 0; w < displayTag.getChildNodes().getLength(); w++) {
                Node displayTagChildNode = (Node) displayTag.getChildNodes().item(w);
                if ((displayTagChildNode != null) && ("values".equals(displayTagChildNode.getNodeName()))) {
                    if (displayTagChildNode.getChildNodes().getLength() > 0) {
                        String valuesNodeText = displayTagChildNode.getFirstChild().getNodeValue();
                        String potentialClassName = getPotentialKualiClassName(valuesNodeText,
                                KUALI_VALUES_FINDER_REFERENCE_PREFIX, KUALI_VALUES_FINDER_REFERENCE_SUFFIX);
                        if (StringUtils.isNotBlank(potentialClassName)) {
                            try {
                                Class finderClass = Class.forName((String) potentialClassName);
                                KeyValuesFinder finder = (KeyValuesFinder) finderClass.newInstance();
                                NamedNodeMap valuesNodeAttributes = displayTagChildNode.getAttributes();
                                Node potentialSelectedAttribute = (valuesNodeAttributes != null)
                                        ? valuesNodeAttributes.getNamedItem("selected")
                                        : null;
                                for (Iterator iter = finder.getKeyValues().iterator(); iter.hasNext();) {
                                    KeyValue keyValue = (KeyValue) iter.next();
                                    Element newValuesElement = root.getOwnerDocument().createElement("values");
                                    newValuesElement.appendChild(
                                            root.getOwnerDocument().createTextNode(keyValue.getKey()));
                                    // newValuesElement.setNodeValue(KeyValue.getKey().toString());
                                    newValuesElement.setAttribute("title", keyValue.getValue());
                                    if (potentialSelectedAttribute != null) {
                                        newValuesElement.setAttribute("selected",
                                                potentialSelectedAttribute.getNodeValue());
                                    }
                                    valuesElementsToAdd.add(newValuesElement);
                                }
                            } catch (ClassNotFoundException cnfe) {
                                String errorMessage = "Caught an exception trying to find class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, cnfe);
                                throw new RuntimeException(errorMessage, cnfe);
                            } catch (InstantiationException ie) {
                                String errorMessage = "Caught an exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, ie);
                                throw new RuntimeException(errorMessage, ie);
                            } catch (IllegalAccessException iae) {
                                String errorMessage = "Caught an access exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, iae);
                                throw new RuntimeException(errorMessage, iae);
                            }
                        } else {
                            valuesElementsToAdd.add(displayTagChildNode.cloneNode(true));
                        }
                        displayTag.removeChild(displayTagChildNode);
                    }
                }
            }
            for (Iterator iter = valuesElementsToAdd.iterator(); iter.hasNext();) {
                Element valuesElementToAdd = (Element) iter.next();
                displayTag.appendChild(valuesElementToAdd);
            }
        }
        if ((xpathExpressionElements != null) && (xpathExpressionElements.length > 0)) {
            NodeList fieldEvaluationElements = theTag.getElementsByTagName("fieldEvaluation");
            if (fieldEvaluationElements.getLength() == 1) {
                Element fieldEvaluationTag = (Element) fieldEvaluationElements.item(0);
                List tagsToAdd = new ArrayList();
                for (int w = 0; w < fieldEvaluationTag.getChildNodes().getLength(); w++) {
                    Node fieldEvaluationChildNode = (Node) fieldEvaluationTag.getChildNodes().item(w);
                    Element newTagToAdd = null;
                    if ((fieldEvaluationChildNode != null)
                            && ("xpathexpression".equals(fieldEvaluationChildNode.getNodeName()))) {
                        newTagToAdd = root.getOwnerDocument().createElement("xpathexpression");
                        newTagToAdd.appendChild(root.getOwnerDocument()
                                .createTextNode(generateNewXpathExpression(
                                        fieldEvaluationChildNode.getFirstChild().getNodeValue(),
                                        xpathExpressionElements)));
                        tagsToAdd.add(newTagToAdd);
                        fieldEvaluationTag.removeChild(fieldEvaluationChildNode);
                    }
                }
                for (Iterator iter = tagsToAdd.iterator(); iter.hasNext();) {
                    Element elementToAdd = (Element) iter.next();
                    fieldEvaluationTag.appendChild(elementToAdd);
                }
            }
        }
        theTag.setAttribute("title", getBusinessObjectTitle(theTag));

    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(XmlJotter.jotNode(root));
        StringWriter xmlBuffer = new StringWriter();
        try {

            root.normalize();
            Source source = new DOMSource(root);
            Result result = new StreamResult(xmlBuffer);
            TransformerFactory.newInstance().newTransformer().transform(source, result);
        } catch (Exception e) {
            LOG.debug(" Exception when printing debug XML output " + e);
        }
        LOG.debug(xmlBuffer.getBuffer());
    }

    return root;
}

From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.DocumentFactory.java

/**
 * Updates the Target Element of the given Policy
 * //from  w w w  .  j a v  a2s. c  om
 * @param policy
 */
private void updatePolicyTargets(Node policy) {

    Node target = policy.getChildNodes().item(1);

    while (target.hasChildNodes()) {

        target.removeChild(target.getFirstChild());
    }

    Vector<Node> resourceListFromRules = new Vector<Node>();

    for (int i = 0; i < policy.getChildNodes().getLength(); i++) {

        Node n = policy.getChildNodes().item(i);

        if (n.getNodeName().equalsIgnoreCase("Rule")) {

            resourceListFromRules.add(n);
        }
    }

    Vector<Node> resourceListFromTarget = new Vector<Node>();

    for (int i = 0; i < resourceListFromRules.size(); i++) {

        Node n = resourceListFromRules.elementAt(i);
        boolean matches = false;

        for (int k = 0; k < resourceListFromTarget.size(); k++) {

            if (n.getChildNodes().item(3).getChildNodes().item(3).getChildNodes().item(1).getChildNodes()
                    .item(1).getChildNodes().item(1).getTextContent()
                    .equalsIgnoreCase(resourceListFromTarget.elementAt(k).getChildNodes().item(3)
                            .getChildNodes().item(3).getChildNodes().item(1).getChildNodes().item(1)
                            .getChildNodes().item(1).getTextContent())) {
                matches = true;
            }
        }
        if (!matches) {
            resourceListFromTarget.add(n.cloneNode(true));
        }
    }

    Document ress = null;
    try {
        ress = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new java.io.StringReader("<Resources></Resources>")));
    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e);
    }

    if (resourceListFromTarget.size() != 0) {
        Node copy = target.getOwnerDocument().importNode(ress.getDocumentElement(), true);

        target.appendChild(copy);

        for (int f = 0; f < resourceListFromTarget.size(); f++) {

            Node res = policy.getOwnerDocument().importNode(resourceListFromTarget.elementAt(f).getChildNodes()
                    .item(3).getChildNodes().item(3).getChildNodes().item(1), true);

            copy.appendChild(res);

        }
    }
}

From source file:org.regenstrief.util.XMLUtil.java

/**
 * Strips namespaces and prefixes from a Node tree
 * //from www  . j a v  a  2 s.  com
 * @param n the root Node
 * @return the stripped Node
 **/
public final static Node stripNamespaces(final Node n) {
    if (n == null) {
        return null;
    }

    final Document doc = n.getOwnerDocument();
    if (n instanceof Element) {
        final Element eOld = (Element) n;
        final Element eNew = doc.createElement(getLocalName(eOld));
        final NamedNodeMap map = eOld.getAttributes();
        for (int i = 0, size = size(map); i < size; i++) {
            final Attr attr = (Attr) map.item(i);
            String name = attr.getName();
            if (name == null) {
                name = attr.getLocalName();
            }
            if (!("xmlns".equals(name) || ((name != null) && name.startsWith("xmlns:"))
                    || "xmlns".equals(attr.getPrefix()))) {
                final int j = name.indexOf(':');
                eNew.setAttribute(j < 0 ? name : name.substring(j + 1), attr.getValue());
            }
        }
        final NodeList list = n.getChildNodes();
        for (int i = 0, size = size(list); i < size; i++) {
            appendChild(eNew, stripNamespaces(list.item(i)));
        }
        return eNew;
    } else if (n instanceof Attr) {
        return null;
    }
    return n.cloneNode(false);
}

From source file:org.silverpeas.SilverpeasSettings.xml.transform.XPathTransformer.java

/**
 * Transform the DOM tree using the configuration.
 * @param configuration the transformation configuration.
 * @param doc the DOM tree to be updated.
 *///from  w  w  w .  j  a v a  2s .  c  om
protected void applyTransformation(XmlConfiguration configuration, Document doc) {
    List<Parameter> parameters = configuration.getParameters();
    for (Parameter parameter : parameters) {
        displayMessageln("\t" + parameter.getKey() + " (mode:" + parameter.getMode() + ")");
        Node rootXpathNode = getMatchingNode(parameter.getKey(), doc);
        if (rootXpathNode != null) {
            for (Value value : parameter.getValues()) {
                switch (value.getMode()) {
                case XmlTreeHandler.MODE_INSERT: {
                    createNewNode(doc, rootXpathNode, value);
                }
                    break;
                case XmlTreeHandler.MODE_DELETE: {
                    Node deletedNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    rootXpathNode.removeChild(deletedNode);
                }
                    break;
                case XmlTreeHandler.MODE_UPDATE: {
                    Node oldNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    if (oldNode == null) {
                        createNewNode(doc, rootXpathNode, value);
                    } else {
                        if (rootXpathNode.equals(oldNode)) {
                            rootXpathNode = rootXpathNode.getParentNode();
                        }
                        Node newNode = oldNode.cloneNode(true);
                        if (oldNode instanceof Element) {
                            ((Element) newNode).setTextContent(value.getValue());
                            rootXpathNode.replaceChild(newNode, oldNode);
                        } else {
                            ((Attr) newNode).setValue(value.getValue());
                            rootXpathNode.getAttributes().setNamedItem(newNode);
                        }

                    }
                    break;
                }
                }
            }
        }
    }
}

From source file:org.silverpeas.util.xml.transform.XPathTransformer.java

/**
 * Transform the DOM tree using the configuration.
 *
 * @param configuration the transformation configuration.
 * @param doc the DOM tree to be updated.
 *///  w w  w. ja  v  a 2  s  . c  o  m
protected void applyTransformation(XmlConfiguration configuration, Document doc) {
    List<Parameter> parameters = configuration.getParameters();
    for (Parameter parameter : parameters) {
        console.printMessage('\t' + parameter.getKey() + " (mode:" + parameter.getMode() + ')');
        Node rootXpathNode = getMatchingNode(parameter.getKey(), doc);
        if (rootXpathNode != null) {
            for (Value value : parameter.getValues()) {
                switch (value.getMode()) {
                case XmlTreeHandler.MODE_INSERT: {
                    createNewNode(doc, rootXpathNode, value);
                }
                    break;
                case XmlTreeHandler.MODE_DELETE: {
                    Node deletedNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    rootXpathNode.removeChild(deletedNode);
                }
                    break;
                case XmlTreeHandler.MODE_UPDATE: {
                    Node oldNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    if (oldNode == null) {
                        createNewNode(doc, rootXpathNode, value);
                    } else {
                        if (rootXpathNode.equals(oldNode)) {
                            rootXpathNode = rootXpathNode.getParentNode();
                        }
                        Node newNode = oldNode.cloneNode(true);
                        if (oldNode instanceof Element) {
                            newNode.setTextContent(value.getValue());
                            rootXpathNode.replaceChild(newNode, oldNode);
                        } else {
                            ((Attr) newNode).setValue(value.getValue());
                            rootXpathNode.getAttributes().setNamedItem(newNode);
                        }

                    }
                    break;
                }
                }
            }
        }
    }
}

From source file:org.structr.web.entity.dom.PageTest.java

public void testCloneNode() {

    try {/*from   w  w w .  j  av a 2s . co  m*/
        try (final Tx tx = app.tx()) {

            Page page = Page.createNewPage(securityContext, "srcPage");

            assertTrue(page != null);
            assertTrue(page instanceof Page);
            Node html = page.createElement("html");
            Node head = page.createElement("head");
            Node body = page.createElement("body");
            Node title = page.createElement("title");
            Node h1 = page.createElement("h1");
            Node div = page.createElement("div");
            Node p = page.createElement("p");
            try {
                // add HTML element to page
                page.appendChild(html);

                // add HEAD and BODY elements to HTML
                html.appendChild(head);
                html.appendChild(body);

                // add TITLE element to HEAD
                head.appendChild(title);

                // add H1 element to BODY
                body.appendChild(h1);

                // add DIV element to BODY
                body.appendChild(div);
                div.appendChild(p);

                // add text element to P
                p.appendChild(page.createTextNode("First Paragraph"));

                Node clone = body.cloneNode(false);

                assertTrue(isClone(clone, body));

                tx.success();

            } catch (DOMException dex) {

                throw new FrameworkException(422, dex.getMessage());
            }

        }

    } catch (FrameworkException ex) {

        fail("Unexpected exception");
    }

}

From source file:sf.net.experimaestro.utils.JSUtils.java

public static Object toDOM(Scriptable scope, Object object, OptionalDocument document) {
    // Unwrap if needed (if this is not a JSBaseObject)
    if (object instanceof Wrapper && !(object instanceof JSBaseObject))
        object = ((Wrapper) object).unwrap();

    // It is already a DOM node
    if (object instanceof Node)
        return object;

    if (object instanceof XMLObject) {
        final XMLObject xmlObject = (XMLObject) object;
        String className = xmlObject.getClassName();

        if (className.equals("XMLList")) {
            LOGGER.debug("Transforming from XMLList [%s]", object);
            final Object[] ids = xmlObject.getIds();
            if (ids.length == 1)
                return toDOM(scope, xmlObject.get((Integer) ids[0], xmlObject), document);

            Document doc = XMLUtils.newDocument();
            DocumentFragment fragment = doc.createDocumentFragment();

            for (int i = 0; i < ids.length; i++) {
                Node node = (Node) toDOM(scope, xmlObject.get((Integer) ids[i], xmlObject), document);
                if (node instanceof Document)
                    node = ((Document) node).getDocumentElement();
                fragment.appendChild(doc.adoptNode(node));
            }/*ww w  . j  a  va  2s. co m*/

            return fragment;
        }

        // XML node
        if (className.equals("XML")) {
            // FIXME: this strips all whitespaces!
            Node node = XMLLibImpl.toDomNode(object);
            LOGGER.debug("Got node from JavaScript [%s / %s] from [%s]", node.getClass(),
                    XMLUtils.toStringObject(node), object.toString());

            if (node instanceof Document)
                node = ((Document) node).getDocumentElement();

            node = document.get().adoptNode(node.cloneNode(true));
            return node;
        }

        throw new RuntimeException(format("Not implemented: convert %s to XML", className));

    }

    if (object instanceof NativeArray) {
        NativeArray array = (NativeArray) object;
        ArrayNodeList list = new ArrayNodeList();
        for (Object x : array) {
            Object o = toDOM(scope, x, document);
            if (o instanceof Node)
                list.add(document.cloneAndAdopt((Node) o));
            else {
                for (Node node : XMLUtils.iterable((NodeList) o)) {
                    list.add(document.cloneAndAdopt(node));
                }
            }
        }
        return list;
    }

    if (object instanceof NativeObject) {
        // JSON case: each key of the JS object is an XML element
        NativeObject json = (NativeObject) object;
        ArrayNodeList list = new ArrayNodeList();

        for (Object _id : json.getIds()) {

            String jsQName = JSUtils.toString(_id);

            if (jsQName.length() == 0) {
                final Object seq = toDOM(scope, json.get(jsQName, json), document);
                for (Node node : XMLUtils.iterable(seq)) {
                    if (node instanceof Document)
                        node = ((Document) node).getDocumentElement();
                    list.add(document.cloneAndAdopt(node));
                }
            } else if (jsQName.charAt(0) == '@') {
                final QName qname = QName.parse(jsQName.substring(1), null, new JSNamespaceBinder(scope));
                Attr attribute = document.get().createAttributeNS(qname.getNamespaceURI(),
                        qname.getLocalPart());
                StringBuilder sb = new StringBuilder();
                for (Node node : XMLUtils.iterable(toDOM(scope, json.get(jsQName, json), document))) {
                    sb.append(node.getTextContent());
                }

                attribute.setTextContent(sb.toString());
                list.add(attribute);
            } else {
                final QName qname = QName.parse(jsQName, null, new JSNamespaceBinder(scope));
                Element element = qname.hasNamespace()
                        ? document.get().createElementNS(qname.getNamespaceURI(), qname.getLocalPart())
                        : document.get().createElement(qname.getLocalPart());

                list.add(element);

                final Object seq = toDOM(scope, json.get(jsQName, json), document);
                for (Node node : XMLUtils.iterable(seq)) {
                    if (node instanceof Document)
                        node = ((Document) node).getDocumentElement();
                    node = document.get().adoptNode(node.cloneNode(true));
                    if (node.getNodeType() == Node.ATTRIBUTE_NODE)
                        element.setAttributeNodeNS((Attr) node);
                    else
                        element.appendChild(node);
                }
            }
        }

        return list;
    }

    if (object instanceof Double) {
        // Wrap a double
        final Double x = (Double) object;
        if (x.longValue() == x.doubleValue())
            return document.get().createTextNode(Long.toString(x.longValue()));
        return document.get().createTextNode(Double.toString(x));
    }

    if (object instanceof Integer) {
        return document.get().createTextNode(Integer.toString((Integer) object));
    }

    if (object instanceof CharSequence) {
        return document.get().createTextNode(object.toString());
    }

    if (object instanceof UniqueTag)
        throw new XPMRuntimeException("Undefined cannot be converted to XML", object.getClass());

    if (object instanceof JSNode) {
        Node node = ((JSNode) object).getNode();
        if (document.has()) {
            if (node instanceof Document)
                node = ((Document) node).getDocumentElement();
            return document.get().adoptNode(node);
        }
        return node;
    }

    if (object instanceof JSNodeList) {
        return ((JSNodeList) object).getList();
    }

    if (object instanceof Scriptable) {
        ((Scriptable) object).getDefaultValue(String.class);
    }

    // By default, convert to string
    return document.get().createTextNode(object.toString());
}

From source file:sf.net.experimaestro.utils.JSUtils.java

/**
 * Converts a JavaScript object into an XML document
 *
 * @param srcObject The javascript object to convert
 * @param wrapName  If the object is not already a document and has more than one
 *                  element child (or zero), use this to wrap the elements
 * @return//from w  ww.  j ava  2 s  .  com
 */
public static Document toDocument(Scriptable scope, Object srcObject, QName wrapName) {
    final Object object = toDOM(scope, srcObject);

    if (object instanceof Document)
        return (Document) object;

    Document document = XMLUtils.newDocument();

    // Add a new root element if needed
    NodeList childNodes;

    if (!(object instanceof Node)) {
        childNodes = (NodeList) object;
    } else {
        final Node dom = (Node) object;
        if (dom.getNodeType() == Node.ELEMENT_NODE) {
            childNodes = new NodeList() {
                @Override
                public Node item(int index) {
                    if (index == 0)
                        return dom;
                    throw new IndexOutOfBoundsException(Integer.toString(index) + " out of bounds");
                }

                @Override
                public int getLength() {
                    return 1;
                }
            };
        } else
            childNodes = dom.getChildNodes();
    }

    int elementCount = 0;
    for (int i = 0; i < childNodes.getLength(); i++)
        if (childNodes.item(i).getNodeType() == Node.ELEMENT_NODE)
            elementCount++;

    Node root = document;
    if (elementCount != 1) {
        root = document.createElementNS(wrapName.getNamespaceURI(), wrapName.getLocalPart());
        document.appendChild(root);
    }

    // Copy back in the DOM
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        node = node.cloneNode(true);
        document.adoptNode(node);
        root.appendChild(node);
    }

    return document;
}