Example usage for org.w3c.dom Document importNode

List of usage examples for org.w3c.dom Document importNode

Introduction

In this page you can find the example usage for org.w3c.dom Document importNode.

Prototype

public Node importNode(Node importedNode, boolean deep) throws DOMException;

Source Link

Document

Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.

Usage

From source file:org.apache.xml.security.samples.signature.CreateMerlinsExampleSixteen.java

/**
 * Method createObject4//from w w  w .  j  a va 2 s . c  o m
 *
 * @param sig
 *
 * @throws Exception
 */
public static Element createObject4(XMLSignature sig) throws Exception {

    Document doc = sig.getElement().getOwnerDocument();
    String BaseURI = sig.getBaseURI();
    Manifest manifest = new Manifest(doc);
    manifest.addResourceResolver(new OfflineResolver());

    manifest.setId("manifest-1");
    manifest.addDocument(BaseURI, "http://www.w3.org/TR/xml-stylesheet", null, Constants.ALGO_ID_DIGEST_SHA1,
            "manifest-reference-1", null);
    manifest.addDocument(BaseURI, "#reference-1", null, Constants.ALGO_ID_DIGEST_SHA1, null,
            "http://www.w3.org/2000/09/xmldsig#Reference");

    //J-
    String xslt = "" + "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'\n"
            + "                xmlns='http://www.w3.org/TR/xhtml1/strict' \n"
            + "                exclude-result-prefixes='foo' \n" + "                version='1.0'>\n"
            + "  <xsl:output encoding='UTF-8' \n" + "              indent='no' \n"
            + "              method='xml' />\n" + "  <xsl:template match='/'>\n" + "    <html>\n"
            + "      <head>\n" + "        <title>Notaries</title>\n" + "      </head>\n" + "      <body>\n"
            + "        <table>\n" + "          <xsl:for-each select='Notaries/Notary'>\n" + "            <tr>\n"
            + "              <th>\n" + "                <xsl:value-of select='@name' />\n"
            + "              </th>\n" + "            </tr>\n" + "          </xsl:for-each>\n"
            + "        </table>\n" + "      </body>\n" + "    </html>\n" + "  </xsl:template>\n"
            + "</xsl:stylesheet>\n";
    //J+
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document docxslt = db.parse(new ByteArrayInputStream(xslt.getBytes()));
    Node xslElem = docxslt.getDocumentElement();
    Node xslElemImported = doc.importNode(xslElem, true);
    Transforms transforms = new Transforms(doc);

    transforms.addTransform(Transforms.TRANSFORM_XSLT, (Element) xslElemImported);
    manifest.addDocument(BaseURI, "#notaries", transforms, Constants.ALGO_ID_DIGEST_SHA1, null, null);

    return manifest.getElement();
}

From source file:org.apereo.portal.layout.dlm.EditManager.java

/**
   Evaluate whether attribute changes exist in the ilfChild and if so
   apply them. Returns true if some changes existed. If changes existed
   but matched those in the original node then they are not applicable,
   are removed from the editSet, and false is returned.
*///from   w w  w.j  a  va2  s.co m
public static boolean applyEditSet(Element plfChild, Element original) {
    // first get edit set if it exists
    Element editSet = null;
    try {
        editSet = getEditSet(plfChild, null, null, false);
    } catch (Exception e) {
        // should never occur unless problem during create in getEditSet
        // and we are telling it not to create.
        return false;
    }

    if (editSet == null || editSet.getChildNodes().getLength() == 0)
        return false;

    if (original.getAttribute(Constants.ATT_EDIT_ALLOWED).equals("false")) {
        // can't change anymore so discard changes
        plfChild.removeChild(editSet);
        return false;
    }

    Document ilf = original.getOwnerDocument();
    boolean attributeChanged = false;
    Element edit = (Element) editSet.getFirstChild();

    while (edit != null) {
        String attribName = edit.getAttribute(Constants.ATT_NAME);
        Attr attr = plfChild.getAttributeNode(attribName);

        // preferences are only updated at preference storage time so
        // if a preference change exists in the edit set assume it is
        // still valid so that the node being edited will persist in
        // the PLF.
        if (edit.getNodeName().equals(Constants.ELM_PREF))
            attributeChanged = true;
        else if (attr == null) {
            // attribute removed. See if needs removing in original.
            attr = original.getAttributeNode(attribName);
            if (attr == null) // edit irrelevant,
                editSet.removeChild(edit);
            else {
                // edit differs, apply to original
                original.removeAttribute(attribName);
                attributeChanged = true;
            }
        } else {
            // attribute there, see if original is also there
            Attr origAttr = original.getAttributeNode(attribName);
            if (origAttr == null) {
                // original attribute isn't defined so need to add
                origAttr = (Attr) ilf.importNode(attr, true);
                original.setAttributeNode(origAttr);
                attributeChanged = true;
            } else {
                // original attrib found, see if different
                if (attr.getValue().equals(origAttr.getValue())) {
                    // they are the same, edit irrelevant
                    editSet.removeChild(edit);
                } else {
                    // edit differs, apply to original
                    origAttr.setValue(attr.getValue());
                    attributeChanged = true;
                }
            }
        }
        edit = (Element) edit.getNextSibling();
    }
    return attributeChanged;
}

From source file:org.apereo.portal.layout.dlm.ILFBuilder.java

public static Document constructILF(Document PLF, List<Document> sequence, IPerson person) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Constructing ILF for IPerson='" + person + "'");
    }/*w w  w  .ja va  2s. co m*/
    // first construct the destination document and root element. The root
    // element should be a complete copy of the PLF's root including its
    // node identifier in the new document. This requires the use of
    // the implementation class to set the identifier for that node
    // in the document.

    Document result = DocumentFactory.getThreadDocument();
    Element plfLayout = PLF.getDocumentElement();
    Element ilfLayout = (Element) result.importNode(plfLayout, false);
    result.appendChild(ilfLayout);
    Element plfRoot = (Element) plfLayout.getFirstChild();
    Element ilfRoot = (Element) result.importNode(plfRoot, false);
    ilfLayout.appendChild(ilfRoot);

    if (ilfRoot.getAttribute(Constants.ATT_ID) != null)
        ilfRoot.setIdAttribute(Constants.ATT_ID, true);

    // build the auth principal for determining if pushed channels can be 
    // used by this user
    EntityIdentifier ei = person.getEntityIdentifier();
    AuthorizationService authS = AuthorizationService.instance();
    IAuthorizationPrincipal ap = authS.newPrincipal(ei.getKey(), ei.getType());

    // now merge fragments one at a time into ILF document

    for (final Document document : sequence) {
        mergeFragment(document, result, ap);
    }
    return result;
}

From source file:org.apereo.portal.layout.dlm.ILFBuilder.java

/**
 * @param source parent of children//from   w w  w .  j a  v  a  2 s . c  o  m
 * @param dest receiver of children
 * @param ap User's authorization principal for determining if they can view a channel
 * @param visitedNodes A Set of nodes from the source tree that have been visited to get to this node, used to ensure a loop doesn't exist in the source tree.
 * @throws AuthorizationException
 */
private static void mergeChildren(Element source, Element dest, IAuthorizationPrincipal ap, Set visitedNodes)
        throws AuthorizationException {
    //Record this node in the visited nodes set. If add returns false a loop has been detected
    if (!visitedNodes.add(source)) {
        final String msg = "mergeChildren has encountered a loop in the source DOM. currentNode='" + source
                + "', currentDepth='" + visitedNodes.size() + "', visitedNodes='" + visitedNodes + "'";
        final IllegalStateException ise = new IllegalStateException(msg);
        LOG.error(msg, ise);

        printNodeToDebug(source, "Source");
        printNodeToDebug(dest, "Dest");

        throw ise;
    }

    Document destDoc = dest.getOwnerDocument();

    Node item = source.getFirstChild();
    while (item != null) {
        if (item instanceof Element) {

            Element child = (Element) item;
            Element newChild = null;

            if (null != child && mergeAllowed(child, ap)) {
                newChild = (Element) destDoc.importNode(child, false);
                dest.appendChild(newChild);
                String id = newChild.getAttribute(Constants.ATT_ID);
                if (id != null && !id.equals(""))
                    newChild.setIdAttribute(Constants.ATT_ID, true);
                mergeChildren(child, newChild, ap, visitedNodes);
            }
        }

        item = item.getNextSibling();
    }

    //Remove this node from the visited nodes set
    visitedNodes.remove(source);
}

From source file:org.apereo.portal.layout.dlm.PLFIntegrator.java

/**
   This method copies a plf node and any of its children into the passed
   in compViewParent./*from  ww  w.j a v a 2s.c  om*/
 */
static Element appendChild(Element plfChild, Element parent, boolean copyChildren) {
    Document document = parent.getOwnerDocument();
    Element copy = (Element) document.importNode(plfChild, false);
    parent.appendChild(copy);

    // set the identifier for the doc if warrented
    String id = copy.getAttribute(Constants.ATT_ID);
    if (id != null && !id.equals(""))
        copy.setIdAttribute(Constants.ATT_ID, true);

    if (copyChildren) {
        NodeList children = plfChild.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            if (children.item(i) instanceof Element)
                appendChild((Element) children.item(i), copy, true);
        }
    }
    return copy;
}

From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java

/**
 * Method for acquiring copies of fragment layouts to assist in debugging.
 * No infrastructure code calls this but channels designed to expose the
 * structure of the cached fragments use this to obtain copies.
 * @return Map// w  w  w  .j  a v a 2  s  . c  o  m
 */
public Map<String, Document> getFragmentLayoutCopies() {
    // since this is only visible in fragment list in administrative portlet, use default portal locale
    final Locale defaultLocale = LocaleManager.getPortalLocales()[0];

    final Map<String, Document> layouts = new HashMap<String, Document>();

    final List<FragmentDefinition> definitions = this.fragmentUtils.getFragmentDefinitions();
    for (final FragmentDefinition fragmentDefinition : definitions) {
        final Document layout = DocumentFactory.getThreadDocument();
        final UserView userView = this.fragmentUtils.getUserView(fragmentDefinition, defaultLocale);
        if (userView == null) {
            logger.warn("No UserView found for FragmentDefinition {}, it will be skipped.",
                    fragmentDefinition.getName());
            continue;
        }
        final Node copy = layout.importNode(userView.getLayout().getDocumentElement(), true);
        layout.appendChild(copy);
        layouts.put(fragmentDefinition.getOwnerId(), layout);
    }
    return layouts;
}

From source file:org.broadleafcommerce.common.extensibility.context.merge.handlers.NodeReplaceInsert.java

private List<Node> matchNodes(List<Node> exhaustedNodes, Node[] primaryNodes, ArrayList<Node> list) {
    List<Node> usedNodes = new ArrayList<Node>(20);
    Iterator<Node> itr = list.iterator();
    Node parentNode = primaryNodes[0].getParentNode();
    Document ownerDocument = parentNode.getOwnerDocument();
    while (itr.hasNext()) {
        Node node = itr.next();// w  w  w.j  av a2  s  .c  o  m
        if (Element.class.isAssignableFrom(node.getClass()) && !exhaustedNodesContains(exhaustedNodes, node)) {

            if (LOG.isDebugEnabled()) {
                StringBuffer sb = new StringBuffer();
                sb.append("matching node for replacement: ");
                sb.append(node.getNodeName());
                int attrLength = node.getAttributes().getLength();
                for (int j = 0; j < attrLength; j++) {
                    sb.append(" : (");
                    sb.append(node.getAttributes().item(j).getNodeName());
                    sb.append("/");
                    sb.append(node.getAttributes().item(j).getNodeValue());
                    sb.append(")");
                }
                LOG.debug(sb.toString());
            }
            if (!checkNode(usedNodes, primaryNodes, node)) {
                //simply append the node if all the above fails
                Node newNode = ownerDocument.importNode(node.cloneNode(true), true);
                parentNode.appendChild(newNode);
                usedNodes.add(node);
            }
        }
    }
    return usedNodes;
}

From source file:org.chiba.tools.schemabuilder.AbstractSchemaFormBuilder.java

/**
 * builds a form from a XML schema./*www. j  a v  a 2s  . c  om*/
 *
 * @param inputURI the URI of the Schema to be used
 * @return __UNDOCUMENTED__
 * @throws FormBuilderException __UNDOCUMENTED__
 */
public Document buildForm(String inputURI) throws FormBuilderException {
    try {
        this.loadSchema(inputURI);
        buildTypeTree(schema);

        //refCounter = 0;
        counter = new HashMap();

        Document xForm = createFormTemplate(_rootTagName, _rootTagName + " Form",
                getProperty(CSS_STYLE_PROP, DEFAULT_CSS_STYLE_PROP));

        //this.buildInheritenceTree(schema);
        Element envelopeElement = xForm.getDocumentElement();

        //Element formSection = (Element) envelopeElement.getElementsByTagNameNS(CHIBA_NS, "form").item(0);
        //Element formSection =(Element) envelopeElement.getElementsByTagName("body").item(0);
        //find form element: last element created
        NodeList children = xForm.getDocumentElement().getChildNodes();
        int nb = children.getLength();
        Element formSection = (Element) children.item(nb - 1);

        Element modelSection = (Element) envelopeElement.getElementsByTagNameNS(XFORMS_NS, "model").item(0);

        //add XMLSchema if we use schema types
        if (_useSchemaTypes && modelSection != null) {
            modelSection.setAttributeNS(XFORMS_NS, this.getXFormsNSPrefix() + "schema", inputURI);
        }

        //change stylesheet
        String stylesheet = this.getStylesheet();

        if ((stylesheet != null) && !stylesheet.equals("")) {
            envelopeElement.setAttributeNS(CHIBA_NS, this.getChibaNSPrefix() + "stylesheet", stylesheet);
        }

        // TODO: Commented out because comments aren't output properly by the Transformer.
        //String comment = "This XForm was automatically generated by " + this.getClass().getName() + " on " + (new Date()) + System.getProperty("line.separator") + "    from the '" + rootElementName + "' element from the '" + schema.getSchemaTargetNS() + "' XML Schema.";
        //xForm.insertBefore(xForm.createComment(comment),envelopeElement);
        //xxx XSDNode node = findXSDNodeByName(rootElementTagName,schemaNode.getElementSet());

        //check if target namespace
        //no way to do this with XS API ? load DOM document ?
        //TODO: find a better way to find the targetNamespace
        try {
            Document domDoc = DOMUtil.parseXmlFile(inputURI, true, false);
            if (domDoc != null) {
                Element root = domDoc.getDocumentElement();
                targetNamespace = root.getAttribute("targetNamespace");
                if (targetNamespace != null && targetNamespace.equals(""))
                    targetNamespace = null;
            }
        } catch (Exception ex) {
            LOGGER.error("Schema not loaded as DOM document: " + ex.getMessage());
        }

        //if target namespace & we use the schema types: add it to form ns declarations
        if (_useSchemaTypes && targetNamespace != null && !targetNamespace.equals("")) {
            envelopeElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:schema", targetNamespace);
        }

        //TODO: WARNING: in Xerces 2.6.1, parameters are switched !!! (name, namespace)
        //XSElementDeclaration rootElementDecl =schema.getElementDeclaration(targetNamespace, _rootTagName);
        XSElementDeclaration rootElementDecl = schema.getElementDeclaration(_rootTagName, targetNamespace);

        if (rootElementDecl == null) {
            //DEBUG
            rootElementDecl = schema.getElementDeclaration(_rootTagName, targetNamespace);
            if (rootElementDecl != null && LOGGER.isDebugEnabled())
                LOGGER.debug("getElementDeclaration: inversed parameters OK !!!");

            throw new FormBuilderException("Invalid root element tag name [" + _rootTagName
                    + ", targetNamespace=" + targetNamespace + "]");
        }

        Element instanceElement = (Element) modelSection
                .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "instance"));
        this.setXFormsId(instanceElement);

        Element rootElement;

        if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_NONE) {
            rootElement = (Element) instanceElement.appendChild(
                    xForm.createElementNS(targetNamespace, getElementName(rootElementDecl, xForm)));

            String prefix = xmlSchemaInstancePrefix.substring(0, xmlSchemaInstancePrefix.length() - 1);
            rootElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:" + prefix,
                    XMLSCHEMA_INSTANCE_NAMESPACE_URI);

        } else if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_INCLUDED)
        //get the instance element
        {
            boolean ok = true;

            try {
                /*DOMResult result = new DOMResult();
                TransformerFactory trFactory =
                TransformerFactory.newInstance();
                Transformer tr = trFactory.newTransformer();
                tr.transform(_instanceSource, result);
                Document instanceDoc = (Document) result.getNode();*/
                DocumentBuilderFactory docFact = DocumentBuilderFactory.newInstance();
                docFact.setNamespaceAware(true);
                docFact.setValidating(false);
                DocumentBuilder parser = docFact.newDocumentBuilder();
                Document instanceDoc = parser.parse(new InputSource(_instanceSource.getSystemId()));

                //possibility abandonned for the moment:
                //modify the instance to add the correct "xsi:type" attributes wherever needed
                //Document instanceDoc=this.setXMLSchemaAndPSVILoad(inputURI, _instanceSource, targetNamespace);

                if (instanceDoc != null) {
                    Element instanceInOtherDoc = instanceDoc.getDocumentElement();

                    if (instanceInOtherDoc.getNodeName().equals(_rootTagName)) {
                        rootElement = (Element) xForm.importNode(instanceInOtherDoc, true);
                        instanceElement.appendChild(rootElement);

                        //add XMLSchema instance NS
                        String prefix = xmlSchemaInstancePrefix.substring(0,
                                xmlSchemaInstancePrefix.length() - 1);
                        if (!rootElement.hasAttributeNS(XMLNS_NAMESPACE_URI, prefix))
                            rootElement.setAttributeNS(XMLNS_NAMESPACE_URI, "xmlns:" + prefix,
                                    XMLSCHEMA_INSTANCE_NAMESPACE_URI);

                        //possibility abandonned for the moment:
                        //modify the instance to add the correct "xsi:type" attributes wherever needed
                        //this.addXSITypeAttributes(rootElement);
                    } else {
                        ok = false;
                    }
                } else {
                    ok = false;
                }
            } catch (Exception ex) {
                ex.printStackTrace();

                //if there is an exception we put the empty root element
                ok = false;
            }

            //if there was a problem
            if (!ok) {
                rootElement = (Element) instanceElement.appendChild(xForm.createElement(_rootTagName));
            }
        } else if (_instanceMode == AbstractSchemaFormBuilder.INSTANCE_MODE_HREF)
        //add the xlink:href attribute
        {
            instanceElement.setAttributeNS(SchemaFormBuilder.XLINK_NS, this.getXLinkNSPrefix() + "href",
                    _instanceHref);
        }

        Element formContentWrapper = _wrapper.createGroupContentWrapper(formSection);
        addElement(xForm, modelSection, formContentWrapper, rootElementDecl,
                rootElementDecl.getTypeDefinition(), "/" + getElementName(rootElementDecl, xForm));

        Element submitInfoElement = (Element) modelSection
                .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "submission"));

        //submitInfoElement.setAttributeNS(XFORMS_NS,getXFormsNSPrefix()+"id","save");
        String submissionId = this.setXFormsId(submitInfoElement);

        //action
        if (_action == null) {
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "action", "");
        } else {
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "action", _action);
        }

        //method
        if ((_submitMethod != null) && !_submitMethod.equals("")) {
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "method", _submitMethod);
        } else { //default is "post"
            submitInfoElement.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "method",
                    AbstractSchemaFormBuilder.SUBMIT_METHOD_POST);
        }

        //Element submitButton = (Element) formSection.appendChild(xForm.createElementNS(XFORMS_NS,getXFormsNSPrefix()+"submit"));
        Element submitButton = xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "submit");
        Element submitControlWrapper = _wrapper.createControlsWrapper(submitButton);
        formContentWrapper.appendChild(submitControlWrapper);
        submitButton.setAttributeNS(XFORMS_NS, getXFormsNSPrefix() + "submission", submissionId);
        this.setXFormsId(submitButton);

        Element submitButtonCaption = (Element) submitButton
                .appendChild(xForm.createElementNS(XFORMS_NS, getXFormsNSPrefix() + "label"));
        submitButtonCaption.appendChild(xForm.createTextNode("Submit"));
        this.setXFormsId(submitButtonCaption);

        return xForm;
    } catch (ParserConfigurationException x) {
        throw new FormBuilderException(x);
    } catch (java.lang.ClassNotFoundException x) {
        throw new FormBuilderException(x);
    } catch (java.lang.InstantiationException x) {
        throw new FormBuilderException(x);
    } catch (java.lang.IllegalAccessException x) {
        throw new FormBuilderException(x);
    }
}

From source file:org.chiba.xml.xforms.ChibaBean.java

private Document toDocument(Node node) throws XFormsException {
    // ensure xerces dom
    if (node instanceof org.apache.xerces.dom.DocumentImpl) {
        return (Document) node;
    }/*from  www . j av a 2s . c  o  m*/

    Document document = getDocumentBuilder().newDocument();
    if (node instanceof Document) {
        node = ((Document) node).getDocumentElement();
    }
    document.appendChild(document.importNode(node, true));

    return document;
}

From source file:org.chiba.xml.xforms.core.Instance.java

/**
 * Returns a new created instance document.
 * <p/>/*from   www.j  a va  2 s  .c om*/
 * If this instance has an original instance, it will be imported into this
 * new document. Otherwise the new document is left empty.
 *
 * @return a new created instance document.
 */
private Document createInstanceDocument() throws XFormsException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        Document document = factory.newDocumentBuilder().newDocument();

        if (this.initialInstance != null) {
            document.appendChild(document.importNode(this.initialInstance.cloneNode(true), true));

            String srcAttribute = getXFormsAttribute(SRC_ATTRIBUTE);
            if (srcAttribute == null) {
                // apply namespaces
                NamespaceResolver.applyNamespaces(this.element, document.getDocumentElement());
            }
        }

        return document;
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}