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

The following examples show how to use org.w3c.dom.Document#importNode() . 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
/**
 * Creates a document having a node as root.
 * 
 * @param sourceNode the node
 * @return a document having the specified node as root
 * @throws JRException
 */
public static Document createDocument(Node sourceNode, boolean isNamespaceAware) throws JRException
{
	Document doc = JRXmlUtils.createDocumentBuilder(isNamespaceAware).newDocument();
	Node source;
	if (sourceNode.getNodeType() == Node.DOCUMENT_NODE) {
		source = ((Document) sourceNode).getDocumentElement();
	} else {
		source = sourceNode;
	}

	Node node = doc.importNode(source, true);
	doc.appendChild(node);
	
	return doc;
}
 
Example 2
@Test
public void testSignBES() throws Exception
{
    System.out.println("signBES");

    Document doc1 = getTestDocument();
    Document doc2 = getDocument("content.xml");
    Node objectContent = doc1.importNode(doc2.getDocumentElement(), true);
    Element elemToSign = doc1.getDocumentElement();
    SignerBES signer = (SignerBES)new XadesBesSigningProfile(keyingProviderMy).newSigner();

    IndividualDataObjsTimeStampProperty dataObjsTimeStamp = new IndividualDataObjsTimeStampProperty();
    AllDataObjsCommitmentTypeProperty globalCommitment = AllDataObjsCommitmentTypeProperty.proofOfApproval();
    CommitmentTypeProperty commitment = (CommitmentTypeProperty)CommitmentTypeProperty.proofOfCreation().withQualifier("MyQualifier");
    DataObjectDesc obj1 = new DataObjectReference('#' + elemToSign.getAttribute("Id")).withTransform(new EnvelopedSignatureTransform()).withDataObjectFormat(new DataObjectFormatProperty("text/xml", "MyEncoding").withDescription("Isto é uma descrição do elemento raiz").withDocumentationUri("http://doc1.txt").withDocumentationUri("http://doc2.txt").withIdentifier("http://elem.root")).withCommitmentType(commitment).withDataObjectTimeStamp(dataObjsTimeStamp);
    DataObjectDesc obj2 = new EnvelopedXmlObject(objectContent, "text/xml", null).withDataObjectFormat(new DataObjectFormatProperty("text/xml", "MyEncoding").withDescription("Isto é uma descrição do elemento dentro do object").withDocumentationUri("http://doc3.txt").withDocumentationUri("http://doc4.txt").withIdentifier("http://elem.in.object")).withCommitmentType(commitment).withDataObjectTimeStamp(dataObjsTimeStamp);
    SignedDataObjects dataObjs = new SignedDataObjects(obj1, obj2).withCommitmentType(globalCommitment).withDataObjectsTimeStamp();

    signer.sign(dataObjs, elemToSign);

    outputDocument(doc1, "document.signed.bes.xml");
}
 
Example 3
Source Project: container   File: Fragments.java    License: Apache License 2.0 6 votes vote down vote up
public Node generateAssignFromPropertyVarToDomMapping(final String nodeInstancePropertyRequestVarName,
                                                      final Map<String, Node> propertyVarToDomMapping) throws SAXException,
    IOException {
    // create empty bpel:assign
    final String bpelAssignString =
        "<bpel:assign xmlns:bpel=\"http://docs.oasis-open.org/wsbpel/2.0/process/executable\" name=\"assignPropertyVarsToAnyElement"
            + System.currentTimeMillis() + "\" />";
    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(bpelAssignString));
    final Document doc = this.docBuilder.parse(is);

    final Node assignNode = doc.getFirstChild();
    for (final String propertyVarName : propertyVarToDomMapping.keySet()) {
        final Node propertyNode = propertyVarToDomMapping.get(propertyVarName);
        Node copyNode =
            generateCopyFromStringVarToAnyTypeVarAsNode(propertyVarName, nodeInstancePropertyRequestVarName,
                propertyNode.getLocalName(),
                propertyNode.getNamespaceURI());

        copyNode = doc.importNode(copyNode, true);
        assignNode.appendChild(copyNode);
    }

    return assignNode;
}
 
Example 4
private void createFaultDetail(Document faultData, FaultInfo faultInfo, Fault faultEx) {
    MessagePartInfo partInfo = faultInfo.getMessageParts().get(0);
    QName partInfoName = partInfo.getElementQName();
    Document faultDoc = DOMUtils.getEmptyDocument();
    Element faultElement = faultDoc.createElement("detail");
    Element partElement =
        faultDoc.createElementNS(partInfoName.getNamespaceURI(), partInfoName.getLocalPart());

    Element faultDataElement = (Element) faultData.getFirstChild();
    Node node = faultDataElement.getFirstChild();
    while (node != null) {
        Node importedFaultData = faultDoc.importNode(node, true);
        partElement.appendChild(importedFaultData);
        node = node.getNextSibling();
    }
    faultElement.appendChild(partElement);
    faultEx.setDetail(faultElement);
}
 
Example 5
/**
 * Pull apart object bank based on elementName
 * @param objectBank
 * @param elementName e.g. "assessment", "item", etc.
 * @return
 */
private Document[] getDocumentsFromObjectBankDoc(Document objectBank,
  String elementName)
{
  Document[] documents = null;
  // Get the matching elements
  NodeList nodeList = objectBank.getElementsByTagName("//" + elementName); 
  
  int numDocs = nodeList.getLength();
  if (numDocs == 0)
  {
    return null;
  }

  documents = new Document[numDocs];
  for (int i = 0; i < numDocs; i++)
  {
    Node node = (Node) nodeList.item(i);
    Document objectDoc = XmlUtil.createDocument();
    Node importNode = objectDoc.importNode(node, true);
    objectDoc.appendChild(importNode);
    documents[i] = objectDoc;
  }
  
  return documents;
}
 
Example 6
private Object extractPartsInfoFromDetail(Element faultDetail, RaisesType exType) {
    Document faultDoc = DOMUtils.createDocument();
    Element faultElement = faultDoc.createElement(exType.getException().getLocalPart());
    faultDoc.appendChild(faultElement);

    Node node = faultDetail.getFirstChild();
    while (node != null) {
        Node importedFaultData = faultDoc.importNode(node, true);
        faultElement.appendChild(importedFaultData);
        node = node.getNextSibling();
    }

    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Exception DOM: " + StaxUtils.toString(faultElement));
    }
    return faultDoc;
}
 
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
private  SOAPElement convertToSoapElement(Element element) throws SOAPException {

        if (element instanceof SOAPElement) {
            return (SOAPElement) element;
        }

        SOAPElement copy = createElement(
                                element.getLocalName(),
                                element.getPrefix(),
                                element.getNamespaceURI());

        Document ownerDoc = copy.getOwnerDocument();

        NamedNodeMap attrMap = element.getAttributes();
        for (int i=0; i < attrMap.getLength(); i++) {
            Attr nextAttr = (Attr)attrMap.item(i);
            Attr importedAttr = (Attr)ownerDoc.importNode(nextAttr, true);
            copy.setAttributeNodeNS(importedAttr);
        }


        NodeList nl = element.getChildNodes();
        for (int i=0; i < nl.getLength(); i++) {
            org.w3c.dom.Node next = nl.item(i);
            org.w3c.dom.Node imported = ownerDoc.importNode(next, true);
            copy.appendChild(imported);
        }

        return copy;
    }
 
Example 9
/**
 * create child
 *
 * @param childXpath
 *
 * @return
 */
protected final Element createChildElement(String childXpath)
{
  int index = childXpath.indexOf("/");
  String elementName = childXpath;
  String subChildXpath = null;
  Element element = null;
  Element child = null;
  if(index > 0)
  {
    elementName = childXpath.substring(0, index);
    subChildXpath = childXpath.substring(index + 1);
    child = createChildElement(subChildXpath);
  }
  try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.newDocument();
    element = document.createElement(elementName);
    if(child != null)
    {
      Node importedNode = document.importNode(child, true);
      element.appendChild(importedNode);
    }
  } catch(ParserConfigurationException pce) {
  	log.error("Exception thrown from createChildElement(): " + pce.getMessage());
  }
  
  return element;
}
 
Example 10
Source Project: tutorial-soap-spring-boot-cxf   File: XmlUtils.java    License: MIT License 5 votes vote down vote up
private static Document copyDocumentAsChildelementUnderNewDocument(Document document) throws XmlUtilsException {
	Document docWithDocumentAsChild = createNewDocument();
	docWithDocumentAsChild.appendChild(docWithDocumentAsChild.createElement("root2kick"));			
	Node importedNode = docWithDocumentAsChild.importNode(document.getDocumentElement(), true);
	docWithDocumentAsChild.getDocumentElement().appendChild(importedNode);
	return docWithDocumentAsChild;
}
 
Example 11
public Document getDocument(Node sourceNode) throws JRException {
	Document doc = getDocumentBuilder().newDocument();

	Node source;
	if (sourceNode.getNodeType() == Node.DOCUMENT_NODE) {
		source = ((Document) sourceNode).getDocumentElement();
	} else {
		source = sourceNode;
	}

	Node node = doc.importNode(source, true);
	doc.appendChild(node);
	
	return doc;
}
 
Example 12
Source Project: tutorial-soap-spring-boot-cxf   File: XmlUtils.java    License: MIT License 5 votes vote down vote up
private static Document copyDocumentAsChildelementUnderNewDocument(Document document) throws XmlUtilsException {
	Document docWithDocumentAsChild = createNewDocument();
	docWithDocumentAsChild.appendChild(docWithDocumentAsChild.createElement("root2kick"));			
	Node importedNode = docWithDocumentAsChild.importNode(document.getDocumentElement(), true);
	docWithDocumentAsChild.getDocumentElement().appendChild(importedNode);
	return docWithDocumentAsChild;
}
 
Example 13
@Override
public void execute() throws BuildException {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		
		// lecture du contenu d'un fichier XML avec DOM
		File target = new File(targetMenuFile);
		File source = new File(srcMenuFile);
		Document srcDoc = builder.parse(source);
		Document targetDoc = builder.parse(target);
		Node node = targetDoc.importNode(srcDoc.getFirstChild(), true);
		for (int i = 0; i < node.getChildNodes().getLength(); i++) {
			Node child = node.getChildNodes().item(i);
			if (child instanceof Element) {
				((Element)targetDoc.getElementsByTagName("Menu").item(0)).appendChild(child);
			}
		}
		
		DOMSource domSource = new DOMSource(targetDoc);
		StreamResult result = new StreamResult(target);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = tf.newTransformer();
		transformer.transform(domSource, result);
	} catch (Exception ex) {
		throw new BuildException(ex);
	}
}
 
Example 14
Source Project: exificient   File: DocumentFragmentBuilder.java    License: MIT License 5 votes vote down vote up
public DocumentFragment parse(InputStream is) throws SAXException,
		IOException {
	// Wrap the fragment in an arbitrary element
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	baos.write("<fragment>".getBytes());

	int b;
	while ((b = is.read()) != -1) {
		baos.write(b);
	}

	baos.write("</fragment>".getBytes());

	// parse
	Document doc = this.docBuilder.parse(new ByteArrayInputStream(baos
			.toByteArray()));

	// // Import the nodes of the new document into doc so that they
	// // will be compatible with doc
	Node node = doc.importNode(doc.getDocumentElement(), true);

	// Create the document fragment node to hold the new nodes
	DocumentFragment docfrag = doc.createDocumentFragment();

	// Move the nodes into the fragment
	while (node.hasChildNodes()) {
		docfrag.appendChild(node.removeChild(node.getFirstChild()));
	}

	// Return the fragment
	return docfrag;
}
 
Example 15
/**
 * Look up a List of Item XML from Section Xml
 * @param Section sectionXml
 * @return a List of Item XML objects
 */
public List getItemXmlList(Section sectionXml)
{
  String itemElementName =
      qtiVersion == QTIVersion.VERSION_1_2 ? "//item" : "//assessmentItem";

  // now convert our list of Nodes to a list of section xml
  List nodeList = sectionXml.selectNodes(itemElementName);
  List itemXmlList = new ArrayList();
  for (int i = 0; i < nodeList.size(); i++)
  {
    try
    {
      Node node = (Node) nodeList.get(i);
      // create a document for a item xml object
      Document itemDoc = XmlUtil.createDocument();
      // Make a copy for inserting into the new document
      Node importNode = itemDoc.importNode(node, true);
      // Insert the copy into itemDoc
      itemDoc.appendChild(importNode);
      Item itemXml = new Item(itemDoc,
             this.getQtiVersion());
      // add the new section xml object to the list
      itemXmlList.add(itemXml);
    }
    catch (DOMException ex)
    {
      log.error(ex.getMessage(), ex);
    }
  }
  return itemXmlList;
}
 
Example 16
public Element getConfigurationFragment(String elementName, String namespace, boolean shared) {
    Element el = find(shared, namespace, elementName);

    if (el != null) {
        Document dummy = XMLUtil.createDocument("test", null, null, null);
        return (Element) dummy.importNode(el, true);
    }
    
    return null;
}
 
Example 17
Source Project: cxf   File: FragmentDialect.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Helper method. It adds new Node as the last child of parent.
 * @param ownerDocument Document, where the Node is added.
 * @param parent Parent, where the Node is added.
 * @param value Value defined in the Value element. It represents newly added Node.
 */
private void addNode(Document ownerDocument, Node parent, Node nextSibling, ValueType value) {
    if (ownerDocument == parent && ownerDocument.getDocumentElement() != null) {
        throw new InvalidRepresentation();
    }
    for (Object o : value.getContent()) {
        if (o instanceof String) {
            parent.setTextContent(parent.getTextContent() + ((String) o));
        } else if (o instanceof Node) {
            Node node = (Node) o;
            if (
                    FragmentDialectConstants.FRAGMENT_2011_03_IRI.equals(node.getNamespaceURI())
                            && FragmentDialectConstants.FRAGMENT_ATTR_NODE_NAME.equals(node.getLocalName())) {
                String attrName = ((Element)node).getAttributeNS(
                        FragmentDialectConstants.FRAGMENT_2011_03_IRI,
                        FragmentDialectConstants.FRAGMENT_ATTR_NODE_NAME_ATTR);
                String attrValue = node.getTextContent();
                if (attrName == null) {
                    throw new SoapFault("wsf:[email protected] is not present.", getSoapVersion().getSender());
                }
                if (((Element) parent).hasAttribute(attrName)) {
                    throw new InvalidRepresentation();
                }
                ((Element) parent).setAttribute(attrName, attrValue);
            } else {
                // import the node to the ownerDocument
                Node importedNode = ownerDocument.importNode((Node) o, true);
                if (nextSibling == null) {
                    parent.appendChild(importedNode);
                } else {
                    parent.insertBefore(importedNode, nextSibling);
                }
            }
        } else {
            throw new InvalidExpression();
        }
    }
}
 
Example 18
Source Project: keycloak   File: XMLSignatureUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Sign a node in a document
 *
 * @param doc
 * @param nodeToBeSigned
 * @param keyPair
 * @param digestMethod
 * @param signatureMethod
 * @param referenceURI
 *
 * @return
 *
 * @throws ParserConfigurationException
 * @throws XMLSignatureException
 * @throws MarshalException
 * @throws GeneralSecurityException
 */
public static Document sign(Document doc, Node nodeToBeSigned, String keyName, KeyPair keyPair, String digestMethod,
                            String signatureMethod, String referenceURI, X509Certificate x509Certificate,
                            String canonicalizationMethodType) throws ParserConfigurationException, GeneralSecurityException,
        MarshalException, XMLSignatureException {
    if (nodeToBeSigned == null)
        throw logger.nullArgumentError("Node to be signed");

    if (logger.isTraceEnabled()) {
        logger.trace("Document to be signed=" + DocumentUtil.asString(doc));
    }

    Node parentNode = nodeToBeSigned.getParentNode();

    // Let us create a new Document
    Document newDoc = DocumentUtil.createDocument();
    // Import the node
    Node signingNode = newDoc.importNode(nodeToBeSigned, true);
    newDoc.appendChild(signingNode);

    if (!referenceURI.isEmpty()) {
        propagateIDAttributeSetup(nodeToBeSigned, newDoc.getDocumentElement());
    }
    newDoc = sign(newDoc, keyName, keyPair, digestMethod, signatureMethod, referenceURI, x509Certificate, canonicalizationMethodType);

    // if the signed element is a SAMLv2.0 assertion we need to move the signature element to the position
    // specified in the schema (before the assertion subject element).
    if (nodeToBeSigned.getLocalName().equals("Assertion")
            && WSTrustConstants.SAML2_ASSERTION_NS.equals(nodeToBeSigned.getNamespaceURI())) {
        Node signatureNode = DocumentUtil.getElement(newDoc, new QName(WSTrustConstants.DSIG_NS, "Signature"));
        Node subjectNode = DocumentUtil.getElement(newDoc, new QName(WSTrustConstants.SAML2_ASSERTION_NS, "Subject"));
        if (signatureNode != null && subjectNode != null) {
            newDoc.getDocumentElement().removeChild(signatureNode);
            newDoc.getDocumentElement().insertBefore(signatureNode, subjectNode);
        }
    }

    // Now let us import this signed doc into the original document we got in the method call
    Node signedNode = doc.importNode(newDoc.getFirstChild(), true);

    if (!referenceURI.isEmpty()) {
        propagateIDAttributeSetup(newDoc.getDocumentElement(), (Element) signedNode);
    }

    parentNode.replaceChild(signedNode, nodeToBeSigned);
    // doc.getDocumentElement().replaceChild(signedNode, nodeToBeSigned);

    return doc;
}
 
Example 19
@Mock
GetDatastreamDissemination getDatastreamDissemination(
        String pid, String dsId) {
    return new GetDatastreamDissemination(pid, dsId) {
        @Override
        public FedoraResponse execute(FedoraClient fedora) {
            return new FedoraResponse() {
                @Override
                public int getStatus() {
                    return HttpURLConnection.HTTP_OK;
                }

                @Override
                public InputStream getEntityInputStream() {
                    try {
                        Optional<URL> stream = Optional.ofNullable(getClass().getResource(dsId + "/" + StringUtils.remove(pid, "uuid:")));
                        if (stream.isPresent()) {
                            return stream.get().openStream();
                        } else {
                            URL objectUrl = getClass().getResource(StringUtils.remove(pid, "uuid:") + ".xml");
                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                            dbf.setNamespaceAware(true);
                            DocumentBuilder db = dbf.newDocumentBuilder();
                            Document objectXML = db.parse(objectUrl.openStream());
                            XPath xPath = XPathFactory.newInstance().newXPath();
                            SimpleNamespaceContext namespaces = new SimpleNamespaceContext().add("foxml", "info:fedora/fedora-system:def/foxml#");
                            xPath.setNamespaceContext(namespaces);
                            Document datastreamXML = db.newDocument();
                            Node node = (Node) xPath.compile("//foxml:datastream[@ID='" + dsId + "']").evaluate(objectXML, XPathConstants.NODE);
                            Node importedNode = datastreamXML.importNode(node, true);
                            datastreamXML.appendChild(importedNode);

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            Source xmlSource = new DOMSource(datastreamXML);
                            Result outputTarget = new StreamResult(outputStream);
                            TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
                            return new ByteArrayInputStream(outputStream.toByteArray());
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public <T> T getEntity(Class<T> c) {
                    return null;
                }

                @Override
                public String getType() {
                    return null;
                }

                @Override
                public void close() {
                }
            };
        }
    };
}
 
Example 20
Source Project: syndesis   File: BindingHelper.java    License: Apache License 2.0 4 votes vote down vote up
private String getSpecificationString(XmlSchemaExtractor schemaExtractor) throws ParserException {
    try {
        // copy source elements and types to target schema
        schemaExtractor.copyObjects();
        final SchemaCollection targetSchemas = schemaExtractor.getTargetSchemas();

        // serialize schemas as AtlasMap schemaset
        // schemaset is described at https://docs.atlasmap.io/#importing-xml-files-into-atlasmap
        final Document schemaSet = this.documentBuilder.parse(new InputSource(new StringReader(SCHEMA_SET_XML)));
        final Node additionalSchemas = schemaSet.getElementsByTagName("d:AdditionalSchemas").item(0);

        // insert schemas into schemaset
        final XmlSchema[] xmlSchemas = targetSchemas.getXmlSchemaCollection().getXmlSchemas();
        for (XmlSchema schema : xmlSchemas) {
            final String targetNamespace = schema.getTargetNamespace();

            // no need to add XSD and XML schema
            if (!targetNamespace.equals(XMLConstants.XML_NS_URI) &&
                !targetNamespace.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI)) {

                // get the schema DOM document
                final Document schemaDocument = schema.getSchemaDocument();
                // remove targetnamespace declaration for no namespace schema
                if (targetNamespace.isEmpty()) {
                    // remove invalid xmlns:tns="" attribute or it breaks StaxUtils.toString below
                    schemaDocument.getDocumentElement().removeAttribute("xmlns:tns");
                }

                // import the schema into schemaset
                final Node documentElement = schemaSet.importNode(schemaDocument.getDocumentElement(), true);

                if (targetNamespace.equals(soapVersion.getNamespace())) {
                    // add soap envelope under schemaset as first child
                    schemaSet.getDocumentElement().insertBefore(documentElement, additionalSchemas);
                } else {
                    // add the schema under 'AdditionalSchemas'
                    additionalSchemas.appendChild(documentElement);
                }
            }
        }

        // write schemaset as string
        return StaxUtils.toString(schemaSet);

    } catch (XmlSchemaSerializer.XmlSchemaSerializerException | ParserException | SAXException | IOException e) {
        throw new ParserException(String.format("Error parsing %s for operation %s: %s",
            bindingMessageInfo.getMessageInfo().getType(),
            bindingMessageInfo.getBindingOperation().getOperationInfo().getName(),
            e.getMessage())
            , e);
    }
}