Example usage for org.w3c.dom Document adoptNode

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

Introduction

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

Prototype

public Node adoptNode(Node source) throws DOMException;

Source Link

Document

Attempts to adopt a node from another document to this document.

Usage

From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilder.java

/**
 * Builds modsCollection from mods of articles.
 *//* ww w.ja  va2 s.  c  om*/
Document mergeElements(List<Article> articles) throws DOMException {
    Document doc = db.newDocument();
    Element root = doc.createElementNS(ModsConstants.NS, "modsCollection");
    for (Article article : articles) {
        Element modsElm = article.getModsElement();
        Node n = doc.adoptNode(modsElm);
        root.appendChild(n);
    }
    doc.appendChild(root);
    return doc;
}

From source file:de.betterform.session.DefaultSerializer.java

/**
 * inlines all instances from the processor into the output document. Eventually existent @src Attributes
 * have already been removed during the 'reset' transformation.
 *
 * @param out the output document for serialization
 *///from  ww w .ja v  a2 s. c  o  m
public void inlineInstances(Document out) throws XFormsException {
    //imlining instances
    NodeInfo context = getDocumentElementContext(out);
    //iterate all models to get all instances
    List models = this.processor.getContainer().getModels();
    for (int i = 0; i < models.size(); i++) {
        Model model = (Model) models.get(i);

        List instances = model.getInstances();
        for (int j = 0; j < instances.size(); j++) {
            Instance instance = (Instance) instances.get(j);
            String id = instance.getId();

            //get node from out
            String search = "//*[@id='" + id + "']";
            Node outInstance = XPathUtil.getAsNode(
                    XPathCache.getInstance().evaluate(context, search, Collections.EMPTY_MAP, null), 1);
            Node imported = out.adoptNode(instance.getInstanceDocument().getDocumentElement());
            if (imported == null) {
                throw new XFormsException("Root Element for Instance '" + instance.getId() + "' not found");
            }

            Node firstChild = DOMUtil.getFirstChildElement(outInstance);

            if (firstChild != null) {
                outInstance.removeChild(firstChild);
            }

            outInstance.appendChild(imported);
            //                    outInstance.replaceChild(imported,DOMUtil.getFirstChildElement(outInstance));

        }
    }
}

From source file:eu.europa.esig.dss.asic.validation.ASiCContainerValidator.java

/**
 * This is an experimental implementation for Aho's contribution. It is likely to be changed. The current implementation does not work with CAdES signatures.
 *
 * @param signatureId the id of the signature to be removed.
 * @return the {@code DSSDocument} with removed given signature
 * @throws DSSException//  w ww.  j  a  v  a  2s.com
 */
@Override
public DSSDocument removeSignature(final String signatureId) throws DSSException {

    if (StringUtils.isBlank(signatureId)) {
        throw new NullPointerException("signatureId");
    }

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

        final DSSDocument signature = signatures.get(i);
        final Document root = DSSXMLUtils.buildDOM(signature);
        final Element signatureEl = (Element) root.getDocumentElement().getFirstChild();
        final String idIdentifier = DSSXMLUtils.getIDIdentifier(signatureEl);
        if (signatureId.equals(idIdentifier)) {

            signatures.remove(i);
            final Document signatureDOM = DSSXMLUtils.createDocument(ASiCNamespaces.ASiC, ASiCService.ASICS_NS);
            for (int j = 0; j < signatures.size(); j++) {

                final Document doc = DSSXMLUtils.buildDOM(signature);
                final Node signatureElement = doc.getDocumentElement().getFirstChild();

                final Element newElement = signatureDOM.getDocumentElement();
                signatureDOM.adoptNode(signatureElement);
                newElement.appendChild(signatureElement);
            }
            return new InMemoryDocument(DSSXMLUtils.serializeNode(signatureDOM));
        }
    }
    throw new DSSException("The signature with the given id was not found!");
}

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 ww . ja va  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.bluexml.xforms.controller.mapping.MappingToolAlfrescoToClassForms.java

/**
 * Fill x forms association create element inline.
 * /*from ww w .j a va  2 s  .c om*/
 * @param transaction
 *            the login
 * @param xformsDocument
 *            the xforms document
 * @param association
 *            the association
 * @param stack
 *            the stack
 * @param targetClassType
 *            the target class type
 * @param initParams
 *            the init params
 * 
 * @return the node
 */
private Node fillXFormsAssociationCreateElementInline(AlfrescoTransaction transaction, Document xformsDocument,
        AssociationType association, Stack<AssociationType> stack, String targetClassType,
        Map<String, String> initParams, boolean formIsReadOnly, boolean isServletRequest) {
    Document inlineElement = null;
    inlineElement = createClassFormsInstance(transaction, targetClassType,
            subMap(initParams, association.getName()), stack, formIsReadOnly, isServletRequest);
    Node clonedNode = inlineElement.getDocumentElement().cloneNode(true);
    clonedNode = xformsDocument.adoptNode(clonedNode);
    return clonedNode;
}

From source file:com.bluexml.xforms.controller.mapping.MappingToolAlfrescoToClassForms.java

/**
 * Fill x forms element from id./*from w w w  .  ja v a  2 s.c  o m*/
 * 
 * @param transaction
 *            the login
 * @param xformsDocument
 *            the xforms document
 * @param stack
 *            the stack
 * @param alfrescoTargetId
 *            the alfresco target id
 * @param isServletRequest
 * 
 * @return the node
 */
private Node fillXFormsElementFromIdInline(AlfrescoTransaction transaction, Document xformsDocument,
        Stack<AssociationType> stack, String alfrescoTargetId, boolean formIsReadOnly,
        boolean isServletRequest) {
    Node subNode;
    Document inlineElement = null;
    try {
        inlineElement = controller.getObjectInstance(transaction, alfrescoTargetId, stack, formIsReadOnly,
                isServletRequest);
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
    subNode = inlineElement.getDocumentElement().cloneNode(true);
    subNode = xformsDocument.adoptNode(subNode);
    return subNode;
}

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>//from  ww w . j  a v a2 s. c om
 * 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:eu.eidas.encryption.SAMLAuthnResponseEncrypter.java

@Nonnull
private Response performEncryption(@Nonnull Response samlResponseEncryptee, @Nonnull Credential credential)
        throws EncryptionException {
    try {//from ww w .ja v a  2s. com
        // Set Data Encryption parameters
        EncryptionParameters encParams = new EncryptionParameters();
        encParams.setAlgorithm(getDataEncAlgorithm());
        // Set Key Encryption parameters
        KeyEncryptionParameters kekParams = new KeyEncryptionParameters();
        kekParams.setEncryptionCredential(credential);
        kekParams.setAlgorithm(getKeyEncAlgorithm());
        KeyInfoGeneratorFactory kigf = Configuration.getGlobalSecurityConfiguration()
                .getKeyInfoGeneratorManager().getDefaultManager().getFactory(credential);
        kekParams.setKeyInfoGenerator(kigf.newInstance());
        // Setup Open SAML Encrypter
        Encrypter encrypter = new Encrypter(encParams, kekParams);
        encrypter.setKeyPlacement(Encrypter.KeyPlacement.INLINE);
        if (getJcaProviderName() != null) {
            encrypter.setJCAProviderName(getJcaProviderName());
        }

        for (Assertion assertion : samlResponseEncryptee.getAssertions()) {
            if (assertion.getDOM() == null) {
                OpenSamlHelper.marshallToDom(assertion);
            }
            manageNamespaces(assertion);
        }
        List<EncryptedAssertion> encryptedAssertions = new ArrayList<>();
        for (Assertion assertion : samlResponseEncryptee.getAssertions()) {
            EncryptedAssertion encryptedAssertion = encrypter.encrypt(assertion);
            encryptedAssertions.add(encryptedAssertion);
        }

        Element previousDom = samlResponseEncryptee.getDOM();
        if (null == previousDom) {
            previousDom = OpenSamlHelper.marshallToDom(samlResponseEncryptee);
        }
        Document ownerDocument = previousDom.getOwnerDocument();

        // Deep copy the previous DOM into a new one using importNode()
        Document newDocument = DocumentBuilderFactoryUtil.newDocument();
        Node copiedRoot = newDocument.importNode(ownerDocument.getDocumentElement(), true);
        newDocument.appendChild(copiedRoot);

        Element newRootElement = newDocument.getDocumentElement();
        NodeList assertionList = newRootElement.getElementsByTagNameNS(
                Assertion.DEFAULT_ELEMENT_NAME.getNamespaceURI(),
                Assertion.DEFAULT_ELEMENT_NAME.getLocalPart());

        // Replace the encrypted assertions by the decrypted assertions in the new DOM tree:
        for (int i = 0, n = assertionList.getLength(); i < n; i++) {
            Node assertion = assertionList.item(i);
            EncryptedAssertion encryptedAssertion = encryptedAssertions.get(i);
            Element encryptedAssertionDOM = encryptedAssertion.getDOM();
            Node copiedEncryptedAssertion;
            if (null == encryptedAssertionDOM) {
                encryptedAssertionDOM = OpenSamlHelper.marshallToDom(encryptedAssertion);
            }
            // we may use adoptNode() instead of importNode() because the unmarshaller rectifies the ID-ness:
            copiedEncryptedAssertion = newDocument.adoptNode(encryptedAssertionDOM);
            newRootElement.replaceChild(copiedEncryptedAssertion, assertion);
        }

        // Finally unmarshall the updated DOM into a new XMLObject graph:
        // The unmarshaller rectifies the ID-ness:
        // See org.opensaml.saml1.core.impl.AssertionUnmarshaller.unmarshall()
        // See org.opensaml.saml2.core.impl.AssertionUnmarshaller.processAttribute()
        // And org.opensaml.saml1.core.impl.ResponseAbstractTypeUnmarshaller.unmarshall()
        // And org.opensaml.saml2.core.impl.StatusResponseTypeUnmarshaller.processAttribute()
        Response encryptedResponse = (Response) OpenSamlHelper.unmarshallFromDom(newDocument);

        if (LOGGER.isTraceEnabled()) {
            try {
                LOGGER.trace("SAML Response XMLObject encrypted: "
                        + EidasStringUtil.toString(DocumentBuilderFactoryUtil.marshall(newDocument, true)));
            } catch (TransformerException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }

        return encryptedResponse;

    } catch (org.opensaml.xml.encryption.EncryptionException | ParserConfigurationException | MarshallException
            | UnmarshallException e) {
        throw new EncryptionException(e);
    }
}

From source file:de.codesourcery.spring.contextrewrite.XMLRewrite.java

private Document parseXML(Resource resource, List<Rule> rules)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    debug("Now loading " + resource);

    try (InputStream in = resource.getInputStream()) {
        final Document doc = XMLRewrite.parseXML(in);
        rewriteXML(doc, rules, false, false);

        final List<Node> importNodes = evaluateXPath("/beans//import", doc);
        debug("Found " + importNodes.size() + " import statements");
        for (Node importNode : importNodes) {
            debug("(1) Node has parent: " + importNode.getParentNode());
            String path = importNode.getAttributes().getNamedItem("resource").getNodeValue();
            if (path.startsWith("classpath:")) {
                path = path.substring("classpath:".length());
            }//from  w  ww  . j a  v a 2  s .c o m
            debug("Including '" + path + "' , now at " + resource);
            final Resource imported;
            if (path.startsWith("/")) { // absolute
                imported = new ClassPathResource(path);
            } else {
                imported = resource.createRelative(path);
            }
            final Document importedXML = parseXML(imported, rules);
            mergeAttributes(importedXML.getFirstChild(), doc.getFirstChild(), doc);

            final List<Node> beans = wrapNodeList(importedXML.getFirstChild().getChildNodes());

            for (Node beanNode : beans) {
                final Node adoptedNode = doc.adoptNode(beanNode.cloneNode(true));
                importNode.getParentNode().insertBefore(adoptedNode, importNode);
            }
            importNode.getParentNode().removeChild(importNode);
        }
        debug("*** return ***");
        return doc;
    } catch (Exception e) {
        throw new RuntimeException("Failed to load XML from '" + resource + "'", e);
    }
}

From source file:de.ingrid.interfaces.csw.server.impl.GenericServer.java

@Override
public Document process(GetRecordsRequest request) throws CSWException {
    try {/*  w ww . j  a  v a2  s  . co m*/
        CSWQuery query = request.getQuery();
        CSWRecordResults result = this.searcher.search(query);

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        DOMImplementation domImpl = docBuilder.getDOMImplementation();
        Document doc = domImpl.createDocument(RESPONSE_NAMESPACE, "csw:GetRecordsResponse", null);

        Element searchStatus = doc.createElementNS(RESPONSE_NAMESPACE, "csw:SearchStatus");

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        df.setTimeZone(TimeZone.getTimeZone("ThreeLetterISO8601TimeZone"));
        searchStatus.setAttribute("timestamp", df.format(new Date()));
        doc.getDocumentElement().appendChild(searchStatus);

        Element searchResults = doc.createElementNS(RESPONSE_NAMESPACE, "csw:SearchResults");
        searchResults.setAttribute("elementSet", request.getQuery().getElementSetName().name().toLowerCase());
        searchResults.setAttribute("numberOfRecordsMatched", String.valueOf(result.getTotalHits()));
        searchResults.setAttribute("numberOfRecordsReturned",
                String.valueOf((result.getResults() == null) ? 0 : result.getResults().size()));
        int nextRecord = query.getStartPosition()
                + ((result.getResults() == null) ? 0 : result.getResults().size());
        if (nextRecord > result.getTotalHits()) {
            nextRecord = 0;
        }
        searchResults.setAttribute("nextRecord", String.valueOf(nextRecord));
        doc.getDocumentElement().appendChild(searchResults);

        if (query.getResultType() == ResultType.RESULTS && result.getResults() != null) {
            for (CSWRecord record : result.getResults()) {
                Node recordNode = record.getDocument().getFirstChild();
                doc.adoptNode(recordNode);
                searchResults.appendChild(recordNode);
            }
        }
        return doc;
    } catch (CSWException ex) {
        log.error("An error occured processing GetRecordsRequest", ex);
        throw ex;
    } catch (Exception ex) {
        log.error("An error occured processing GetRecordsRequest", ex);
        throw new CSWException("An error occured processing GetRecordsRequest");
    }
}