org.w3c.dom.Document#adoptNode ( )源码实例Demo

下面列出了org.w3c.dom.Document#adoptNode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cxf   文件: XmlSigOutInterceptor.java
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;
}
 
源代码2 项目: keycloak   文件: BaseSAML2BindingBuilder.java
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);
}
 
源代码3 项目: lams   文件: Decrypter.java
/**
 * 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;
}
 
源代码4 项目: cxf   文件: XmlSigOutInterceptor.java
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;
}
 
源代码5 项目: proarc   文件: MetsUtils.java
/**
 *
 * 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;
}
 
源代码6 项目: Bytecoder   文件: XSAnnotationImpl.java
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());
}
 
源代码7 项目: openjdk-8   文件: XSAnnotationImpl.java
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());
}
 
源代码8 项目: cosmo   文件: FreeBusyReport.java
@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);
    }
}
 
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);
}
 
源代码10 项目: javaide   文件: NodeUtils.java
/**
 * 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;
}
 
源代码11 项目: freehealth-connector   文件: ResponseBuilderImpl.java
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);
}
 
源代码12 项目: symja_android_library   文件: MathMLUtilities.java
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;
}
 
源代码13 项目: freehealth-connector   文件: XmlSignatureBuilder.java
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);
   }
}
 
源代码14 项目: openjdk-jdk8u-backup   文件: XSAnnotationImpl.java
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());
}
 
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);
}
 
源代码16 项目: packagedrone   文件: P2Unzipper.java
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 );
}
 
源代码17 项目: openjdk-jdk8u   文件: XSAnnotationImpl.java
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());
}
 
源代码18 项目: openjdk-8-source   文件: XSAnnotationImpl.java
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());
}
 
源代码19 项目: java-n-IDE-for-Android   文件: NodeUtils.java
/**
 * 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;
}
 
源代码20 项目: openjdk-jdk9   文件: UserController.java
/**
 * 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());
}