Example usage for org.w3c.dom NamedNodeMap getLength

List of usage examples for org.w3c.dom NamedNodeMap getLength

Introduction

In this page you can find the example usage for org.w3c.dom NamedNodeMap getLength.

Prototype

public int getLength();

Source Link

Document

The number of nodes in this map.

Usage

From source file:Main.java

public static void stripDuplicateAttributes(Node node, Node parent) {

    // The output depends on the type of the node
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE: {
        Document doc = (Document) node;
        Node child = doc.getFirstChild();
        while (child != null) {
            stripDuplicateAttributes(child, node);
            child = child.getNextSibling();
        }//from   ww  w .  j a v  a  2  s .c om
        break;
    }

    case Node.ELEMENT_NODE: {
        Element elt = (Element) node;
        NamedNodeMap attrs = elt.getAttributes();

        ArrayList nodesToRemove = new ArrayList();
        int nodesToRemoveNum = 0;

        for (int i = 0; i < attrs.getLength(); i++) {
            final Node a = attrs.item(i);

            for (int j = 0; j < attrs.getLength(); j++) {
                final Node b = attrs.item(j);

                //if there are two attributes with same name
                if (i != j && (a.getNodeName().equals(b.getNodeName()))) {
                    nodesToRemove.add(b);
                    nodesToRemoveNum++;
                }
            }
        }

        for (int i = 0; i < nodesToRemoveNum; i++) {
            Attr nodeToDelete = (Attr) nodesToRemove.get(i);
            Element nodeToDeleteParent = (Element) node; // nodeToDelete.getParentNode();
            nodeToDeleteParent.removeAttributeNode(nodeToDelete);
        }

        nodesToRemove.clear();

        Node child = elt.getFirstChild();
        while (child != null) {
            stripDuplicateAttributes(child, node);
            child = child.getNextSibling();
        }

        break;
    }

    default:
        //do nothing
        break;
    }
}

From source file:Main.java

/**
 * This method is a tree-search to help prevent against wrapping attacks. It checks that no other
 * Element than the given "knownElement" argument has an ID attribute that matches the "value"
 * argument, which is the ID value of "knownElement". If this is the case then "false" is returned.
 *///from  w w w  .ja v a 2 s. c o m
public static boolean protectAgainstWrappingAttack(Node startNode, Element knownElement, String value) {
    Node startParent = startNode.getParentNode();
    Node processedNode = null;

    String id = value.trim();
    if (id.charAt(0) == '#') {
        id = id.substring(1);
    }

    while (startNode != null) {
        if (startNode.getNodeType() == Node.ELEMENT_NODE) {
            Element se = (Element) startNode;

            NamedNodeMap attributes = se.getAttributes();
            if (attributes != null) {
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attr = (Attr) attributes.item(i);
                    if (attr.isId() && id.equals(attr.getValue()) && se != knownElement) {
                        //log.debug("Multiple elements with the same 'Id' attribute value!");
                        return false;
                    }
                }
            }
        }

        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }

        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return true;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return true;
}

From source file:Main.java

/**
 * This method is a tree-search to help prevent against wrapping attacks. It checks that no
 * two Elements have ID Attributes that match the "value" argument, if this is the case then
 * "false" is returned. Note that a return value of "true" does not necessarily mean that
 * a matching Element has been found, just that no wrapping attack has been detected.
 *//*from  w  w  w .  ja  v a2  s . com*/
public static boolean protectAgainstWrappingAttack(Node startNode, String value) {
    Node startParent = startNode.getParentNode();
    Node processedNode = null;
    Element foundElement = null;

    String id = value.trim();
    if (id.charAt(0) == '#') {
        id = id.substring(1);
    }

    while (startNode != null) {
        if (startNode.getNodeType() == Node.ELEMENT_NODE) {
            Element se = (Element) startNode;

            NamedNodeMap attributes = se.getAttributes();
            if (attributes != null) {
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attr = (Attr) attributes.item(i);
                    if (attr.isId() && id.equals(attr.getValue())) {
                        if (foundElement == null) {
                            // Continue searching to find duplicates
                            foundElement = attr.getOwnerElement();
                        } else {
                            //log.debug("Multiple elements with the same 'Id' attribute value!");
                            return false;
                        }
                    }
                }
            }
        }

        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }

        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return true;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return true;
}

From source file:org.jasypt.spring31.xml.encryption.EncryptorConfigBeanDefinitionParser.java

private static Class<?> computeConfigClass(final Element element) {

    boolean isSimpleConfig = false;
    boolean isStringConfig = false;
    boolean isEnvironmentConfig = false;
    boolean isStringEnvironmentConfig = false;

    final NamedNodeMap attributesMap = element.getAttributes();
    final int attributesLen = attributesMap.getLength();
    for (int i = 0; i < attributesLen; i++) {
        final Node attribute = attributesMap.item(i);
        final String attributeName = attribute.getNodeName();
        if (!isSimpleConfig && PARAMS_SIMPLE.contains(attributeName)) {
            isSimpleConfig = true;//from www .  j  a  v  a 2 s. com
        }
        if (!isStringConfig && PARAMS_STRING.contains(attributeName)) {
            isStringConfig = true;
        }
        if (!isEnvironmentConfig && PARAMS_ENVIRONMENT.contains(attributeName)) {
            isEnvironmentConfig = true;
        }
        if (!isStringEnvironmentConfig && PARAMS_STRING_ENVIRONMENT.contains(attributeName)) {
            isStringEnvironmentConfig = true;
        }
    }

    if (isStringEnvironmentConfig || (isEnvironmentConfig && isStringConfig)) {
        return EnvironmentStringPBEConfig.class;
    }
    if (isEnvironmentConfig) {
        return EnvironmentPBEConfig.class;
    }
    if (isStringConfig) {
        return SimpleStringPBEConfig.class;
    }
    return SimplePBEConfig.class;

}

From source file:com.evolveum.midpoint.prism.util.PrismUtil.java

private static void fortifyNamespaceDeclarations(Element definitionElement, Element childElement) {
    Document doc = definitionElement.getOwnerDocument();
    NamedNodeMap attributes = childElement.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attr = (Attr) attributes.item(i);
        if (DOMUtil.isNamespaceDefinition(attr)) {
            String prefix = DOMUtil.getNamespaceDeclarationPrefix(attr);
            String namespace = DOMUtil.getNamespaceDeclarationNamespace(attr);
            Element namespaceElement = doc.createElementNS(PrismConstants.A_NAMESPACE.getNamespaceURI(),
                    PrismConstants.A_NAMESPACE.getLocalPart());
            namespaceElement.setAttribute(PrismConstants.A_NAMESPACE_PREFIX, prefix);
            namespaceElement.setAttribute(PrismConstants.A_NAMESPACE_URL, namespace);
            definitionElement.insertBefore(namespaceElement, childElement);
        }/*from   w  ww .  ja  va2s  .  c  om*/
    }
}

From source file:Main.java

/**
 * Print a Node tree recursively.//  w w  w  .j a va  2 s  . c o  m
 * @param node A DOM tree Node
 * @return An xml String representation of the DOM tree.
 */
public static String print(Node node) {
    if (node == null) {
        return null;
    }

    StringBuffer xml = new StringBuffer(100);
    int type = node.getNodeType();

    switch (type) {
    // print element with attributes
    case Node.ELEMENT_NODE: {
        xml.append('<');
        xml.append(node.getNodeName());

        NamedNodeMap attrs = node.getAttributes();
        int length = attrs.getLength();
        ;

        for (int i = 0; i < length; i++) {
            Attr attr = (Attr) attrs.item(i);
            xml.append(' ');
            xml.append(attr.getNodeName());
            xml.append("=\"");

            //xml.append(normalize(attr.getNodeValue()));
            xml.append(attr.getNodeValue());
            xml.append('"');
        }

        xml.append('>');

        NodeList children = node.getChildNodes();

        if (children != null) {
            int len = children.getLength();

            for (int i = 0; i < len; i++) {
                xml.append(print(children.item(i)));
            }
        }

        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        NodeList children = node.getChildNodes();

        if (children != null) {
            int len = children.getLength();

            for (int i = 0; i < len; i++) {
                xml.append(print(children.item(i)));
            }
        }

        break;
    }

    // print cdata sections
    case Node.CDATA_SECTION_NODE: {
        xml.append("<![CDATA[");
        xml.append(node.getNodeValue());
        xml.append("]]>");

        break;
    }

    // print text
    case Node.TEXT_NODE: {
        //xml.append(normalize(node.getNodeValue()));
        xml.append(node.getNodeValue());

        break;
    }

    // print processing instruction
    case Node.PROCESSING_INSTRUCTION_NODE: {
        xml.append("<?");
        xml.append(node.getNodeName());

        String data = node.getNodeValue();

        if ((data != null) && (data.length() > 0)) {
            xml.append(' ');
            xml.append(data);
        }

        xml.append("?>");

        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        xml.append("</");
        xml.append(node.getNodeName());
        xml.append('>');
    }

    return xml.toString();
}

From source file:Main.java

/**
 * Checks whether the expected XML element is contained in the actual
 * element. I.e., every attribute of the expected element must occur in the
 * actual element, with the same value, and all child nodes in the expected
 * element must occur in the actual element; if multiple child nodes with
 * the same name are found in the expected element, the first found
 * identifying attribute in the expected child element is used to identify
 * the child in the actual element./*from   w ww  .j a va 2  s .  com*/
 * 
 * @param expected
 * @param actual
 * @return
 */
public static void assertContains(Element expected, Element actual, String messagePrefix,
        String... identifyingAttributes) {
    if (!expected.getTagName().equals(actual.getTagName())) {
        throw new AssertionError(messagePrefix + "\nExpected tagname differs from actual tagname (expected '"
                + printNodeOnly(expected) + "', found " + printNodeOnly(actual) + ")");
    }

    // Compare attributes
    NamedNodeMap expectedAttributes = expected.getAttributes();
    for (int i = expectedAttributes.getLength() - 1; i >= 0; i--) {
        String expectedAttributeName = expectedAttributes.item(i).getNodeName();
        String expectedAttributeValue = expectedAttributes.item(i).getNodeValue();

        String actualValue = actual.getAttribute(expectedAttributeName);
        if (actualValue == null || actualValue.isEmpty()) {
            throw new AssertionError(messagePrefix + "\nThe attribute '" + expectedAttributeName
                    + "' with value '" + expectedAttributeValue + "' was not found in the result "
                    + printNodeOnly(actual));
        }
        if (!expectedAttributeValue.equals(actualValue)) {
            throw new AssertionError(messagePrefix + "\nThe attribute '" + expectedAttributeName
                    + "' has value '" + actualValue + "' instead of '" + expectedAttributeValue
                    + "' in the result " + printNodeOnly(actual));
        }
    }

    // Compare child elements
    Node child = expected.getFirstChild();
    while (child != null) {
        if (child instanceof Element) {
            assertContainsChildElement((Element) child, actual, messagePrefix, identifyingAttributes);
        }
        child = child.getNextSibling();
    }
}

From source file:no.digipost.api.xml.Marshalling.java

public static void trimNamespaces(final Document doc) {
    NamedNodeMap attributes = doc.getDocumentElement().getAttributes();
    List<Attr> attrsToRemove = new ArrayList<Attr>();
    for (int i = 0; i < attributes.getLength(); i++) {
        if (doc.getElementsByTagNameNS(attributes.item(i).getNodeValue(), "*").getLength() == 0) {
            attrsToRemove.add((Attr) attributes.item(i));
        }//from   w w  w. j a v  a 2  s .com
    }
    for (Attr a : attrsToRemove) {
        doc.getDocumentElement().removeAttributeNode(a);
    }
}

From source file:Main.java

public static HashMap<String, String> getAttributes(Node p_node) throws Exception {

    NamedNodeMap l_nnm = null;
    Node l_n = null;/* w ww . j  av  a  2s  .co  m*/
    String l_an = null;
    String l_av = null;
    HashMap<String, String> l_a = new HashMap<String, String>();

    l_nnm = p_node.getAttributes();
    if (l_nnm != null) {
        for (int l_i = 0; l_i < l_nnm.getLength(); l_i++) {
            l_n = l_nnm.item(l_i);
            l_an = l_n.getNodeName();
            l_av = l_n.getNodeValue();
            l_a.put(l_an, l_av);
        }
    }

    return l_a;
}

From source file:org.jasypt.spring31.xml.encryption.DigesterConfigBeanDefinitionParser.java

private static Class<?> computeConfigClass(final Element element) {

    boolean isSimpleConfig = false;
    boolean isStringConfig = false;
    boolean isEnvironmentConfig = false;
    boolean isStringEnvironmentConfig = false;

    final NamedNodeMap attributesMap = element.getAttributes();
    final int attributesLen = attributesMap.getLength();
    for (int i = 0; i < attributesLen; i++) {
        final Node attribute = attributesMap.item(i);
        final String attributeName = attribute.getNodeName();
        if (!isSimpleConfig && PARAMS_SIMPLE.contains(attributeName)) {
            isSimpleConfig = true;//from   w ww  . ja v a 2s.  co  m
        }
        if (!isStringConfig && PARAMS_STRING.contains(attributeName)) {
            isStringConfig = true;
        }
        if (!isEnvironmentConfig && PARAMS_ENVIRONMENT.contains(attributeName)) {
            isEnvironmentConfig = true;
        }
        if (!isStringEnvironmentConfig && PARAMS_STRING_ENVIRONMENT.contains(attributeName)) {
            isStringEnvironmentConfig = true;
        }
    }

    if (isStringEnvironmentConfig || (isEnvironmentConfig && isStringConfig)) {
        return EnvironmentStringDigesterConfig.class;
    }
    if (isEnvironmentConfig) {
        return EnvironmentDigesterConfig.class;
    }
    if (isStringConfig) {
        return SimpleStringDigesterConfig.class;
    }
    return SimpleDigesterConfig.class;

}