Example usage for org.w3c.dom Element cloneNode

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

Introduction

In this page you can find the example usage for org.w3c.dom Element 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:com.bluexml.xforms.actions.GetAction.java

/**
 * Returns the instance for FormWorkflow forms, which includes the instance for the data form. <br/>
 * NOTE: the form name is expected in the returned instance (incl. process & task names), and
 * the data form is nested under the [form name] tag.
 * <p>//  w  w w.ja  v a 2 s  .  com
 * Format:
 * 
 * <pre>
 * &lt;workflow&gt; &lt;!-- this is the node returned by getDocumentElement() on XForms instances --&gt;
 *   &lt;FORM NAME&gt;
 *     PROPERTIES OF THE WORFKLOW
 *     &lt;DATA FORM &gt;
 *       THE DATA FORM'S PROPERTIES
 *     &lt;/DATA FORM &gt;
 *   &lt;/FORM NAME&gt;
 * &lt;/workflow&gt;
 * </pre>
 */
private Document getInstanceWorkflow(Page currentPage, String wkFormName) throws ServletException {
    //
    // get the instance for the task
    Document docWkflw = controller.getInstanceWorkflow(transaction, wkFormName);
    controller.workflowPatchInstance(transaction, wkFormName, docWkflw, currentPage.getWkflwInstanceId());
    //
    // get the instance of the attached data form
    String dataId = currentPage.getDataId();
    String dataFormName = controller.getUnderlyingDataFormForWorkflow(wkFormName);
    if (dataFormName == null) {
        return docWkflw;
    }
    GetInstanceFormBean bean = new GetInstanceFormBean(dataFormName, dataId, false, false, null);
    Document docForm = controller.getInstanceForm(transaction, bean);
    //
    // we need to nest the data form instance under workflow
    Element wkDocElt = docWkflw.getDocumentElement();
    List<Element> childrenWk = DOMUtil.getAllChildren(wkDocElt);
    Element wkElt = DOMUtil.getOneElementByTagName(childrenWk, wkFormName);

    Element clone;
    List<Element> children = DOMUtil.getAllChildren(docForm.getDocumentElement());
    Element dataElt = DOMUtil.getOneElementByTagName(children, dataFormName);
    clone = (Element) dataElt.cloneNode(true);
    docWkflw.adoptNode(clone);
    wkElt.appendChild(clone);
    //
    // also copy supplementary tags that are added for internal usage (SIDEDataType, etc.)
    for (Element child : children) {
        if (child.getTagName().equals(dataFormName) == false) {
            clone = (Element) child.cloneNode(true);
            docWkflw.adoptNode(clone);
            wkDocElt.appendChild(clone);
        }
    }
    if (logger.isDebugEnabled()) {
        DOMUtil.logXML(docWkflw, true, ">> Returning instance document for workflow form: " + wkFormName);
    }

    return docWkflw;
}

From source file:org.ambraproject.search.service.IndexingServiceImpl.java

/**
 *  Add the article-strkImg tag as a child  to the article-meta
 *  tag of the article ml.//from   w w w . j  a v  a  2s  . com
 */
private Document addStrikingImage(Document doc, String strkImagURI) {
    NodeList metaNodeLst = doc.getElementsByTagName("article-meta");
    Node metaNode = metaNodeLst.item(0);
    Element strkImgElem = doc.createElement("article-strkImg");

    strkImgElem.setTextContent(strkImagURI);
    metaNode.appendChild(strkImgElem.cloneNode(true));
    return doc;
}

From source file:com.evolveum.midpoint.prism.lex.dom.DomLexicalWriter.java

private void serializeSchema(SchemaXNode xschema, Element parentElement) {
    Element schemaElement = xschema.getSchemaElement();
    if (schemaElement == null) {
        return;/*from www  . j a v a2  s  .c  o  m*/
    }
    Element clonedSchema = (Element) schemaElement.cloneNode(true);
    doc.adoptNode(clonedSchema);
    parentElement.appendChild(clonedSchema);
}

From source file:com.quest.keycloak.protocol.wsfed.builders.RequestSecurityTokenResponseBuilder.java

protected Document signAssertion(Document samlDocument) throws ProcessingException {
    Element originalAssertionElement = samlDocument.getDocumentElement(); //org.keycloak.saml.common.util.DocumentUtil.getChildElement(samlDocument.getDocumentElement(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()));

    if (originalAssertionElement == null)
        return samlDocument;
    Node clonedAssertionElement = originalAssertionElement.cloneNode(true);
    Document temporaryDocument;/*w w  w.  ja v  a  2  s .c  o  m*/

    try {
        temporaryDocument = org.keycloak.saml.common.util.DocumentUtil.createDocument();
    } catch (ConfigurationException e) {
        throw new ProcessingException(e);
    }

    temporaryDocument.adoptNode(clonedAssertionElement);
    temporaryDocument.appendChild(clonedAssertionElement);

    signDocument(temporaryDocument);

    return temporaryDocument;
}

From source file:com.alfaariss.oa.util.saml2.profile.metadata.AbstractMetadataProfile.java

/**
 * Performs a deep clone of the supplied object. 
 * @param object The XML object to be cloned.
 * @return A deep clone of the supplied object.
 * @throws OAException If marshalling fails
 *///from w ww.  j  ava  2s .c om
protected XMLObject cloneXMLObject(XMLObject object) throws OAException {
    Element eClone = null;
    try {
        Element eSource = object.getDOM();
        if (eSource == null) {
            Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(object);
            if (marshaller == null) {
                _logger.error("No marshaller registered for " + object.getElementQName()
                        + ", unable to marshall metadata");
                throw new OAException(SystemErrors.ERROR_INTERNAL);
            }
            eSource = marshaller.marshall(object);
        }

        eClone = (Element) eSource.cloneNode(true);

        Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(eClone);
        if (unmarshaller == null) {
            _logger.error("No unmarshaller registered for " + eClone.getNodeName()
                    + ", unable to unmarshall metadata");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        return unmarshaller.unmarshall(eClone);
    } catch (MarshallingException e) {
        _logger.debug("Could not marshall object: " + object.getElementQName(), e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (UnmarshallingException e) {
        _logger.debug("Could not unmarshall object: " + eClone.getNodeName(), e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.warn("Internal Error while cloning object: " + object.getElementQName(), e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java

/**
 * This method takes the ER response and converts the Java objects to the Merge Response XML.
 * //from   w  ww.j a v a 2  s.co m
 * @param entityContainerNode
 * @param results
 * @param recordLimit
 * @param attributeParametersNode
 * @return
 * @throws ParserConfigurationException
 * @throws XPathExpressionException
 * @throws TransformerException
 */
private Document createResponseMessage(Node entityContainerNode, EntityResolutionResults results,
        Node attributeParametersNode, int recordLimit) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    Document resultDocument = dbf.newDocumentBuilder().newDocument();

    Element entityMergeResultMessageElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityMergeResultMessage");
    resultDocument.appendChild(entityMergeResultMessageElement);

    Element entityContainerElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityContainer");
    entityMergeResultMessageElement.appendChild(entityContainerElement);

    NodeList inputEntityNodes = (NodeList) xpath.evaluate("er-ext:Entity", entityContainerNode,
            XPathConstants.NODESET);
    Collection<Element> inputEntityElements = null;
    if (attributeParametersNode == null) {
        inputEntityElements = new ArrayList<Element>();
    } else {
        inputEntityElements = TreeMultiset
                .create(new EntityElementComparator((Element) attributeParametersNode));
        //inputEntityElements = new ArrayList<Element>();
    }

    for (int i = 0; i < inputEntityNodes.getLength(); i++) {
        inputEntityElements.add((Element) inputEntityNodes.item(i));
    }

    if (attributeParametersNode == null) {
        LOG.warn("Attribute Parameters element was null, so records will not be sorted");
    }
    //Collections.sort((List<Element>) inputEntityElements, new EntityElementComparator((Element) attributeParametersNode));

    if (inputEntityElements.size() != inputEntityNodes.getLength()) {
        LOG.error("Lost elements in ER output sorting.  Input count=" + inputEntityNodes.getLength()
                + ", output count=" + inputEntityElements.size());
    }

    for (Element e : inputEntityElements) {
        Node clone = resultDocument.adoptNode(e.cloneNode(true));
        resultDocument.renameNode(clone, EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                e.getLocalName());
        entityContainerElement.appendChild(clone);
    }

    Element mergedRecordsElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "MergedRecords");
    entityMergeResultMessageElement.appendChild(mergedRecordsElement);

    if (results != null) {

        List<RecordWrapper> records = results.getRecords();

        // Loop through RecordWrappers to extract info to create merged records
        for (RecordWrapper record : records) {
            LOG.debug("  !#!#!#!# Record 1, id=" + record.getExternalId() + ", externals="
                    + record.getRelatedIds());

            // Create Merged Record Container
            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            // Create Original Record Reference for 'first record'
            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", record.getExternalId());
            mergedRecordElement.appendChild(originalRecordRefElement);

            // Loop through and add any related records
            for (String relatedRecordId : record.getRelatedIds()) {
                originalRecordRefElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
                originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                        "ref", relatedRecordId);
                mergedRecordElement.appendChild(originalRecordRefElement);
            }

            // Create Merge Quality Element
            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            Set<AttributeStatistics> stats = results.getStatisticsForRecord(record.getExternalId());
            for (AttributeStatistics stat : stats) {
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(stat.getAttributeName());
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode(String.valueOf(stat.getAverageStringDistance()));
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument
                        .createTextNode(String.valueOf(stat.getStandardDeviationStringDistance()));
                sdElement.appendChild(contentNode);

            }
        }

    } else {

        for (Element e : inputEntityElements) {

            String id = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "id");

            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", id);
            mergedRecordElement.appendChild(originalRecordRefElement);

            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            XPath xp = XPathFactory.newInstance().newXPath();
            xp.setNamespaceContext(new EntityResolutionNamespaceContext());
            NodeList attributeParameterNodes = (NodeList) xp.evaluate("er-ext:AttributeParameter",
                    attributeParametersNode, XPathConstants.NODESET);
            for (int i = 0; i < attributeParameterNodes.getLength(); i++) {
                String attributeName = xp.evaluate("er-ext:AttributeXPath", attributeParametersNode);
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(attributeName);
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode("0.0");
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument.createTextNode("0.0");
                sdElement.appendChild(contentNode);
            }

        }

    }

    Element recordLimitExceededElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "RecordLimitExceededIndicator");
    recordLimitExceededElement.setTextContent(new Boolean(results == null).toString());
    entityMergeResultMessageElement.appendChild(recordLimitExceededElement);

    return resultDocument;

}

From source file:com.evolveum.midpoint.prism.util.JaxbTestUtil.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public Element toDomElement(Object jaxbElement, Document doc, boolean adopt, boolean clone, boolean deep)
        throws JAXBException {
    if (jaxbElement == null) {
        return null;
    }/*from   w  w w. ja v  a 2s .c  om*/
    if (jaxbElement instanceof Element) {
        Element domElement = (Element) jaxbElement;
        if (clone) {
            domElement = (Element) domElement.cloneNode(deep);
        }
        if (domElement.getOwnerDocument().equals(doc)) {
            return domElement;
        }
        if (adopt) {
            doc.adoptNode(domElement);
        }
        return domElement;
    } else if (jaxbElement instanceof JAXBElement) {
        return marshalElementToDom((JAXBElement) jaxbElement, doc);
    } else {
        throw new IllegalArgumentException(
                "Not an element: " + jaxbElement + " (" + jaxbElement.getClass().getName() + ")");
    }
}

From source file:com.alfaariss.oa.authentication.remote.saml2.profile.metadata.SPMetadata.java

private SPSSODescriptor cloneSPSSODescriptor(SPSSODescriptor orig) throws OAException {
    SPSSODescriptor spRoleDescriptor = null;
    try {//  ww  w  .  j  a  v  a  2  s .c  om
        Element eSource = orig.getDOM();
        if (eSource == null) {
            Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(orig);
            if (marshaller == null) {
                _logger.error("No marshaller registered for " + orig.getElementQName()
                        + ", unable to marshall metadata");
                throw new OAException(SystemErrors.ERROR_INTERNAL);
            }
            eSource = marshaller.marshall(orig);
        }

        SPSSODescriptorBuilder spSSOBuilder = (SPSSODescriptorBuilder) _builderFactory
                .getBuilder(SPSSODescriptor.DEFAULT_ELEMENT_NAME);

        spRoleDescriptor = spSSOBuilder.buildObject();

        spRoleDescriptor.setDOM((Element) eSource.cloneNode(true));
    } catch (MarshallingException e) {
        _logger.debug("Could not marshall object: " + orig.getElementQName(), e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not clone SPSSODescriptor", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    return spRoleDescriptor;
}

From source file:com.alfaariss.oa.profile.saml2.profile.metadata.IDPMetadata.java

private IDPSSODescriptor cloneIDPSSODescriptor(IDPSSODescriptor orig) throws OAException {
    IDPSSODescriptor idpRoleDescriptor = null;
    try {//www  . jav a 2 s .  c  om
        Element eSource = orig.getDOM();
        if (eSource == null) {
            Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(orig);
            if (marshaller == null) {
                _logger.error("No marshaller registered for " + orig.getElementQName()
                        + ", unable to marshall metadata");
                throw new OAException(SystemErrors.ERROR_INTERNAL);
            }
            eSource = marshaller.marshall(orig);
        }

        IDPSSODescriptorBuilder idpSSOBuilder = (IDPSSODescriptorBuilder) _builderFactory
                .getBuilder(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);

        idpRoleDescriptor = idpSSOBuilder.buildObject();

        idpRoleDescriptor.setDOM((Element) eSource.cloneNode(true));
    } catch (MarshallingException e) {
        _logger.debug("Could not marshall object: " + orig.getElementQName(), e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } catch (OAException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not clone IDPSSODescriptor", e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    return idpRoleDescriptor;
}