Java Code Examples for org.w3c.dom.Document#adoptNode()

The following examples show how to use org.w3c.dom.Document#adoptNode() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cxf   File: XmlSigOutInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private XMLSignature prepareEnvelopingSignature(Document doc,
                                                String id,
                                                String referenceId,
                                                String sigAlgo,
                                                String digestAlgo) throws Exception {
    Element docEl = doc.getDocumentElement();
    Document newDoc = DOMUtils.createDocument();
    doc.removeChild(docEl);
    newDoc.adoptNode(docEl);
    Element object = newDoc.createElementNS(Constants.SignatureSpecNS, "ds:Object");
    object.appendChild(docEl);
    docEl.setAttributeNS(null, "Id", id);
    docEl.setIdAttributeNS(null, "Id", true);

    XMLSignature sig = new XMLSignature(newDoc, "", sigAlgo);
    newDoc.appendChild(sig.getElement());
    sig.getElement().appendChild(object);

    Transforms transforms = new Transforms(newDoc);
    transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);

    sig.addDocument(referenceId, transforms, digestAlgo);
    return sig;
}
 
Example 2
public void signAssertion(Document samlDocument) throws ProcessingException {
    Element originalAssertionElement = org.keycloak.saml.common.util.DocumentUtil.getChildElement(samlDocument.getDocumentElement(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()));
    if (originalAssertionElement == null) return;
    Node clonedAssertionElement = originalAssertionElement.cloneNode(true);
    Document temporaryDocument;

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

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

    signDocument(temporaryDocument);

    samlDocument.adoptNode(clonedAssertionElement);

    Element parentNode = (Element) originalAssertionElement.getParentNode();

    parentNode.replaceChild(clonedAssertionElement, originalAssertionElement);
}
 
Example 3
Source Project: lams   File: Decrypter.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse the specified input stream in a DOM DocumentFragment, owned by the specified Document.
 * 
 * @param input the InputStream to parse
 * @param owningDocument the Document which will own the returned DocumentFragment
 * @return a DocumentFragment
 * @throws DecryptionException thrown if there is an error parsing the input stream
 */
private DocumentFragment parseInputStream(InputStream input, Document owningDocument) throws DecryptionException {
    // Since Xerces currently seems not to handle parsing into a DocumentFragment
    // without a bit hackery, use this to simulate, so we can keep the API
    // the way it hopefully will look in the future. Obviously this only works for
    // input streams containing valid XML instances, not fragments.

    Document newDocument = null;
    try {
        newDocument = parserPool.parse(input);
    } catch (XMLParserException e) {
        log.error("Error parsing decrypted input stream", e);
        throw new DecryptionException("Error parsing input stream", e);
    }

    Element element = newDocument.getDocumentElement();
    owningDocument.adoptNode(element);

    DocumentFragment container = owningDocument.createDocumentFragment();
    container.appendChild(element);

    return container;
}
 
Example 4
Source Project: cxf   File: XmlSigOutInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private XMLSignature prepareDetachedSignature(Document doc,
        String id,
        String referenceId,
        String sigAlgo,
        String digestAlgo) throws Exception {
    Element docEl = doc.getDocumentElement();
    Document newDoc = DOMUtils.createDocument();
    doc.removeChild(docEl);
    newDoc.adoptNode(docEl);
    docEl.setAttributeNS(null, "Id", id);
    docEl.setIdAttributeNS(null, "Id", true);

    Element root = newDoc.createElementNS(envelopeQName.getNamespaceURI(),
            envelopeQName.getPrefix() + ":" + envelopeQName.getLocalPart());
    root.appendChild(docEl);
    newDoc.appendChild(root);

    XMLSignature sig = new XMLSignature(newDoc, "", sigAlgo);
    root.appendChild(sig.getElement());

    Transforms transforms = new Transforms(newDoc);
    transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);

    sig.addDocument(referenceId, transforms, digestAlgo);
    return sig;
}
 
Example 5
Source Project: proarc   File: MetsUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 *
 * Generates an XML document from list of elements
 *
 * @param elements
 * @return
 */
public static Document getDocumentFromList(List<Element> elements) throws MetsExportException {
    Document document = null;
    try {
        DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
        builder.setValidating(true);
        builder.setNamespaceAware(true);
        document = builder.newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new MetsExportException("Error while getting document from list", false, e1);
    }

    for (Element element : elements) {
        Node newNode = element.cloneNode(true);
        document.adoptNode(newNode);
        document.appendChild(newNode);
    }
    return document;
}
 
Example 6
Source Project: Bytecoder   File: XSAnnotationImpl.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void writeToDOM(Node target, short type) {
    Document futureOwner = (type == XSAnnotation.W3C_DOM_ELEMENT) ?
            target.getOwnerDocument() : (Document)target;
    DOMParser parser = fGrammar.getDOMParser();
    StringReader aReader = new StringReader(fData);
    InputSource aSource = new InputSource(aReader);
    try {
        parser.parse(aSource);
    }
    catch (SAXException e) {
        // this should never happen!
        // REVISIT:  what to do with this?; should really not
        // eat it...
    }
    catch (IOException i) {
        // ditto with above
    }
    Document aDocument = parser.getDocument();
    parser.dropDocumentReferences();
    Element annotation = aDocument.getDocumentElement();
    Node newElem = null;
    if (futureOwner instanceof CoreDocumentImpl) {
        newElem = futureOwner.adoptNode(annotation);
        // adoptNode will return null when the DOM implementations are not compatible.
        if (newElem == null) {
            newElem = futureOwner.importNode(annotation, true);
        }
    }
    else {
        newElem = futureOwner.importNode(annotation, true);
    }
    target.insertBefore(newElem, target.getFirstChild());
}
 
Example 7
private synchronized void writeToDOM(Node target, short type) {
    Document futureOwner = (type == XSAnnotation.W3C_DOM_ELEMENT) ?
            target.getOwnerDocument() : (Document)target;
    DOMParser parser = fGrammar.getDOMParser();
    StringReader aReader = new StringReader(fData);
    InputSource aSource = new InputSource(aReader);
    try {
        parser.parse(aSource);
    }
    catch (SAXException e) {
        // this should never happen!
        // REVISIT:  what to do with this?; should really not
        // eat it...
    }
    catch (IOException i) {
        // ditto with above
    }
    Document aDocument = parser.getDocument();
    parser.dropDocumentReferences();
    Element annotation = aDocument.getDocumentElement();
    Node newElem = null;
    if (futureOwner instanceof CoreDocumentImpl) {
        newElem = futureOwner.adoptNode(annotation);
        // adoptNode will return null when the DOM implementations are not compatible.
        if (newElem == null) {
            newElem = futureOwner.importNode(annotation, true);
        }
    }
    else {
        newElem = futureOwner.importNode(annotation, true);
    }
    target.insertBefore(newElem, target.getFirstChild());
}
 
Example 8
Source Project: cosmo   File: FreeBusyReport.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Element toXml(Document document) {
    try {
        if (getStream() == null) {
            runQuery();
        }

        Document doc = DomUtil.parseDocument(getStream());
        document.adoptNode(doc);

        return doc.getDocumentElement();
    } catch (IOException | CosmoDavException | ParserConfigurationException | SAXException e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
private byte[] reassemblyMessage(Object responseObject, Element sigElement) throws TechnicalConnectorException {
   MarshallerHelper<Object, Object> responseMarshaller = this.getMarshallerHelper(responseObject);
   Document explodedDoc = responseMarshaller.toDocument(responseObject);
   explodedDoc.adoptNode(sigElement);
   Element el = explodedDoc.createElement("XadesT-Signature");
   el.appendChild(sigElement);
   ConnectorXmlUtils.getFirstChildElement(explodedDoc).appendChild(el);
   return ConnectorXmlUtils.toByteArray((Node)explodedDoc);
}
 
Example 10
Source Project: javaide   File: NodeUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Makes a new document adopt a node from a different document, and correctly reassign namespace
 * and prefix
 * @param document the new document
 * @param node the node to adopt.
 * @return the adopted node.
 */
static Node adoptNode(Document document, Node node) {
    Node newNode = document.adoptNode(node);

    updateNamespace(newNode, document);

    return newNode;
}
 
Example 11
private byte[] reassemblyMessage(Object responseObject, Element sigElement) throws TechnicalConnectorException {
   MarshallerHelper<Object, Object> responseMarshaller = new MarshallerHelper(responseObject.getClass(), responseObject.getClass());
   Document explodedDoc = responseMarshaller.toDocument(responseObject);
   explodedDoc.adoptNode(sigElement);
   Element el = explodedDoc.createElement("XadesT-Signature");
   el.appendChild(sigElement);
   ConnectorXmlUtils.getFirstChildElement(explodedDoc).appendChild(el);
   return ConnectorXmlUtils.toByteArray((Node)explodedDoc);
}
 
Example 12
private static Document isolateDescendant(final Element mathElement, final Element descendant) {
    Document result = XMLUtilities.createNSAwareDocumentBuilder().newDocument();
    Element resultMathElement = (Element) mathElement.cloneNode(false);
    result.adoptNode(resultMathElement);
    result.appendChild(resultMathElement);
    
    Element firstSemanticElementCopy = (Element) descendant.cloneNode(true);
    result.adoptNode(firstSemanticElementCopy);
    resultMathElement.appendChild(firstSemanticElementCopy);
    return result;
}
 
Example 13
private static byte[] transform(boolean encapsulate, String xpathLocation, EncapsulationTransformer encapsulationTranformer, Document doc, XMLSignature sig) {
   if (!encapsulate) {
      return ConnectorXmlUtils.toByteArray((Node)sig.getElement());
   } else {
      Node toInsert = doc.adoptNode(encapsulationTranformer.transform(sig.getElement()));
      Node insertBeforeNode = null;
      if (StringUtils.isNotBlank(xpathLocation)) {
         try {
            XPath xPath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList)xPath.evaluate(xpathLocation, doc.getDocumentElement(), XPathConstants.NODESET);
            if (nodes.getLength() == 1) {
               LOG.debug("1 node found, inserting at location [" + xpathLocation + "]");
               insertBeforeNode = nodes.item(0);
            } else {
               LOG.warn("XPATH error: " + nodes.getLength() + "found at location [" + xpathLocation + "],using default.");
            }
         } catch (XPathExpressionException var9) {
            LOG.info("Unable to determine XPath Location, using default.", var9);
         }
      } else {
         LOG.debug("Using default location (last child tag)");
      }

      doc.getFirstChild().insertBefore(toInsert, insertBeforeNode);
      return ConnectorXmlUtils.toByteArray((Node)doc);
   }
}
 
Example 14
private synchronized void writeToDOM(Node target, short type) {
    Document futureOwner = (type == XSAnnotation.W3C_DOM_ELEMENT) ?
            target.getOwnerDocument() : (Document)target;
    DOMParser parser = fGrammar.getDOMParser();
    StringReader aReader = new StringReader(fData);
    InputSource aSource = new InputSource(aReader);
    try {
        parser.parse(aSource);
    }
    catch (SAXException e) {
        // this should never happen!
        // REVISIT:  what to do with this?; should really not
        // eat it...
    }
    catch (IOException i) {
        // ditto with above
    }
    Document aDocument = parser.getDocument();
    parser.dropDocumentReferences();
    Element annotation = aDocument.getDocumentElement();
    Node newElem = null;
    if (futureOwner instanceof CoreDocumentImpl) {
        newElem = futureOwner.adoptNode(annotation);
        // adoptNode will return null when the DOM implementations are not compatible.
        if (newElem == null) {
            newElem = futureOwner.importNode(annotation, true);
        }
    }
    else {
        newElem = futureOwner.importNode(annotation, true);
    }
    target.insertBefore(newElem, target.getFirstChild());
}
 
Example 15
private byte[] reassemblyMessage(Object responseObject, Element sigElement) throws TechnicalConnectorException {
   MarshallerHelper<Object, Object> responseMarshaller = this.getMarshallerHelper(responseObject);
   Document explodedDoc = responseMarshaller.toDocument(responseObject);
   explodedDoc.adoptNode(sigElement);
   Element el = explodedDoc.createElement("XadesT-Signature");
   el.appendChild(sigElement);
   ConnectorXmlUtils.getFirstChildElement(explodedDoc).appendChild(el);
   return ConnectorXmlUtils.toByteArray((Node)explodedDoc);
}
 
Example 16
Source Project: packagedrone   File: P2Unzipper.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void processMetaData ( final Context context, final InputStream in, final String filename, final String xpath ) throws Exception
{
    // parse input
    final Document doc = this.xml.newDocumentBuilder ().parse ( new CloseShieldInputStream ( in ) );
    final XPathExpression path = this.xml.newXPathFactory ().newXPath ().compile ( xpath );

    // filter
    final NodeList result = XmlHelper.executePath ( doc, path );

    // write filtered output
    final Document fragmentDoc = this.xml.newDocumentBuilder ().newDocument ();
    Node node = result.item ( 0 );
    node = fragmentDoc.adoptNode ( node );
    fragmentDoc.appendChild ( node );

    // create artifact
    context.createVirtualArtifact ( filename, out -> {
        try
        {
            XmlHelper.write ( this.xml.newTransformerFactory (), fragmentDoc, new StreamResult ( out ) );
        }
        catch ( final Exception e )
        {
            throw new IOException ( e );
        }
    }, null );
}
 
Example 17
private synchronized void writeToDOM(Node target, short type) {
    Document futureOwner = (type == XSAnnotation.W3C_DOM_ELEMENT) ?
            target.getOwnerDocument() : (Document)target;
    DOMParser parser = fGrammar.getDOMParser();
    StringReader aReader = new StringReader(fData);
    InputSource aSource = new InputSource(aReader);
    try {
        parser.parse(aSource);
    }
    catch (SAXException e) {
        // this should never happen!
        // REVISIT:  what to do with this?; should really not
        // eat it...
    }
    catch (IOException i) {
        // ditto with above
    }
    Document aDocument = parser.getDocument();
    parser.dropDocumentReferences();
    Element annotation = aDocument.getDocumentElement();
    Node newElem = null;
    if (futureOwner instanceof CoreDocumentImpl) {
        newElem = futureOwner.adoptNode(annotation);
        // adoptNode will return null when the DOM implementations are not compatible.
        if (newElem == null) {
            newElem = futureOwner.importNode(annotation, true);
        }
    }
    else {
        newElem = futureOwner.importNode(annotation, true);
    }
    target.insertBefore(newElem, target.getFirstChild());
}
 
Example 18
private synchronized void writeToDOM(Node target, short type) {
    Document futureOwner = (type == XSAnnotation.W3C_DOM_ELEMENT) ?
            target.getOwnerDocument() : (Document)target;
    DOMParser parser = fGrammar.getDOMParser();
    StringReader aReader = new StringReader(fData);
    InputSource aSource = new InputSource(aReader);
    try {
        parser.parse(aSource);
    }
    catch (SAXException e) {
        // this should never happen!
        // REVISIT:  what to do with this?; should really not
        // eat it...
    }
    catch (IOException i) {
        // ditto with above
    }
    Document aDocument = parser.getDocument();
    parser.dropDocumentReferences();
    Element annotation = aDocument.getDocumentElement();
    Node newElem = null;
    if (futureOwner instanceof CoreDocumentImpl) {
        newElem = futureOwner.adoptNode(annotation);
        // adoptNode will return null when the DOM implementations are not compatible.
        if (newElem == null) {
            newElem = futureOwner.importNode(annotation, true);
        }
    }
    else {
        newElem = futureOwner.importNode(annotation, true);
    }
    target.insertBefore(newElem, target.getFirstChild());
}
 
Example 19
/**
 * Makes a new document adopt a node from a different document, and correctly reassign namespace
 * and prefix
 * @param document the new document
 * @param node the node to adopt.
 * @return the adopted node.
 */
static Node adoptNode(Document document, Node node) {
    Node newNode = document.adoptNode(node);

    updateNamespace(newNode, document);

    return newNode;
}
 
Example 20
/**
 * This will check if adoptNode works will adoptNode from
 * @see <a href="content/userInfo.xml">userInfo.xml</a>
 * @see <a href="content/accountInfo.xml">accountInfo.xml</a>. This is
 * adopting a node from the XML file which is validated by a DTD and
 * into an XML file which is validated by the schema This covers Row 5
 * for the table
 * http://javaweb.sfbay/~jsuttor/JSR206/jsr-206-html/ch03s05.html. Filed
 * bug 4893745 because there was a difference in behavior.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateUserAccount() throws Exception {
    String userXmlFile = XML_DIR + "userInfo.xml";
    String accountXmlFile = XML_DIR + "accountInfo.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    MyErrorHandler eh = new MyErrorHandler();
    docBuilder.setErrorHandler(eh);

    Document document = docBuilder.parse(userXmlFile);
    Element user = (Element) document.getElementsByTagName("FirstName").item(0);
    // Set schema after parsing userInfo.xml. Otherwise it will conflict
    // with DTD validation.
    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
    DocumentBuilder docBuilder1 = dbf.newDocumentBuilder();
    docBuilder1.setErrorHandler(eh);
    Document accDocument = docBuilder1.parse(accountXmlFile);

    Element firstName = (Element) accDocument
            .getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0);
    Element adoptedAccount = (Element) accDocument.adoptNode(user);

    Element parent = (Element) firstName.getParentNode();
    parent.replaceChild(adoptedAccount, firstName);

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();

    MyDOMOutput mydomoutput = new MyDOMOutput();
    mydomoutput.setByteStream(System.out);

    writer.write(document, mydomoutput);
    writer.write(accDocument, mydomoutput);

    assertFalse(eh.isAnyError());
}