Example usage for org.w3c.dom Node removeChild

List of usage examples for org.w3c.dom Node removeChild

Introduction

In this page you can find the example usage for org.w3c.dom Node removeChild.

Prototype

public Node removeChild(Node oldChild) throws DOMException;

Source Link

Document

Removes the child node indicated by oldChild from the list of children, and returns it.

Usage

From source file:org.yawlfoundation.yawl.util.DOMUtil.java

/**
 * Takes the supplied node and recursively removes empty (no content/child nodes) elements
 *
 * @param node to remove all empty elements from
 * @return Trimmed node/*from   ww w.ja va2  s.  c om*/
 * @deprecated
 * @throws XPathExpressionException
 */
public static Node removeEmptyElements(Node node) throws XPathExpressionException {

    NodeList list = selectNodeList(node, "*[string-length(normalize-space(.)) = 0]");

    for (int i = 0; i < list.getLength(); i++) {
        node.removeChild(list.item(i));
    }

    if (node.hasChildNodes()) {
        NodeList childs = node.getChildNodes();
        for (int i = 0; i < childs.getLength(); i++) {
            if (childs.item(i) instanceof Element) {
                removeEmptyElements(childs.item(i));
            }
        }
    }

    return node;
}

From source file:org.yawlfoundation.yawl.util.DOMUtil.java

/**
 * Removes all child nodes from the context Node node.
 * @param node to remove all children from
 */// ww  w  .  ja va2 s  .c o m
public static void removeAllChildNodes(Node node) {
    NodeList children = node.getChildNodes();
    for (int j = children.getLength() - 1; j >= 0; node.removeChild(children.item(j)), j--)
        ;
}

From source file:ru.codeinside.gws.crypto.cryptopro.CryptoProvider.java

@Override
public String signElement(String sourceXML, String elementName, String namespace, boolean removeIdAttribute,
        boolean signatureAfterElement, boolean inclusive) throws Exception {
    loadCertificate();//ww  w .ja v  a2  s.c  o  m
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setCoalescing(true);
    dbf.setNamespaceAware(true);
    DocumentBuilder documentBuilder = dbf.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(sourceXML));
    Document doc = documentBuilder.parse(is);
    Element elementForSign = (Element) doc.getElementsByTagNameNS(namespace, elementName).item(0);

    Node parentNode = null;
    Element detachedElementForSign;
    Document detachedDocument;
    if (!elementForSign.isSameNode(doc.getDocumentElement())) {
        parentNode = elementForSign.getParentNode();
        parentNode.removeChild(elementForSign);

        detachedDocument = documentBuilder.newDocument();
        Node importedElementForSign = detachedDocument.importNode(elementForSign, true);
        detachedDocument.appendChild(importedElementForSign);
        detachedElementForSign = detachedDocument.getDocumentElement();
    } else {
        detachedElementForSign = elementForSign;
        detachedDocument = doc;
    }

    String signatureMethodUri = inclusive ? "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr34102001-gostr3411"
            : "http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411";
    String canonicalizationMethodUri = inclusive ? "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
            : "http://www.w3.org/2001/10/xml-exc-c14n#";
    XMLSignature sig = new XMLSignature(detachedDocument, "", signatureMethodUri, canonicalizationMethodUri);
    if (!removeIdAttribute) {
        detachedElementForSign.setAttribute("Id", detachedElementForSign.getTagName());
    }
    if (signatureAfterElement)
        detachedElementForSign.insertBefore(sig.getElement(),
                detachedElementForSign.getLastChild().getNextSibling());
    else {
        detachedElementForSign.insertBefore(sig.getElement(), detachedElementForSign.getFirstChild());
    }
    Transforms transforms = new Transforms(detachedDocument);
    transforms.addTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature");
    transforms.addTransform(inclusive ? "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"
            : "http://www.w3.org/2001/10/xml-exc-c14n#");

    String digestURI = inclusive ? "urn:ietf:params:xml:ns:cpxmlsec:algorithms:gostr3411"
            : "http://www.w3.org/2001/04/xmldsig-more#gostr3411";
    sig.addDocument(removeIdAttribute ? "" : "#" + detachedElementForSign.getTagName(), transforms, digestURI);
    sig.addKeyInfo(cert);
    sig.sign(privateKey);

    if ((!elementForSign.isSameNode(doc.getDocumentElement())) && (parentNode != null)) {
        Node signedNode = doc.importNode(detachedElementForSign, true);
        parentNode.appendChild(signedNode);
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer trans = tf.newTransformer();
    trans.setOutputProperty("omit-xml-declaration", "yes");
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    trans.transform(new DOMSource(doc), streamResult);
    return stringWriter.toString();
}

From source file:ru.codeinside.gws3572c.GMPClientSignTest.java

@Test
public void testSignForEntity() throws Exception {
    ClientRequest request = client.createClientRequest(createContext());
    InputSource is = new InputSource(new StringReader(request.appData));
    Document doc = documentBuilder.parse(is);

    Element elementForSign = (Element) doc.getElementsByTagNameNS(null, "Charge").item(0);

    Node parentNode;
    Document detachedDocument;/* w  w w.  j a v  a  2  s  .  c om*/
    if (!elementForSign.isSameNode(doc.getDocumentElement())) {
        parentNode = elementForSign.getParentNode();
        parentNode.removeChild(elementForSign);

        detachedDocument = documentBuilder.newDocument();
        Node importedElementForSign = detachedDocument.importNode(elementForSign, true);
        detachedDocument.appendChild(importedElementForSign);
    } else {
        detachedDocument = doc;
    }

    Element nscontext = detachedDocument.createElementNS(null, "namespaceContext");
    nscontext.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + "ds".trim(),
            "http://www.w3.org/2000/09/xmldsig#");

    Element certificateElement = (Element) XPathAPI.selectSingleNode(detachedDocument,
            "//ds:X509Certificate[1]", nscontext);
    Element sigElement = (Element) certificateElement.getParentNode().getParentNode().getParentNode();

    XMLSignature signature = new XMLSignature(sigElement, "");

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate certKey = (X509Certificate) cf.generateCertificate(
            new ByteArrayInputStream(Base64.decode(certificateElement.getTextContent().trim().getBytes())));

    Assert.assertNotNull("There are no information about public key. Verification couldn't be implemented",
            certKey);
    Assert.assertTrue("Signature is not valid", signature.checkSignatureValue(certKey));
}

From source file:ru.runa.wf.web.FormPresentationUtils.java

private static Element wrapSelectToErrorContainer(Document document, Node selectNode, String selectName,
        boolean required) {
    Node parentNode = selectNode.getParentNode();
    if (parentNode instanceof Element && ERROR_CONTAINER.equalsIgnoreCase(parentNode.getNodeName())) {
        return (Element) parentNode;
    }//  w w  w. ja  v  a 2s . c o  m
    log.debug("Wrapping select[name='" + selectName + "'] to " + ERROR_CONTAINER);
    parentNode.removeChild(selectNode);
    Element div = document.createElement(ERROR_CONTAINER);
    if (required) {
        addClassAttribute(div, "requiredWrapper");
    }
    div.appendChild(selectNode);
    parentNode.appendChild(div);
    return div;
}

From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java

/**
 * Transforms the given <code>xml</code> section from KFS3 format to KFS6
 * format./*w ww. j  ava  2s .co m*/
 * 
 * @param xml
 *            {@link String} of the XML to transform
 * @return {@link String} of the transformed XML
 * @throws Exception
 *             Any {@link Exception}s encountered will be rethrown.
 */
private String transformSection(String xml, String docid) throws Exception {
    String rawXml = xml;
    String maintenanceAction = StringUtils.substringBetween(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">",
            "</" + MAINTENANCE_ACTION_ELEMENT_NAME + ">");
    xml = StringUtils.substringBefore(xml, "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">");

    xml = upgradeBONotes(xml, docid);

    if (classNameRuleMap == null) {
        setRuleMaps();
    }

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document;
    try {
        document = db.parse(new InputSource(new StringReader(xml)));
    } catch (SAXParseException ex) {
        String eol = System.getProperty("line.separator");
        String exMsg = "Failed in db.parse(new InputSource(new StringReader(xml))) where xml=" + xml + eol
                + "of maintenanceAction = " + maintenanceAction + eol + "contained in rawXml = " + rawXml;
        throw new SAXParseException(exMsg, null, ex);
    }

    for (Node childNode = document.getFirstChild(); childNode != null;) {
        Node nextChild = childNode.getNextSibling();
        transformClassNode(document, childNode);
        // Also Transform first level Children which have class attribute
        NodeList children = childNode.getChildNodes();
        for (int n = 0; n < children.getLength(); n++) {
            Node child = children.item(n);
            if ((child != null) && (child.getNodeType() == Node.ELEMENT_NODE) && (child.hasAttributes())) {
                NamedNodeMap childAttributes = child.getAttributes();
                if (childAttributes.item(0).getNodeName() == "class") {
                    String childClassName = childAttributes.item(0).getNodeValue();
                    if (classPropertyRuleMap.containsKey(childClassName)) {
                        Map<String, String> propertyMappings = classPropertyRuleMap.get(childClassName);
                        NodeList nestedChildren = child.getChildNodes();
                        for (int i = 0; i < nestedChildren.getLength() - 1; i++) {
                            Node property = nestedChildren.item(i);
                            String propertyName = property.getNodeName();
                            if ((property.getNodeType() == Node.ELEMENT_NODE) && (propertyMappings != null)
                                    && (propertyMappings.containsKey(propertyName))) {
                                String newPropertyName = propertyMappings.get(propertyName);
                                if (StringUtils.isNotBlank(newPropertyName)) {
                                    document.renameNode(property, null, newPropertyName);
                                    propertyName = newPropertyName;
                                } else {
                                    // If there is no replacement name then the element needs to be removed
                                    child.removeChild(property);
                                }
                            }
                        }
                    }
                }
            }
        }
        childNode = nextChild;
    }

    /*
     * the default logic that traverses over the document tree doesn't
     * handle classes that are in an @class attribute, so we deal with those
     * individually.
     */
    migratePersonObjects(document);
    migrateKualiCodeBaseObjects(document);
    migrateAccountExtensionObjects(document);
    migrateClassAsAttribute(document);
    removeAutoIncrementSetElements(document);
    removeReconcilerGroup(document);
    catchMissedTypedArrayListElements(document);

    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer trans = transFactory.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");

    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    DOMSource source = new DOMSource(document);
    trans.transform(source, result);
    /*
     * (?m) puts the regex into multiline mode:
     * https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.
     * html#MULTILINE So the effect of this statement is
     * "remove any empty lines"
     */
    xml = writer.toString().replaceAll("(?m)^\\s+\\n", "");
    xml = xml + "<" + MAINTENANCE_ACTION_ELEMENT_NAME + ">" + maintenanceAction + "</"
            + MAINTENANCE_ACTION_ELEMENT_NAME + ">";

    // replace classnames not updated so far that were captured by smoke test below
    // Using context specific replacements in case match replacement pairs entered are too generic
    for (String className : classNameRuleMap.keySet()) {
        if (xml.contains("active defined-in=\"" + className + "\"")) {
            LOGGER.info("Replacing active defined-in= attribute: " + className + " with: "
                    + classNameRuleMap.get(className) + " at docid= " + docid);
            xml = xml.replace("active defined-in=\"" + className + "\"",
                    "active defined-in=\"" + classNameRuleMap.get(className) + "\"");
        }
    }

    // Using context specific replacements in case match replacement pairs entered are too generic
    for (String className : classNameRuleMap.keySet()) {
        if (xml.contains("<" + className + ">")) {
            LOGGER.info("Replacing open tag: <" + className + "> with: <" + classNameRuleMap.get(className)
                    + ">" + " at docid= " + docid);
            xml = xml.replace("<" + className + ">", "<" + classNameRuleMap.get(className) + ">");
        }
    }

    // Using context specific replacements in case match replacement pairs entered are too generic
    for (String className : classNameRuleMap.keySet()) {
        if (xml.contains("</" + className + ">")) {
            LOGGER.info("Replacing close tag: </" + className + "> with: </" + classNameRuleMap.get(className)
                    + ">" + " at docid= " + docid);
            xml = xml.replace("</" + className + ">", "</" + classNameRuleMap.get(className) + ">");
        }
    }

    // replace classnames not updated so far that were captured by smoke test below
    // Using context specific replacements in case match replacement pairs entered are too generic
    for (String className : classNameRuleMap.keySet()) {
        if (xml.contains("maintainableImplClass=\"" + className + "\"")) {
            LOGGER.info("Replacing maintainableImplClass= attribute: " + className + " with: "
                    + classNameRuleMap.get(className) + " at docid= " + docid);
            xml = xml.replace("maintainableImplClass=\"" + className + "\"",
                    "maintainableImplClass=\"" + classNameRuleMap.get(className) + "\"");
        }
    }

    // investigative logging, still useful as a smoke test
    for (String oldClassName : classNameRuleMap.keySet()) {
        if (xml.contains(oldClassName)) {
            LOGGER.warn("Document has classname in contents that should have been mapped: " + oldClassName);
            LOGGER.warn("at docid= " + docid + " for xml= " + xml);
        }
    }
    checkForElementsWithClassAttribute(document);
    return xml;
}

From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java

private void removeAutoIncrementSetElements(Document document) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = null;/*  w  w w. j  a  va  2s . co m*/
    try {
        expr = xpath.compile("//autoIncrementSet");
        NodeList matchingNodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < matchingNodes.getLength(); i++) {
            Node match = matchingNodes.item(i);
            Node parent = match.getParentNode();
            LOGGER.trace("Removing element 'autoIncrementSet' in " + parent.getNodeName());
            parent.removeChild(match);
        }
    } catch (XPathExpressionException e) {
        LOGGER.error("XPathException encountered: ", e);
    }
}

From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java

@SuppressWarnings("unused")
/*/*from  w  ww  . ja v  a  2  s .  c  o m*/
 * used when debugging, might need to re-enable, not throwing away code just
 * yet
 */
private void removeAssetExtensionElements(Document document) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = null;
    try {
        expr = xpath.compile("//*[@class='edu.arizona.kfs.module.cam.businessobject.AssetExtension']");
        NodeList matchingNodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < matchingNodes.getLength(); i++) {
            Node match = matchingNodes.item(i);
            Node parent = match.getParentNode();
            LOGGER.info("Removing element 'edu.arizona.kfs.module.cam.businessobject.AssetExtension' in "
                    + parent.getNodeName());
            parent.removeChild(match);
        }
    } catch (XPathExpressionException e) {
        LOGGER.error("XPathException encountered: ", e);
    }
}

From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java

private void removeReconcilerGroup(Document document) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = null;/*from w  w w  . j a v a2s  .  c o  m*/
    try {
        expr = xpath.compile("//reconcilerGroup");
        NodeList matchingNodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < matchingNodes.getLength(); i++) {
            Node match = matchingNodes.item(i);
            Node parent = match.getParentNode();
            LOGGER.trace("Removing element 'reconcilerGroup' in " + parent.getNodeName());
            parent.removeChild(match);
        }
    } catch (XPathExpressionException e) {
        LOGGER.error("XPathException encountered: ", e);
    }
}

From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java

/**
 * Migrate any elements with the <code>class</code> containing
 * <code>PersonImpl</code> from the provided {@link Document} if there is a
 * mapping in {@link #classNameRuleMap}.
 * //from  w w  w .ja  va2  s.  com
 * @param doc
 */
public void migratePersonObjects(Document doc) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression personProperties = null;
    try {
        String personImplClassName = null;
        for (String key : classNameRuleMap.keySet()) {
            if (key.endsWith("PersonImpl")) {
                personImplClassName = key;
            }
        }
        // if no mapping, nothing to do here
        if (personImplClassName == null) {
            return;
        }
        personProperties = xpath.compile("//*[@class='" + personImplClassName + "']");
        NodeList matchingNodes = (NodeList) personProperties.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < matchingNodes.getLength(); i++) {
            Node tempNode = matchingNodes.item(i);
            LOGGER.trace(
                    "Migrating PersonImpl node: " + tempNode.getNodeName() + "/" + tempNode.getNodeValue());
            // first, migrate address pieces to an EntityAddress node
            NodeList childNodes = tempNode.getChildNodes();
            String line1 = null, line2 = null, line3 = null, city = null, stateProvinceCode = null,
                    postalCode = null, countryCode = null;
            for (int j = 0; j < childNodes.getLength(); j++) {
                Node child = childNodes.item(j);
                // FIXME magic strings
                if (child.getNodeName().equals("addressLine1")) {
                    line1 = child.getTextContent();
                    tempNode.removeChild(child);
                    continue;
                } else if (child.getNodeName().equals("addressLine2")) {
                    line2 = child.getTextContent();
                    tempNode.removeChild(child);
                    continue;
                } else if (child.getNodeName().equals("addressLine3")) {
                    line3 = child.getTextContent();
                    tempNode.removeChild(child);
                    continue;
                } else if (child.getNodeName().equals("addressCityName")) {
                    city = child.getTextContent();
                    tempNode.removeChild(child);
                    continue;
                } else if (child.getNodeName().equals("addressStateCode")) {
                    stateProvinceCode = child.getTextContent();
                    tempNode.removeChild(child);
                    continue;
                } else if (child.getNodeName().equals("addressPostalCode")) {
                    postalCode = child.getTextContent();
                    tempNode.removeChild(child);
                    continue;
                } else if (child.getNodeName().equals("addressCountryCode")) {
                    countryCode = child.getTextContent();
                    tempNode.removeChild(child);
                }
            }
        }
    } catch (XPathExpressionException e) {
        LOGGER.error("XPathException encountered: ", e);
    }
}