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:org.lareferencia.backend.harvester.OCLCBasedHarvesterImpl.java

/**
 * @param node//from   ww  w. j  a  v a  2  s. c  o  m
 * @param document 
 * @return 
 * @throws TransformerException
 * @throws NoSuchFieldException 
 */
private String getMetadataString(Node node, Document document)
        throws TransformerException, NoSuchFieldException {

    /**
     *  TODO: bsqueda secuencial, puede ser ineficiente pero xpath no esta implementado sobre nodos individaules
     *  en la interfaz listRecords, en necesario construir un DomHelper para Harvester, es sencillo dada la clase
     *  base BaseMetadataDOMHelper
     */

    NodeList childs = node.getChildNodes();
    Node metadataNode = null;
    for (int i = 0; i < childs.getLength(); i++)
        if (childs.item(i).getNodeName().contains(METADATA_NODE_NAME))
            metadataNode = childs.item(i);

    if (metadataNode == null)
        throw new NoSuchFieldException("No existe el nodo: " + METADATA_NODE_NAME + " en la respuesta.\n"
                + MedatadaDOMHelper.Node2XMLString(node));

    // este rename unifica los casos distintos de namespace encontrados en repositorios
    document.renameNode(metadataNode, metadataNode.getNamespaceURI(), METADATA_NODE_NAME);

    // TODO: Ver el tema del char &#56256;
    return MedatadaDOMHelper.Node2XMLString(metadataNode);
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

/**
 * thread-safety tested//from www  .j  av a 2  s.  co  m
 */
@Override
public String replaceRootTagWith(final String xmlData, final String rootTag) throws SAXException, IOException {

    Document document = parse(xmlData);

    String resultXml = "";
    if (rootTag == null) { // remove which will lose the attirbutes on the
        // root element
        NodeList nodes = document.getDocumentElement().getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node n = nodes.item(i);
            resultXml += DomUtils.elementToString((Element) n);
        }

    } else {
        document.renameNode(document.getFirstChild(), null, rootTag);

        resultXml = DomUtils.elementToString(document.getFirstChild());

    }

    return resultXml;

}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java

/**
 * This method takes the ER response and converts the Java objects to the Merge Response XML.
 * /* www . j a v a2s .  c o  m*/
 * @param entityContainerNode
 * @param results
 * @param recordLimit
 * @param attributeParametersNode
 * @return
 * @throws ParserConfigurationException
 * @throws XPathExpressionException
 * @throws TransformerException
 */
private Document createResponseMessage(Node entityContainerNode, EntityResolutionResults results,
        Node attributeParametersNode, int recordLimit) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    Document resultDocument = dbf.newDocumentBuilder().newDocument();

    Element entityMergeResultMessageElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityMergeResultMessage");
    resultDocument.appendChild(entityMergeResultMessageElement);

    Element entityContainerElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityContainer");
    entityMergeResultMessageElement.appendChild(entityContainerElement);

    NodeList inputEntityNodes = (NodeList) xpath.evaluate("er-ext:Entity", entityContainerNode,
            XPathConstants.NODESET);
    Collection<Element> inputEntityElements = null;
    if (attributeParametersNode == null) {
        inputEntityElements = new ArrayList<Element>();
    } else {
        inputEntityElements = TreeMultiset
                .create(new EntityElementComparator((Element) attributeParametersNode));
        //inputEntityElements = new ArrayList<Element>();
    }

    for (int i = 0; i < inputEntityNodes.getLength(); i++) {
        inputEntityElements.add((Element) inputEntityNodes.item(i));
    }

    if (attributeParametersNode == null) {
        LOG.warn("Attribute Parameters element was null, so records will not be sorted");
    }
    //Collections.sort((List<Element>) inputEntityElements, new EntityElementComparator((Element) attributeParametersNode));

    if (inputEntityElements.size() != inputEntityNodes.getLength()) {
        LOG.error("Lost elements in ER output sorting.  Input count=" + inputEntityNodes.getLength()
                + ", output count=" + inputEntityElements.size());
    }

    for (Element e : inputEntityElements) {
        Node clone = resultDocument.adoptNode(e.cloneNode(true));
        resultDocument.renameNode(clone, EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                e.getLocalName());
        entityContainerElement.appendChild(clone);
    }

    Element mergedRecordsElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "MergedRecords");
    entityMergeResultMessageElement.appendChild(mergedRecordsElement);

    if (results != null) {

        List<RecordWrapper> records = results.getRecords();

        // Loop through RecordWrappers to extract info to create merged records
        for (RecordWrapper record : records) {
            LOG.debug("  !#!#!#!# Record 1, id=" + record.getExternalId() + ", externals="
                    + record.getRelatedIds());

            // Create Merged Record Container
            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            // Create Original Record Reference for 'first record'
            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", record.getExternalId());
            mergedRecordElement.appendChild(originalRecordRefElement);

            // Loop through and add any related records
            for (String relatedRecordId : record.getRelatedIds()) {
                originalRecordRefElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
                originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                        "ref", relatedRecordId);
                mergedRecordElement.appendChild(originalRecordRefElement);
            }

            // Create Merge Quality Element
            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            Set<AttributeStatistics> stats = results.getStatisticsForRecord(record.getExternalId());
            for (AttributeStatistics stat : stats) {
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(stat.getAttributeName());
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode(String.valueOf(stat.getAverageStringDistance()));
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument
                        .createTextNode(String.valueOf(stat.getStandardDeviationStringDistance()));
                sdElement.appendChild(contentNode);

            }
        }

    } else {

        for (Element e : inputEntityElements) {

            String id = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "id");

            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", id);
            mergedRecordElement.appendChild(originalRecordRefElement);

            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            XPath xp = XPathFactory.newInstance().newXPath();
            xp.setNamespaceContext(new EntityResolutionNamespaceContext());
            NodeList attributeParameterNodes = (NodeList) xp.evaluate("er-ext:AttributeParameter",
                    attributeParametersNode, XPathConstants.NODESET);
            for (int i = 0; i < attributeParameterNodes.getLength(); i++) {
                String attributeName = xp.evaluate("er-ext:AttributeXPath", attributeParametersNode);
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(attributeName);
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode("0.0");
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument.createTextNode("0.0");
                sdElement.appendChild(contentNode);
            }

        }

    }

    Element recordLimitExceededElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "RecordLimitExceededIndicator");
    recordLimitExceededElement.setTextContent(new Boolean(results == null).toString());
    entityMergeResultMessageElement.appendChild(recordLimitExceededElement);

    return resultDocument;

}

From source file:fi.csc.kapaVirtaAS.MessageTransformer.java

public String transform(String message, MessageDirection direction) throws Exception {
    try {/*from www  .ja va  2s . c o  m*/
        DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = dBuilder
                .parse(new InputSource(new ByteArrayInputStream(stripXmlDefinition(message).getBytes())));
        doc.setXmlVersion("1.0");
        doc.normalizeDocument();
        Element root = doc.getDocumentElement();

        if (direction == MessageDirection.XRoadToVirta) {
            // Save XRoad schema prefix for response message
            xroadSchemaPrefix = namedNodeMapToStream(root.getAttributes())
                    .filter(node -> node
                            .getNodeValue().toLowerCase().contains(conf.getXroadSchema().toLowerCase()))
                    .findFirst()
                    .orElseThrow(
                            () -> new DOMException(DOMException.NOT_FOUND_ERR, "Xroad schema prefix not found"))
                    .getNodeName();

            xroadIdSchemaPrefix = namedNodeMapToStream(root.getAttributes())
                    .filter(node -> node.getNodeValue().toLowerCase()
                            .contains(conf.getXroadIdSchema().toLowerCase()))
                    .findFirst().orElseThrow(() -> new DOMException(DOMException.NOT_FOUND_ERR,
                            "XroadId schema prefix not found"))
                    .getNodeName();

            // Change tns schema
            getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getAdapterServiceSchema())
                    .map(attribute -> setNodeValueToNode(attribute, conf.getVirtaServiceSchema()));

            //There should be two children under the root node: header and body
            for (int i = 0; i < root.getChildNodes().getLength(); ++i) {
                Node child = root.getChildNodes().item(i);
                // Save soap-headers for reply message and remove child elements under soap-headers
                if (child.getNodeName().toLowerCase().contains("header")) {
                    this.xroadHeaderElement = child.cloneNode(true);
                    root.replaceChild(child.cloneNode(false), child);
                }
                // Change SOAP-body
                else if (child.getNodeName().toLowerCase().contains("body")) {
                    for (int j = 0; j < child.getChildNodes().getLength(); ++j) {
                        if (child.getChildNodes().item(j).getNodeType() == Node.ELEMENT_NODE) {
                            doc.renameNode(child.getChildNodes().item(j), conf.getVirtaServiceSchema(),
                                    child.getChildNodes().item(j).getNodeName() + "Request");
                            break;
                        }
                    }

                }
            }
        }
        if (direction == MessageDirection.VirtaToXRoad) {
            // Add XRoad schemas with saved prefix to response message
            root.setAttribute(xroadSchemaPrefix, conf.getXroadSchema());
            root.setAttribute(xroadIdSchemaPrefix, conf.getXroadIdSchema());

            // Change tns schema
            getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getVirtaServiceSchema())
                    .map(attribute -> setNodeValueToNode(attribute, conf.getAdapterServiceSchema()));

            // Change SOAP-headers
            Node headerNode = getNodeByKeyword(nodeListToStream(root.getChildNodes()), "header").get();
            for (int i = 0; i < this.xroadHeaderElement.getChildNodes().getLength(); ++i) {
                headerNode.appendChild(doc.importNode(this.xroadHeaderElement.getChildNodes().item(i), true));
            }

            // Change SOAP-body
            getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body")
                    .map(bodyNode -> removeAttribureFromElement(nodeToElement(bodyNode), virtaServicePrefix))
                    .map(bodyNode -> setAttributeToElement(nodeToElement(bodyNode), virtaServicePrefix,
                            conf.getAdapterServiceSchema()));

            //Virta gives malformed soap fault message. Need to parse it correct.
            getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body")
                    .map(bodyNode -> nodeListToStream(bodyNode.getChildNodes())).map(
                            nodesInBodyStream -> getNodeByKeyword(nodesInBodyStream, "fault")
                                    .map(faultNode -> removeAttribureFromElement(
                                            nodeToElement(nodeToElement(faultNode)
                                                    .getElementsByTagName("faultstring").item(0)),
                                            "xml:lang")));
        }

        doc.normalizeDocument();
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(domSource, result);
        message = writer.toString();

        return stripXmlDefinition(message);
    } catch (Exception e) {
        if (direction == MessageDirection.XRoadToVirta) {
            log.error("Error in parsing request message.");
            throw e;
        } else {
            log.error("Error in parsing response message");
            log.error(e.toString());
            return stripXmlDefinition(faultMessageService.generateSOAPFault(message,
                    faultMessageService.getResValidFail(), this.xroadHeaderElement));
        }
    }
}

From source file:org.apache.camel.blueprint.handler.CamelNamespaceHandler.java

public static void renameNamespaceRecursive(Node node) {
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Document doc = node.getOwnerDocument();
        if (((Element) node).getNamespaceURI().equals(BLUEPRINT_NS)) {
            doc.renameNode(node, SPRING_NS, node.getNodeName());
        }//from  ww  w.  j  av a2s .c  o m
    }
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); ++i) {
        renameNamespaceRecursive(list.item(i));
    }
}

From source file:org.apache.camel.spring.handler.CamelNamespaceHandler.java

public static void renameNamespaceRecursive(Node node) {
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Document doc = node.getOwnerDocument();
        if (node.getNamespaceURI().startsWith(SPRING_NS + "/v")) {
            doc.renameNode(node, SPRING_NS, node.getNodeName());
        }/*from w w w .  j av a 2 s  .c  om*/
    }
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); ++i) {
        renameNamespaceRecursive(list.item(i));
    }
}

From source file:org.apache.geode.session.tests.ContainerInstall.java

/**
 * Edit the given xml file/*from   w  w  w . java  2s .  c  o m*/
 *
 * Uses {@link #findNodeWithAttribute(Document, String, String, String)},
 * {@link #rewriteNodeAttributes(Node, HashMap)},
 * {@link #nodeHasExactAttributes(Node, HashMap, boolean)} to edit the required parts of the XML
 * file.
 * 
 * @param XMLPath The path to the xml file to edit
 * @param tagId The id of tag to edit. If null, then this method will add a new xml element,
 *        unless writeOnSimilarAttributeNames is set to true.
 * @param tagName The name of the xml element to edit
 * @param replacementTagName The new name of the XML attribute that is being edited
 * @param parentTagName The parent element of the element we should edit
 * @param attributes the xml attributes for the element to edit
 * @param writeOnSimilarAttributeNames If true, find an existing element with the same set of
 *        attributes as the attributes parameter, and modifies the attributes of that element,
 *        rather than adding a new element. If false, create a new XML element (unless tagId is
 *        not null).
 */
protected static void editXMLFile(String XMLPath, String tagId, String tagName, String replacementTagName,
        String parentTagName, HashMap<String, String> attributes, boolean writeOnSimilarAttributeNames) {

    try {
        // Get XML file to edit
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(XMLPath);

        Node node = null;
        // Get node with specified tagId
        if (tagId != null) {
            node = findNodeWithAttribute(doc, tagName, "id", tagId);
        }
        // If writing on similar attributes then search by tag name
        else if (writeOnSimilarAttributeNames) {
            // Get all the nodes with the given tag name
            NodeList nodes = doc.getElementsByTagName(tagName);
            for (int i = 0; i < nodes.getLength(); i++) {
                Node n = nodes.item(i);
                // If the node being iterated across has the exact attributes then it is the one that
                // should be edited
                if (nodeHasExactAttributes(n, attributes, false)) {
                    node = n;
                    break;
                }
            }
        }
        // If a node if found
        if (node != null) {
            doc.renameNode(node, null, replacementTagName);
            // Rewrite the node attributes
            rewriteNodeAttributes(node, attributes);
            // Write the tagId so that it can be found easier next time
            if (tagId != null)
                ((Element) node).setAttribute("id", tagId);
        }
        // No node found creates new element under the parent tag passed in
        else {
            Element e = doc.createElement(replacementTagName);
            // Set id attribute
            if (tagId != null) {
                e.setAttribute("id", tagId);
            }
            // Set other attributes
            for (String key : attributes.keySet()) {
                e.setAttribute(key, attributes.get(key));
            }

            // Add it as a child of the tag for the file
            doc.getElementsByTagName(parentTagName).item(0).appendChild(e);
        }

        // Write updated XML file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(XMLPath));
        transformer.transform(source, result);

        logger.info("Modified container XML file " + XMLPath);
    } catch (Exception e) {
        throw new RuntimeException("Unable to edit XML file", e);
    }
}

From source file:org.apache.sling.stanbol.ui.StanbolResourceViewer.java

private Element parseBody(String string) throws SAXException, IOException, ParserConfigurationException {
    InputSource inputSource = new InputSource(new StringReader(string));
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputSource);
    Element docElem = doc.getDocumentElement();
    docElem.removeAttribute("id");
    doc.renameNode(docElem, null, "body");
    return docElem;
}

From source file:org.eclipse.skalli.model.ext.maven.internal.DataMigrationMavenModule.java

@Override
public void migrate(Document doc) throws MigrationException {
    NodeList nodes = doc.getElementsByTagName("org.eclipse.skalli.model.ext.maven.MavenCoordinate"); //$NON-NLS-1$
    for (int i = 0; i < nodes.getLength(); i++) {
        doc.renameNode(nodes.item(i), null, "org.eclipse.skalli.model.ext.maven.MavenModule"); //$NON-NLS-1$
    }//from   www . jav  a 2  s  .  co  m
}