Java Code Examples for org.w3c.dom.Node.replaceChild()

The following are Jave code examples for showing how to use replaceChild() of the org.w3c.dom.Node class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: incubator-netbeans   File: GenerateJnlpFileTask.java   Source Code and License Vote up 6 votes
private void processSecurityElem(Document docDom, Node parent) {
    NodeList childNodes = parent.getChildNodes();
    int len = childNodes.getLength();
    for (int i = 0; i < len; i++) {
        Node node = childNodes.item(i);
        if (node != null && node.getNodeType() == Node.COMMENT_NODE) { // node might be null (don't know why)
            if (node.getNodeValue().equals(DEFAULT_JNLP_SECURITY)) {
                String securityProp = getProperty("jnlp.signed", null); //NOI18N // property in project.properties
                if (securityProp != null && securityProp.equalsIgnoreCase("true")) { //NOI18N
                    parent.replaceChild(createSecurityElement(docDom), node);
                } else {
                    parent.removeChild(node);
                }
            }
        }
    }
}
 
Example 2
Project: OpenJSharp   File: XMLCipher.java   Source Code and License Vote up 6 votes
/**
 * Encrypts an <code>Element</code> and replaces it with its encrypted
 * counterpart in the context <code>Document</code>, that is, the
 * <code>Document</code> specified when one calls
 * {@link #getInstance(String) getInstance}.
 *
 * @param element the <code>Element</code> to encrypt.
 * @return the context <code>Document</code> with the encrypted
 *   <code>Element</code> having replaced the source <code>Element</code>.
 *  @throws Exception
 */
private Document encryptElement(Element element) throws Exception{
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting element...");
    }
    if (null == element) {
        log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
    }
    if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
    }

    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }
    encryptData(contextDocument, element, false);

    Element encryptedElement = factory.toElement(ed);

    Node sourceParent = element.getParentNode();
    sourceParent.replaceChild(encryptedElement, element);

    return contextDocument;
}
 
Example 3
Project: OpenJSharp   File: ElementImpl.java   Source Code and License Vote up 6 votes
protected static SOAPElement replaceElementWithSOAPElement(
    Element element,
    ElementImpl copy) {

    Iterator eachAttribute = getAllAttributesFrom(element);
    while (eachAttribute.hasNext()) {
        Name name = (Name) eachAttribute.next();
        copy.addAttributeBare(name, getAttributeValueFrom(element, name));
    }

    Iterator eachChild = getChildElementsFrom(element);
    while (eachChild.hasNext()) {
        Node nextChild = (Node) eachChild.next();
        copy.insertBefore(nextChild, null);
    }

    Node parent = element.getParentNode();
    if (parent != null) {
        parent.replaceChild(copy, element);
    } // XXX else throw an exception?

    return copy;
}
 
Example 4
Project: jdk8u-jdk   File: XMLCipher.java   Source Code and License Vote up 6 votes
/**
 * Encrypts an <code>Element</code> and replaces it with its encrypted
 * counterpart in the context <code>Document</code>, that is, the
 * <code>Document</code> specified when one calls
 * {@link #getInstance(String) getInstance}.
 *
 * @param element the <code>Element</code> to encrypt.
 * @return the context <code>Document</code> with the encrypted
 *   <code>Element</code> having replaced the source <code>Element</code>.
 *  @throws Exception
 */
private Document encryptElement(Element element) throws Exception{
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting element...");
    }
    if (null == element) {
        log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
    }
    if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
    }

    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }
    encryptData(contextDocument, element, false);

    Element encryptedElement = factory.toElement(ed);

    Node sourceParent = element.getParentNode();
    sourceParent.replaceChild(encryptedElement, element);

    return contextDocument;
}
 
Example 5
Project: openjdk-jdk10   File: XMLCipher.java   Source Code and License Vote up 6 votes
/**
 * Encrypts an <code>Element</code> and replaces it with its encrypted
 * counterpart in the context <code>Document</code>, that is, the
 * <code>Document</code> specified when one calls
 * {@link #getInstance(String) getInstance}.
 *
 * @param element the <code>Element</code> to encrypt.
 * @return the context <code>Document</code> with the encrypted
 *   <code>Element</code> having replaced the source <code>Element</code>.
 *  @throws Exception
 */
private Document encryptElement(Element element) throws Exception{
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting element...");
    }
    if (null == element) {
        log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
    }
    if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
    }

    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }
    encryptData(contextDocument, element, false);

    Element encryptedElement = factory.toElement(ed);

    Node sourceParent = element.getParentNode();
    sourceParent.replaceChild(encryptedElement, element);

    return contextDocument;
}
 
Example 6
Project: openjdk-jdk10   File: ElementImpl.java   Source Code and License Vote up 6 votes
protected SOAPElement replaceElementWithSOAPElement(
    Element element,
    ElementImpl copy) {

    Iterator<Name> eachAttribute = getAllAttributesFrom(element);
    while (eachAttribute.hasNext()) {
        Name name = eachAttribute.next();
        copy.addAttributeBare(name, getAttributeValueFrom(element, name));
    }

    Iterator<Node> eachChild = getChildElementsFromDOM(element);
    while (eachChild.hasNext()) {
        Node nextChild = eachChild.next();
        copy.insertBefore(nextChild, null);
    }

    Node parent = soapDocument.find(element.getParentNode());
    if (parent != null) {
        parent.replaceChild(copy, element);
    } // XXX else throw an exception?

    return copy;
}
 
Example 7
Project: karate   File: XmlUtils.java   Source Code and License Vote up 5 votes
public static void setByPath(Document doc, String path, Node in) {
    if (in.getNodeType() == Node.DOCUMENT_NODE) {
        in = in.getFirstChild();
    }
    Node node = getNodeByPath(doc, path, true);
    if (node == null) {
        throw new RuntimeException("no results for xpath: " + path);
    }
    Node newNode = doc.importNode(in, true);
    if (node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE) {
        node.replaceChild(newNode, node.getFirstChild());
    } else {
        node.appendChild(newNode);
    }
}
 
Example 8
Project: OpenJSharp   File: XMLCipher.java   Source Code and License Vote up 5 votes
/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    byte[] octets = decryptToByteArray(element);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}
 
Example 9
Project: jdk8u-jdk   File: XMLCipher.java   Source Code and License Vote up 5 votes
/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    byte[] octets = decryptToByteArray(element);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}
 
Example 10
Project: openjdk-jdk10   File: XMLCipher.java   Source Code and License Vote up 5 votes
/**
 * Decrypts <code>EncryptedData</code> in a single-part operation.
 *
 * @param element the <code>EncryptedData</code> to decrypt.
 * @return the <code>Node</code> as a result of the decrypt operation.
 * @throws XMLEncryptionException
 */
private Document decryptElement(Element element) throws XMLEncryptionException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypting element...");
    }

    if (cipherMode != DECRYPT_MODE) {
        log.log(java.util.logging.Level.SEVERE, "XMLCipher unexpectedly not in DECRYPT_MODE...");
    }

    byte[] octets = decryptToByteArray(element);

    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Decrypted octets:\n" + new String(octets));
    }

    Node sourceParent = element.getParentNode();
    Node decryptedNode = serializer.deserialize(octets, sourceParent);

    // The de-serialiser returns a node whose children we need to take on.
    if (sourceParent != null && Node.DOCUMENT_NODE == sourceParent.getNodeType()) {
        // If this is a content decryption, this may have problems
        contextDocument.removeChild(contextDocument.getDocumentElement());
        contextDocument.appendChild(decryptedNode);
    } else if (sourceParent != null) {
        sourceParent.replaceChild(decryptedNode, element);
    }

    return contextDocument;
}
 
Example 11
Project: openjdk-jdk10   File: ElementImpl.java   Source Code and License Vote up 5 votes
protected TextImpl convertToSoapText(CharacterData characterData) {
        final Node soapNode = getSoapDocument().findIfPresent(characterData);
        if (soapNode instanceof TextImpl) {
            return (TextImpl) soapNode;
        } else {
            TextImpl t = null;
            switch (characterData.getNodeType()) {
                case CDATA_SECTION_NODE:
                    t = new CDATAImpl(getSoapDocument(), characterData.getData());
                    break;
                case COMMENT_NODE:
                    t = new SOAPCommentImpl(getSoapDocument(), characterData.getData());
                    break;
                case TEXT_NODE:
                    t = new SOAPTextImpl(getSoapDocument(), characterData.getData());
                    break;
            }
            Node parent = getSoapDocument().find(characterData.getParentNode());
            if (parent != null) {
                parent.replaceChild(t, characterData);
            } // XXX else throw an exception?

            return t;

//            return replaceElementWithSOAPElement(
//                element,
//                (ElementImpl) createElement(NameImpl.copyElementName(element)));
        }
    }
 
Example 12
Project: ccpa   File: TreeOptimizer.java   Source Code and License Vote up 4 votes
private static void removeNoOpsFromOp(Node root, Node op)
{
	if (!op.getNodeName().equals("op"))
		return;
	NamedNodeMap attr = op.getAttributes();
	String operation =  attr.getNamedItem("name").getTextContent();
	if (operation.equals("NO_OP"))
	{
		root.removeChild(op);
	}
	else if (operation.equals(";"))
	{
		NodeList children = op.getChildNodes();

		if (children.item(0).getNodeName().equals("op"))
			removeNoOpsFromOp(op,children.item(0));
		else if (children.item(0).getNodeName().equals("value"))
			op.removeChild(children.item(0));

		if (children.item(1) == null)
		{
			if (children.item(0).getNodeName().equals("op"))
				removeNoOpsFromOp(op,children.item(0));
			else if (children.item(0).getNodeName().equals("value"))
				op.removeChild(children.item(0));
		}
		else
		{
			if (children.item(1).getNodeName().equals("op"))
				removeNoOpsFromOp(op,children.item(1));
			else if (children.item(1).getNodeName().equals("value"))
				op.removeChild(children.item(1));
		}

		if (op.getChildNodes().getLength() == 1)
			root.replaceChild(op.getFirstChild(), op);
		else if (op.getChildNodes().getLength() == 0)
			root.removeChild(op);
	}
	else if (operation.equals("FUN"))
	{
		removeNoOpsFromOp(op,op.getChildNodes().item(1));
	}
}
 
Example 13
Project: ccpa   File: TreeTransformer.java   Source Code and License Vote up 4 votes
public static void moveFunctionCallsInNode(Node node)
{
	if (!node.getNodeName().equals("op"))
		return;

	NamedNodeMap attr = node.getAttributes();
	String operation = attr.getNamedItem("name").getTextContent();
	NodeList children = node.getChildNodes();

	for (int i = 0; i < children.getLength(); i++)
	{
		moveFunctionCallsInNode(children.item(i));
	}

	if (operation.equals("CALL"))
	{
		Node parent = node.getParentNode();
		Node temp = node;

		if (parent != null && parent.getAttributes().getNamedItem("name") != null){
			String parentOp = node.getParentNode().getAttributes().getNamedItem("name").getTextContent();
		while (!parentOp.equals(";") && !parentOp.equals("while") && !parentOp.equals("doWhile") &&  !parentOp.equals("for") && !parentOp.equals("if") && !parentOp.equals("if/else") && !parentOp.equals("ASSIGN"))
		{
			temp = parent;
			parent = temp.getParentNode();
			if (parent == null || parent.getAttributes().getNamedItem("name") == null)
				return;
			parentOp = parent.getAttributes().getNamedItem("name").getTextContent();
		}

		if (node.getParentNode() != parent)
		{
			Element assignOp = doc.createElement("op");
			Element joinOps = doc.createElement("op");
			Element funName = doc.createElement("value");
			Element funType = doc.createElement("value");
			Element usesVar = doc.createElement("uses");

			String type;
			String name = getUniqueName();

			type =  attr.getNamedItem("type").getTextContent();

			funName.setTextContent(name);
			funType.setTextContent(type);

			usesVar.appendChild(funType.cloneNode(true));
			usesVar.appendChild(funName.cloneNode(true));

			assignOp.setAttribute("name", "ASSIGN");
			assignOp.setAttribute("type", type);
			assignOp.appendChild(node.cloneNode(true));
			assignOp.appendChild(funName.cloneNode(true));

			node.getParentNode().replaceChild(funName.cloneNode(true), node);

			joinOps.setAttribute("name", ";");
			joinOps.setAttribute("type", "");
			joinOps.appendChild(temp.cloneNode(true));
			joinOps.appendChild(assignOp.cloneNode(true));

			parent.replaceChild(joinOps.cloneNode(true), temp);
			parent.appendChild(usesVar);
		}
		}
	}
}
 
Example 14
Project: oscm   File: UpdateFieldAdapter.java   Source Code and License Vote up 4 votes
private void updateNode(SOAPMessageContext context, List<FieldInfo> fields,
        String variableName, boolean isResponse) throws SOAPException {

    Node variableNode;
    if (isResponse) {
        variableNode = context.getMessage().getSOAPBody().getFirstChild()
                .getFirstChild();
    } else {
        variableNode = context.getMessage().getSOAPBody()
                .getElementsByTagName(variableName).item(0);
    }

    NodeList fieldsList = variableNode.getChildNodes();
    int fieldsSize = fieldsList.getLength();

    for (int i = 0; i < fieldsSize; i++) {
        Node fieldNode = fieldsList.item(i);
        for (FieldInfo field : fields) {
            String oldNodeName = "";
            String updatedNodeName = "";
            if (isResponse) {
                oldNodeName = PREFIX
                        + field.getNewField().getVariableName();
                updatedNodeName = PREFIX
                        + field.getOldField().getVariableName();
            } else {
                oldNodeName = PREFIX
                        + field.getOldField().getVariableName();
                updatedNodeName = PREFIX
                        + field.getNewField().getVariableName();

            }
            if (fieldNode.getNodeName().equals(oldNodeName)) {
                Element newNode = variableNode
                        .getOwnerDocument()
                        .createElementNS(
                                variableNode.getFirstChild()
                                        .getNamespaceURI(), updatedNodeName);
                newNode.setTextContent(fieldNode.getTextContent());
                variableNode.replaceChild(newNode, fieldNode);
            }
        }
    }
}
 
Example 15
Project: monarch   File: XmlUtils.java   Source Code and License Vote up 4 votes
/*****
 * Adds a new node or replaces an existing node in the Document
 * 
 * @param doc Target document where the node will added
 * @param xmlEntity contains definition of the xml entity
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws XPathExpressionException
 */
public static void addNewNode(final Document doc, final XmlEntity xmlEntity)
    throws IOException, XPathExpressionException, SAXException, ParserConfigurationException {
  // Build up map per call to avoid issues with caching wrong version of the map.
  final LinkedHashMap<String, CacheElement> elementOrderMap = CacheElement.buildElementMap(doc);

  final Node newNode = createNode(doc, xmlEntity.getXmlDefinition());
  final Node root = doc.getDocumentElement();
  final int incomingElementOrder =
      getElementOrder(elementOrderMap, xmlEntity.getNamespace(), xmlEntity.getType());

  boolean nodeAdded = false;
  NodeList nodes = root.getChildNodes();
  final int length = nodes.getLength();
  for (int i = 0; i < length; i++) {
    final Node node = nodes.item(i);

    if (node instanceof Element) {
      final Element childElement = (Element) node;
      final String type = childElement.getLocalName();
      final String namespace = childElement.getNamespaceURI();

      if (namespace.equals(xmlEntity.getNamespace()) && type.equals(xmlEntity.getType())) {
        // TODO this should really be checking all attributes in xmlEntity.getAttributes
        // First check if the element has a name
        String nameOrId = getAttribute(childElement, "name");
        // If not then check if the element has an Id
        if (nameOrId == null) {
          nameOrId = getAttribute(childElement, "id");
        }

        if (nameOrId != null) {
          // If there is a match , then replace the existing node with the incoming node
          if (nameOrId.equals(xmlEntity.getNameOrId())) {
            root.replaceChild(newNode, node);
            nodeAdded = true;
            break;
          }
        } else {
          // This element does not have any name or id identifier for e.g PDX and gateway-receiver
          // If there is only one element of that type then replace it with the incoming node
          if (!isMultiple(elementOrderMap, namespace, type)) {
            root.replaceChild(newNode, node);
            nodeAdded = true;
            break;
          }
        }
      } else {
        if (incomingElementOrder < getElementOrder(elementOrderMap, namespace, type)) {
          root.insertBefore(newNode, node);
          nodeAdded = true;
          break;
        }
      }
    }
  }
  if (!nodeAdded) {
    root.appendChild(newNode);
  }
}