Example usage for org.w3c.dom Node normalize

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

Introduction

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

Prototype

public void normalize();

Source Link

Document

Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

Usage

From source file:com.icesoft.faces.context.DOMResponseWriter.java

/**
 * Copy the one generated stateSaving branch into all the marker (one per form)
 * node areas. <p>//from  w w w  . jav a2s  .  c o m
 * This method shouldn't be called if state saving is not enabled
 */
public void copyStateNodesToMarkers() {

    Iterator i = markerNodes.iterator();
    while (i.hasNext()) {

        Node n = (Node) i.next();
        if ((n != null) && (savedJSFStateCursor != null)) {

            String nodeValue;

            // The View state consists of 4 sibling text nodes. We need to find the one
            // with the actual id, and preserve that ID in the PersistentFacesState object
            // so that server push operations can restore state as well.

            for (Node child = savedJSFStateCursor.getFirstChild(); child != null; child = child
                    .getNextSibling()) {

                nodeValue = child.getNodeValue();
                if (nodeValue != null && nodeValue.indexOf("j_id") > -1) {
                    PersistentFacesState.getInstance().setStateRestorationId(nodeValue);
                    if (log.isDebugEnabled()) {
                        log.debug("State id for server push state saving: " + nodeValue);
                    }
                }
                n.appendChild(child.cloneNode(true));
            }
        }
        //avoids unnecessary DOM diff due to normalization during
        //FastInfoset compression
        n.normalize();
    }
    markerNodes.clear();
}

From source file:org.apache.ambari.server.upgrade.UpgradeCatalog220.java

protected void updateKnoxTopology() throws AmbariException {
    AmbariManagementController ambariManagementController = injector
            .getInstance(AmbariManagementController.class);
    for (final Cluster cluster : getCheckedClusterMap(ambariManagementController.getClusters()).values()) {
        Config topology = cluster.getDesiredConfigByType(TOPOLOGY_CONFIG);
        if (topology != null) {
            String content = topology.getProperties().get(CONTENT_PROPERTY);
            if (content != null) {
                Document topologyXml = convertStringToDocument(content);
                if (topologyXml != null) {
                    Element root = topologyXml.getDocumentElement();
                    if (root != null) {
                        NodeList providerNodes = root.getElementsByTagName("provider");
                        boolean authorizationProviderExists = false;
                        try {
                            for (int i = 0; i < providerNodes.getLength(); i++) {
                                Node providerNode = providerNodes.item(i);
                                NodeList childNodes = providerNode.getChildNodes();
                                for (int k = 0; k < childNodes.getLength(); k++) {
                                    Node child = childNodes.item(k);
                                    child.normalize();
                                    String childTextContent = child.getTextContent();
                                    if (childTextContent != null
                                            && childTextContent.toLowerCase().equals("authorization")) {
                                        authorizationProviderExists = true;
                                        break;
                                    }//  w ww  . j a va2s. c om
                                }
                                if (authorizationProviderExists) {
                                    break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            LOG.error(
                                    "Error occurred during check 'authorization' provider already exists in topology."
                                            + e);
                            return;
                        }
                        if (!authorizationProviderExists) {
                            NodeList nodeList = root.getElementsByTagName("gateway");
                            if (nodeList != null && nodeList.getLength() > 0) {
                                boolean rangerPluginEnabled = isConfigEnabled(cluster,
                                        AbstractUpgradeCatalog.CONFIGURATION_TYPE_RANGER_KNOX_PLUGIN_PROPERTIES,
                                        AbstractUpgradeCatalog.PROPERTY_RANGER_KNOX_PLUGIN_ENABLED);

                                Node gatewayNode = nodeList.item(0);
                                Element newProvider = topologyXml.createElement("provider");

                                Element role = topologyXml.createElement("role");
                                role.appendChild(topologyXml.createTextNode("authorization"));
                                newProvider.appendChild(role);

                                Element name = topologyXml.createElement("name");
                                if (rangerPluginEnabled) {
                                    name.appendChild(topologyXml.createTextNode("XASecurePDPKnox"));
                                } else {
                                    name.appendChild(topologyXml.createTextNode("AclsAuthz"));
                                }
                                newProvider.appendChild(name);

                                Element enabled = topologyXml.createElement("enabled");
                                enabled.appendChild(topologyXml.createTextNode("true"));
                                newProvider.appendChild(enabled);

                                gatewayNode.appendChild(newProvider);

                                DOMSource topologyDomSource = new DOMSource(root);
                                StringWriter writer = new StringWriter();
                                try {
                                    Transformer transformer = TransformerFactory.newInstance().newTransformer();
                                    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                                    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                                            "5");
                                    transformer.transform(topologyDomSource, new StreamResult(writer));
                                } catch (TransformerConfigurationException e) {
                                    e.printStackTrace();
                                    LOG.error(
                                            "Unable to create transformer instance, to convert Document(XML) to String. "
                                                    + e);
                                    return;
                                } catch (TransformerException e) {
                                    e.printStackTrace();
                                    LOG.error("Unable to transform Document(XML) to StringWriter. " + e);
                                    return;
                                }

                                content = writer.toString();
                                Map<String, String> updates = Collections.singletonMap(CONTENT_PROPERTY,
                                        content);
                                updateConfigurationPropertiesForCluster(cluster, TOPOLOGY_CONFIG, updates, true,
                                        false);
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Get the value of the DOM node./*from  w w  w  .  j  ava 2s  .c  o  m*/
 * The value of a node is the content of the first text node.
 * If the node has no text nodes, <code>null</code> is returned.
 */
public static String getValueOfNode(Node node) {
    if (node != null) {
        if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
            return node.getNodeValue();
        } else {
            node.normalize();
            NodeList childs = node.getChildNodes();
            int i = 0;
            int length = childs.getLength();
            while (i < length) {
                if (childs.item(i).getNodeType() == Node.TEXT_NODE) {
                    return childs.item(i).getNodeValue().trim();
                } else {
                    i++;
                }
            }
        }
    }
    return null;
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Get a document fragment from a <code>Reader</code>.
 * The reader must provide valid XML, but it is allowed that the XML
 * has more than one root node. This xml is parsed by the
 * specified parser instance and a DOM DocumentFragment is created.
 *///from w  w w .ja  va 2s  .c om
public static DocumentFragment getDocumentFragment(SAXParser parser, Reader stream) throws ProcessingException {
    DocumentFragment frag = null;

    Writer writer;
    Reader reader;
    boolean removeRoot = true;

    try {
        // create a writer,
        // write the root element, then the input from the
        // reader
        writer = new StringWriter();

        writer.write(XML_ROOT_DEFINITION);
        char[] cbuf = new char[16384];
        int len;
        do {
            len = stream.read(cbuf, 0, 16384);
            if (len != -1) {
                writer.write(cbuf, 0, len);
            }
        } while (len != -1);
        writer.write("</root>");

        // now test if xml input start with <?xml
        String xml = writer.toString();
        String searchString = XML_ROOT_DEFINITION + "<?xml ";
        if (xml.startsWith(searchString) == true) {
            // now remove the surrounding root element
            xml = xml.substring(XML_ROOT_DEFINITION.length(), xml.length() - 7);
            removeRoot = false;
        }

        reader = new StringReader(xml);

        InputSource input = new InputSource(reader);

        DOMBuilder builder = new DOMBuilder();
        builder.startDocument();
        builder.startElement("", "root", "root", XMLUtils.EMPTY_ATTRIBUTES);

        IncludeXMLConsumer filter = new IncludeXMLConsumer(builder, builder);
        parser.parse(input, filter);

        builder.endElement("", "root", "root");
        builder.endDocument();

        // Create Document Fragment, remove <root>
        final Document doc = builder.getDocument();
        frag = doc.createDocumentFragment();
        final Node root = doc.getDocumentElement().getFirstChild();
        root.normalize();
        if (removeRoot == false) {
            root.getParentNode().removeChild(root);
            frag.appendChild(root);
        } else {
            Node child;
            while (root.hasChildNodes() == true) {
                child = root.getFirstChild();
                root.removeChild(child);
                frag.appendChild(child);
            }
        }
    } catch (SAXException sax) {
        throw new ProcessingException("SAXException: " + sax, sax);
    } catch (IOException ioe) {
        throw new ProcessingException("IOException: " + ioe, ioe);
    }
    return frag;
}

From source file:org.apache.cocoon.xml.dom.DOMUtil.java

/**
 * Create a parameter object from xml./*from   w  w w  . j  a v  a2  s.c o  m*/
 * The xml is flat and consists of elements which all have exactly one text node:
 * <parone>value_one<parone>
 * <partwo>value_two<partwo>
 * A parameter can occur more than once with different values.
 * If <CODE>source</CODE> is not specified a new paramter object is created
 * otherwise the parameters are added to source.
 */
public static SourceParameters createParameters(Node fragment, SourceParameters source) {
    SourceParameters par = (source == null ? new SourceParameters() : source);
    if (fragment != null) {
        NodeList childs = fragment.getChildNodes();
        if (childs != null) {
            Node current;
            for (int i = 0; i < childs.getLength(); i++) {
                current = childs.item(i);

                // only element nodes
                if (current.getNodeType() == Node.ELEMENT_NODE) {
                    current.normalize();
                    NodeList valueChilds = current.getChildNodes();
                    String key;
                    StringBuffer valueBuffer;
                    String value;

                    key = current.getNodeName();
                    valueBuffer = new StringBuffer();
                    for (int m = 0; m < valueChilds.getLength(); m++) {
                        current = valueChilds.item(m); // attention: current is reused here!
                        if (current.getNodeType() == Node.TEXT_NODE) { // only text nodes
                            if (valueBuffer.length() > 0)
                                valueBuffer.append(' ');
                            valueBuffer.append(current.getNodeValue());
                        }
                    }
                    value = valueBuffer.toString().trim();
                    if (key != null && value.length() > 0) {
                        par.setParameter(key, value);
                    }
                }
            }
        }
    }
    return par;
}

From source file:org.kmallan.azureus.rssfeed.Scheduler.java

private static String getText(Node node) {
    StringBuffer sb = new StringBuffer();
    node.normalize();
    NodeList children = node.getChildNodes();
    int childrenLen = children.getLength(), type;

    for (int iLoop = 0; iLoop < childrenLen; iLoop++) {
        Node child = children.item(iLoop);
        type = child.getNodeType();//  ww w.  j  av  a  2 s . co  m
        if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) {
            sb.append(child.getNodeValue());
            sb.append(" ");
        }
    }
    return sb.toString().trim();
}

From source file:org.kuali.rice.kns.workflow.attribute.KualiXmlAttributeHelper.java

/**
 * This method overrides the super class and modifies the XML that it operates on to put the name and the title in the place
 * where the super class expects to see them, overwriting the original title in the XML.
 *
 * @see org.kuali.rice.kew.rule.xmlrouting.StandardGenericXMLRuleAttribute#getConfigXML()
 *///from   ww  w . j a v  a  2s .  co  m

public Element processConfigXML(Element root, String[] xpathExpressionElements) {

    NodeList fields = root.getElementsByTagName("fieldDef");
    Element theTag = null;
    String docContent = "";

    /**
     * This section will check to see if document content has been defined in the configXML for the document type, by running an
     * XPath. If this is an empty list the xpath expression in the fieldDef is used to define the xml document content that is
     * added to the configXML. The xmldocument content is of this form, when in the document configXML. <xmlDocumentContent>
     * <org.kuali.rice.krad.bo.SourceAccountingLine> <amount> <value>%totaldollarAmount%</value> </amount>
     * </org.kuali.rice.krad.bo.SourceAccountingLine> </xmlDocumentContent> This class generates this on the fly, by creating an XML
     * element for each term in the XPath expression. When this doesn't apply XML can be coded in the configXML for the
     * ruleAttribute.
     *
     * @see org.kuali.rice.kew.plugin.attributes.WorkflowAttribute#getDocContent()
     */

    org.w3c.dom.Document xmlDoc = null;
    if (!xmlDocumentContentExists(root)) { // XML Document content is given because the xpath is non standard
        fields = root.getElementsByTagName("fieldDef");
        xmlDoc = root.getOwnerDocument();
    }
    for (int i = 0; i < fields.getLength(); i++) { // loop over each fieldDef
        String name = null;
        if (!xmlDocumentContentExists(root)) {
            theTag = (Element) fields.item(i);

            /*
             * Even though there may be multiple xpath test, for example one for source lines and one for target lines, the
             * xmlDocumentContent only needs one, since it is used for formatting. The first one is arbitrarily selected, since
             * they are virtually equivalent in structure, most of the time.
             */

            List<String> xPathTerms = getXPathTerms(theTag);
            if (xPathTerms.size() != 0) {
                Node iterNode = xmlDoc.createElement("xmlDocumentContent");

                xmlDoc.normalize();

                iterNode.normalize();

                /*
                 * Since this method is run once per attribute and there may be multiple fieldDefs, the first fieldDef is used
                 * to create the configXML.
                 */
                for (int j = 0; j < xPathTerms.size(); j++) {// build the configXML based on the Xpath
                    // TODO - Fix the document content element generation
                    iterNode.appendChild(xmlDoc.createElement(xPathTerms.get(j)));
                    xmlDoc.normalize();

                    iterNode = iterNode.getFirstChild();
                    iterNode.normalize();

                }
                iterNode.setTextContent("%" + xPathTerms.get(xPathTerms.size() - 1) + "%");
                root.appendChild(iterNode);
            }
        }
        theTag = (Element) fields.item(i);
        // check to see if a values finder is being used to set valid values for a field
        NodeList displayTagElements = theTag.getElementsByTagName("display");
        if (displayTagElements.getLength() == 1) {
            Element displayTag = (Element) displayTagElements.item(0);
            List valuesElementsToAdd = new ArrayList();
            for (int w = 0; w < displayTag.getChildNodes().getLength(); w++) {
                Node displayTagChildNode = (Node) displayTag.getChildNodes().item(w);
                if ((displayTagChildNode != null) && ("values".equals(displayTagChildNode.getNodeName()))) {
                    if (displayTagChildNode.getChildNodes().getLength() > 0) {
                        String valuesNodeText = displayTagChildNode.getFirstChild().getNodeValue();
                        String potentialClassName = getPotentialKualiClassName(valuesNodeText,
                                KUALI_VALUES_FINDER_REFERENCE_PREFIX, KUALI_VALUES_FINDER_REFERENCE_SUFFIX);
                        if (StringUtils.isNotBlank(potentialClassName)) {
                            try {
                                Class finderClass = Class.forName((String) potentialClassName);
                                KeyValuesFinder finder = (KeyValuesFinder) finderClass.newInstance();
                                NamedNodeMap valuesNodeAttributes = displayTagChildNode.getAttributes();
                                Node potentialSelectedAttribute = (valuesNodeAttributes != null)
                                        ? valuesNodeAttributes.getNamedItem("selected")
                                        : null;
                                for (Iterator iter = finder.getKeyValues().iterator(); iter.hasNext();) {
                                    KeyValue keyValue = (KeyValue) iter.next();
                                    Element newValuesElement = root.getOwnerDocument().createElement("values");
                                    newValuesElement.appendChild(
                                            root.getOwnerDocument().createTextNode(keyValue.getKey()));
                                    // newValuesElement.setNodeValue(KeyValue.getKey().toString());
                                    newValuesElement.setAttribute("title", keyValue.getValue());
                                    if (potentialSelectedAttribute != null) {
                                        newValuesElement.setAttribute("selected",
                                                potentialSelectedAttribute.getNodeValue());
                                    }
                                    valuesElementsToAdd.add(newValuesElement);
                                }
                            } catch (ClassNotFoundException cnfe) {
                                String errorMessage = "Caught an exception trying to find class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, cnfe);
                                throw new RuntimeException(errorMessage, cnfe);
                            } catch (InstantiationException ie) {
                                String errorMessage = "Caught an exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, ie);
                                throw new RuntimeException(errorMessage, ie);
                            } catch (IllegalAccessException iae) {
                                String errorMessage = "Caught an access exception trying to instantiate class '"
                                        + potentialClassName + "'";
                                LOG.error(errorMessage, iae);
                                throw new RuntimeException(errorMessage, iae);
                            }
                        } else {
                            valuesElementsToAdd.add(displayTagChildNode.cloneNode(true));
                        }
                        displayTag.removeChild(displayTagChildNode);
                    }
                }
            }
            for (Iterator iter = valuesElementsToAdd.iterator(); iter.hasNext();) {
                Element valuesElementToAdd = (Element) iter.next();
                displayTag.appendChild(valuesElementToAdd);
            }
        }
        if ((xpathExpressionElements != null) && (xpathExpressionElements.length > 0)) {
            NodeList fieldEvaluationElements = theTag.getElementsByTagName("fieldEvaluation");
            if (fieldEvaluationElements.getLength() == 1) {
                Element fieldEvaluationTag = (Element) fieldEvaluationElements.item(0);
                List tagsToAdd = new ArrayList();
                for (int w = 0; w < fieldEvaluationTag.getChildNodes().getLength(); w++) {
                    Node fieldEvaluationChildNode = (Node) fieldEvaluationTag.getChildNodes().item(w);
                    Element newTagToAdd = null;
                    if ((fieldEvaluationChildNode != null)
                            && ("xpathexpression".equals(fieldEvaluationChildNode.getNodeName()))) {
                        newTagToAdd = root.getOwnerDocument().createElement("xpathexpression");
                        newTagToAdd.appendChild(root.getOwnerDocument()
                                .createTextNode(generateNewXpathExpression(
                                        fieldEvaluationChildNode.getFirstChild().getNodeValue(),
                                        xpathExpressionElements)));
                        tagsToAdd.add(newTagToAdd);
                        fieldEvaluationTag.removeChild(fieldEvaluationChildNode);
                    }
                }
                for (Iterator iter = tagsToAdd.iterator(); iter.hasNext();) {
                    Element elementToAdd = (Element) iter.next();
                    fieldEvaluationTag.appendChild(elementToAdd);
                }
            }
        }
        theTag.setAttribute("title", getBusinessObjectTitle(theTag));

    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(XmlJotter.jotNode(root));
        StringWriter xmlBuffer = new StringWriter();
        try {

            root.normalize();
            Source source = new DOMSource(root);
            Result result = new StreamResult(xmlBuffer);
            TransformerFactory.newInstance().newTransformer().transform(source, result);
        } catch (Exception e) {
            LOG.debug(" Exception when printing debug XML output " + e);
        }
        LOG.debug(xmlBuffer.getBuffer());
    }

    return root;
}

From source file:org.rippleosi.patient.contacts.search.SCCISContactHeadlineTransformer.java

@Override
public List<ContactHeadline> transform(Node xml) {

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();

    List<ContactHeadline> contactList = new ArrayList<ContactHeadline>();

    try {//from   w w w. j a  v a  2s  . co m
        xml.normalize();
        // Retrieve contacts from Carers section of XML
        NodeList nodeSet = (NodeList) xpath.evaluate("/LCR/Carers/List/RelatedPerson", xml,
                XPathConstants.NODESET);
        for (int i = 0; i < nodeSet.getLength(); i++) {
            ContactHeadline contact = new ContactHeadline();
            contact.setSource("SC-CIS");

            Node node = nodeSet.item(i);
            String sourceId = (String) xpath.evaluate("identifier/value/@value", node, XPathConstants.STRING);
            String name = (String) xpath.evaluate("name/text/@value", node, XPathConstants.STRING);

            contact.setSourceId(sourceId);
            contact.setName(name);
            contactList.add(contact);
        }

        // Retrieve contacts from Allocations section of the XML
        nodeSet = (NodeList) xpath.evaluate("/LCR/Allocations/List/Practitioner", xml, XPathConstants.NODESET);

        for (int i = 0; i < nodeSet.getLength(); i++) {
            ContactHeadline contact = new ContactHeadline();
            contact.setSource("SC-CIS");

            Node node = nodeSet.item(i);
            String sourceId = (String) xpath.evaluate("identifier/value/@value", node, XPathConstants.STRING);
            String name = (String) xpath.evaluate("name/text/@value", node, XPathConstants.STRING);

            contact.setSourceId(sourceId);
            contact.setName(name);
            contactList.add(contact);
        }

    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return contactList;
}

From source file:org.rippleosi.patient.contacts.search.SCCISContactSummaryTransformer.java

@Override
public List<ContactSummary> transform(Node xml) {

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();

    List<ContactSummary> contactList = new ArrayList<ContactSummary>();

    try {//w  w w  . j  av  a2 s.c o m
        xml.normalize();
        // Retrieve contacts from Carers section of XML
        NodeList nodeSet = (NodeList) xpath.evaluate("/LCR/Carers/List/RelatedPerson", xml,
                XPathConstants.NODESET);

        for (int i = 0; i < nodeSet.getLength(); i++) {
            ContactSummary contact = new ContactSummary();
            contact.setSource("SC-CIS");

            Node node = nodeSet.item(i);
            String sourceId = (String) xpath.evaluate("identifier/value/@value", node, XPathConstants.STRING);
            String name = (String) xpath.evaluate("name/text/@value", node, XPathConstants.STRING);
            String relationshipTeam = (String) xpath.evaluate("relationship/coding/display/@value", node,
                    XPathConstants.STRING);

            contact.setSourceId(sourceId);
            contact.setName(name);
            contact.setRelationship(relationshipTeam);
            contactList.add(contact);
        }

        // Retrieve contacts from Allocations section of the XML
        nodeSet = (NodeList) xpath.evaluate("/LCR/Allocations/List/Practitioner", xml, XPathConstants.NODESET);

        for (int i = 0; i < nodeSet.getLength(); i++) {
            ContactSummary contact = new ContactSummary();
            contact.setSource("SC-CIS");

            Node node = nodeSet.item(i);
            String sourceId = (String) xpath.evaluate("identifier/value/@value", node, XPathConstants.STRING);
            String name = (String) xpath.evaluate("name/text/@value", node, XPathConstants.STRING);
            String relationshipTeam = (String) xpath.evaluate("practitionerRole/role/coding/display/@value",
                    node, XPathConstants.STRING);

            contact.setSourceId(sourceId);
            contact.setName(name);
            contact.setRelationship(relationshipTeam);

            contactList.add(contact);
        }

    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return contactList;
}

From source file:sernet.gs.scraper.ZIPGSSource.java

private Node parseDocument(InputStream inputstream, String encoding)
        throws TransformerConfigurationException, IOException, SAXException {

    InputStreamReader reader = new InputStreamReader(inputstream, encoding);
    BufferedReader buffRead = new BufferedReader(reader);

    SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler th = stf.newTransformerHandler();
    DOMResult dr = new DOMResult();
    th.setResult(dr);/*w w  w  .j  a v a  2 s .  c o m*/
    Parser parser = new Parser();
    parser.setContentHandler(th);
    parser.parse(new InputSource(buffRead));
    Node domRootNode = dr.getNode();
    domRootNode.normalize();

    buffRead.close();
    reader.close();
    inputstream.close();

    return domRootNode;

}