Example usage for org.w3c.dom Document renameNode

List of usage examples for org.w3c.dom Document renameNode

Introduction

In this page you can find the example usage for org.w3c.dom Document renameNode.

Prototype

public Node renameNode(Node n, String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Rename an existing node of type ELEMENT_NODE or ATTRIBUTE_NODE.

Usage

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

/**
 * Transforms the given <code>xml</code> section from KFS3 format to KFS6
 * format.//from w  ww .j  a  v  a  2 s. 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

/**
 * Map the classnames as described in {@link #classNameRuleMap}, finding the
 * elements to transform via XPath against the top level {@link Document}.
 * //from   www .j ava 2  s.c  o  m
 * @param document
 */
private void mapClassNamesWithXPath(Document document) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = null;
    LOGGER.trace("Doing XPath transformations for classnames.");
    for (String classname : classNameRuleMap.keySet()) {
        try {
            expr = xpath.compile("//" + classname);
            NodeList matchingNodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
            for (int i = 0; i < matchingNodes.getLength(); i++) {
                String mapTo = classNameRuleMap.get(classname);
                LOGGER.trace("Renaming class " + classname + " to " + mapTo);
                document.renameNode(matchingNodes.item(i), null, mapTo);
            }
        } catch (XPathExpressionException e) {
            LOGGER.error("XPathException encountered: ", e);
        }
    }

}

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

/**
 * Map the class properties as described in {@link #classPropertyRuleMap},
 * finding the elements to transform via XPath against the top level
 * {@Link Document}./*www.jav  a  2s . c  o m*/
 * 
 * @param document
 */
private void mapClassPropertiesWithXPath(Document document) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = null;
    LOGGER.trace("Doing XPath transformations for class properties.");
    for (String classname : classPropertyRuleMap.keySet()) {
        try {
            expr = xpath.compile("//" + classname);
            NodeList matchingNodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
            for (int i = 0; i < matchingNodes.getLength(); i++) {
                Map<String, String> propertyMappings = classPropertyRuleMap.get(classname);
                for (String propertyName : propertyMappings.keySet()) {
                    expr = xpath.compile("//" + classname + "/" + propertyName);
                    NodeList propertyNodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
                    for (int j = 0; j < propertyNodes.getLength(); j++) {
                        String mapTo = propertyMappings.get(propertyName);
                        /*
                         * if map target is empty, remove the node.
                         * Otherwise, rename to value.
                         */
                        if (mapTo == null || mapTo.isEmpty()) {
                            LOGGER.trace("Removing property " + propertyName);
                            propertyNodes.item(j).getParentNode().removeChild(propertyNodes.item(j));
                        } else {
                            LOGGER.trace("Renaming property " + propertyName + " to " + mapTo);
                            document.renameNode(propertyNodes.item(j), null, mapTo);
                        }
                    }
                }
            }
        } 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>KualiCodeBase</code> from the provided {@link Document} if there is
 * a mapping in {@link #classNameRuleMap}.
 * //from w ww .j a v a2 s.c o m
 * @param doc
 */
public void migrateKualiCodeBaseObjects(Document doc) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression personProperties = null;
    try {
        String kualiCodeBaseClassName = null;
        for (String key : classNameRuleMap.keySet()) {
            if (key.endsWith("KualiCodeBase")) {
                kualiCodeBaseClassName = key;
            }
        }
        // if no mapping, nothing to do here
        if (kualiCodeBaseClassName == null) {
            return;
        }
        personProperties = xpath.compile("//*[@class='" + kualiCodeBaseClassName + "']");
        NodeList matchingNodes = (NodeList) personProperties.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < matchingNodes.getLength(); i++) {
            Node tempNode = matchingNodes.item(i);
            LOGGER.trace(
                    "Migrating KualiCodeBase node: " + tempNode.getNodeName() + "/" + tempNode.getNodeValue());
            String newClassName = this.classNameRuleMap.get(kualiCodeBaseClassName);
            doc.renameNode(tempNode, null, newClassName);
        }
    } catch (XPathExpressionException e) {
        LOGGER.error("XPathException encountered: ", e);
    }
}

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

/**
 * TODO comment/* ww  w.  ja  v a2s .  c om*/
 * 
 * @param doc
 */
public void migrateAccountExtensionObjects(Document doc) {
    // FIXME all sorts of magic strings
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression accountExtensionProperties = null;
    try {
        accountExtensionProperties = xpath
                .compile("//*[@class='edu.arizona.kfs.coa.businessobject.AccountExtension']");
        NodeList matchingNodes = (NodeList) accountExtensionProperties.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < matchingNodes.getLength(); i++) {
            Node tempNode = matchingNodes.item(i);
            LOGGER.trace("Migrating AccountExtension node: " + tempNode.getNodeName() + "/"
                    + tempNode.getNodeValue());
            // migrate taxRegionCodeExt -> taxRegionCode
            NodeList children = tempNode.getChildNodes();
            for (int j = 0; j < children.getLength(); j++) {
                Node child = children.item(j);
                if (child.getNodeName().equals("taxRegionCodeExt")) {
                    doc.renameNode(child, null, "taxRegionCode");
                }
            }
        }
    } catch (XPathExpressionException e) {
        LOGGER.error("XPathException encountered: ", e);
    }
}

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

/**
 * If a mapping for the <code>node</code> class exists in
 * {@link #classNameRuleMap}, the given <code>node</code> is renamed. Then,
 * if the <code>node</code> is a valid class, it is passed to the
 * {@link #transformNode(Document, Node, Class, Map)} method first with the
 * {@link #classPropertyRuleMap} value for the classname, then with the
 * {@link #classPropertyRuleMap} value for "<code>*</code>".
 * /*from w  w w  . jav  a 2s.com*/
 * @param document
 *            Root level {@link Document}
 * @param node
 *            {@link Node} to transform
 * @throws ClassNotFoundException
 * @throws XPathExpressionException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws InstantiationException
 */
private void transformClassNode(Document document, Node node)
        throws ClassNotFoundException, XPathExpressionException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, InstantiationException {

    String className = node.getNodeName();
    LOGGER.trace("Transforming class node for : " + node.getBaseURI() + "/" + className);
    if (this.classNameRuleMap.containsKey(className)) {
        String newClassName = this.classNameRuleMap.get(className);
        document.renameNode(node, null, newClassName);
        className = newClassName;
    }

    if (isValidClass(className)) {
        Class<?> dataObjectClass = Class.forName(className);

        if (classPropertyRuleMap.containsKey(className)) {
            transformNode(document, node, dataObjectClass, classPropertyRuleMap.get(className));
        }

        transformNode(document, node, dataObjectClass, classPropertyRuleMap.get("*"));
    } else if (xPathTransformationRulesMap.containsKey(className)) {
        //specific transformations for docs whose classes cannot be instantiated like in the above code.
        xPathApplyTransformations(document, className, xPathTransformationRulesMap.get(className));
    }
}

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

/**
 * For each child of <code>node</code>
 * /*from  w ww.  ja  va 2s .  com*/
 * @param document
 * @param node
 * @param currentClass
 * @param propertyMappings
 * @throws ClassNotFoundException
 * @throws XPathExpressionException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws InstantiationException
 */
private void transformNode(Document document, Node node, Class<?> currentClass,
        Map<String, String> propertyMappings) throws ClassNotFoundException, XPathExpressionException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException {
    LOGGER.trace("Transforming node: " + node.getBaseURI() + "/" + node.getNodeName());
    for (Node childNode = node.getFirstChild(); childNode != null;) {
        Node nextChild = childNode.getNextSibling();
        String propertyName = childNode.getNodeName();
        if (childNode.hasAttributes()) {
            XPath xpath = XPathFactory.newInstance().newXPath();
            Node serializationAttribute = childNode.getAttributes().getNamedItem(SERIALIZATION_ATTRIBUTE);
            if (serializationAttribute != null
                    && StringUtils.equals(serializationAttribute.getNodeValue(), "custom")) {
                Node classAttribute = childNode.getAttributes().getNamedItem(CLASS_ATTRIBUTE);
                if (classAttribute != null && StringUtils.equals(classAttribute.getNodeValue(),
                        "org.kuali.rice.kns.util.TypedArrayList")) {
                    handleTypedArrayList(document, xpath, (Element) childNode);
                } else if (isTargetEffortCertificationReportPositionsNode(childNode)) {
                    // Need to skip over ECRD positions list due to needing serialization attr
                    // that otherwise was getting stripped on line 924. This also avoids a child
                    // list node from getting errantly pruned off ECRD doc types
                    deleteAllNoneListProxyChildren(childNode);
                } else {
                    ((Element) childNode).removeAttribute(SERIALIZATION_ATTRIBUTE);

                    XPathExpression mapContentsExpression = xpath.compile("//" + propertyName + "/map/string");
                    NodeList mapContents = (NodeList) mapContentsExpression.evaluate(childNode,
                            XPathConstants.NODESET);
                    List<Node> nodesToAdd = new ArrayList<Node>();
                    if (mapContents.getLength() > 0 && mapContents.getLength() % 2 == 0) {
                        for (int i = 0; i < mapContents.getLength(); i++) {
                            Node keyNode = mapContents.item(i);
                            Node valueNode = mapContents.item(++i);
                            Node entryNode = document.createElement("entry");
                            entryNode.appendChild(keyNode);
                            entryNode.appendChild(valueNode);
                            nodesToAdd.add(entryNode);
                        }
                    }
                    for (Node removeNode = childNode.getFirstChild(); removeNode != null;) {
                        Node nextRemoveNode = removeNode.getNextSibling();
                        childNode.removeChild(removeNode);
                        removeNode = nextRemoveNode;
                    }
                    for (Node nodeToAdd : nodesToAdd) {
                        childNode.appendChild(nodeToAdd);
                    }
                }
            }
        }
        if (propertyMappings != null && propertyMappings.containsKey(propertyName)) {
            String newPropertyName = propertyMappings.get(propertyName);
            if (StringUtils.isNotBlank(newPropertyName)) {
                document.renameNode(childNode, null, newPropertyName);
                propertyName = newPropertyName;
            } else {
                // If there is no replacement name then the element needs
                // to be removed and skip all other processing
                node.removeChild(childNode);
                childNode = nextChild;
                continue;
            }
        }

        if (dateRuleMap != null && dateRuleMap.containsKey(propertyName)) {
            String newDateValue = dateRuleMap.get(propertyName);
            if (StringUtils.isNotBlank(newDateValue)) {
                if (childNode.getTextContent().length() == 10) {
                    childNode.setTextContent(childNode.getTextContent() + " " + newDateValue);

                }
            }
        }

        if ((currentClass != null) && isValidClass(currentClass)) {
            if (childNode.hasChildNodes() && !(Collection.class.isAssignableFrom(currentClass)
                    || Map.class.isAssignableFrom(currentClass))) {
                PropertyClassKey key = new PropertyClassKey(currentClass, propertyName);
                Optional<Class<?>> propertyClass = propertyClassCache.getUnchecked(key);
                if (propertyClass.isPresent()
                        && classPropertyRuleMap.containsKey(propertyClass.get().getName())) {
                    transformNode(document, childNode, propertyClass.get(),
                            this.classPropertyRuleMap.get(propertyClass.get().getName()));
                }
                transformNode(document, childNode, propertyClass.orNull(), classPropertyRuleMap.get("*"));
            }
        }
        childNode = nextChild;
    }
}

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

private void replaceNode(Document document, String pathToNode, String newNodeName) {
    LOGGER.trace("Replacing path " + pathToNode + " : with " + newNodeName);
    try {/*from   w ww  .  j  a va  2 s  .  c o m*/
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression nodesFilter = xpath.compile(pathToNode);
        NodeList matchingNodes = (NodeList) nodesFilter.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < matchingNodes.getLength(); i++) {
            Node tempNode = matchingNodes.item(i);
            LOGGER.trace("Migrating node: " + tempNode.getNodeName() + "/" + tempNode.getTextContent());
            document.renameNode(tempNode, null, newNodeName);
        }
    } catch (XPathExpressionException e) {
        LOGGER.error("XPathException encountered: ", e);
    }
}