Java Code Examples for org.w3c.dom.NamedNodeMap#getLength()

The following examples show how to use org.w3c.dom.NamedNodeMap#getLength() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JFIFMarkerSegment.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
JFIFThumbUncompressed(Node node, String name)
    throws IIOInvalidTreeException {

    thumbWidth = 0;
    thumbHeight = 0;
    this.name = name;
    NamedNodeMap attrs = node.getAttributes();
    int count = attrs.getLength();
    if (count > 2) {
        throw new IIOInvalidTreeException
            (name +" node cannot have > 2 attributes", node);
    }
    if (count != 0) {
        int value = getAttributeValue(node, attrs, "thumbWidth",
                                      0, 255, false);
        thumbWidth = (value != -1) ? value : thumbWidth;
        value = getAttributeValue(node, attrs, "thumbHeight",
                                  0, 255, false);
        thumbHeight = (value != -1) ? value : thumbHeight;
    }
}
 
Example 2
Source File: JavaActions.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void addDebugVMArgs(Element java, Document ownerDocument) {
    //Add fork="true" if not alredy there
    NamedNodeMap attrs = java.getAttributes();
    boolean found = false;
    for (int i=0; i<attrs.getLength(); i++) {
        Attr attr = (Attr) attrs.item(i);
        if ("fork".equals(attr.getName())) {        //NOI18N
            String value = attr.getValue();
            if ("on".equalsIgnoreCase (value) ||    //NOI18N
                "true".equalsIgnoreCase(value) ||   //NOI18N
                "yes".equalsIgnoreCase(value)) {    //NOI18N
                found = true;
            }
            break;
        }
    }
    if (!found) {
        java.setAttribute("fork", "true");  //NOI18N
    }
    for (int i = 0; i < DEBUG_VM_ARGS.length; i++) {
        Element jvmarg = ownerDocument.createElement("jvmarg"); // NOI18N
        jvmarg.setAttribute("value", DEBUG_VM_ARGS[i]); // NOI18N
        java.appendChild(jvmarg);
    }
}
 
Example 3
Source File: CanonicalizerPhysical.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Attr[]s to be output for the given element.
 * <br>
 * The code of this method is a copy of {@link #handleAttributes(Element,
 * NameSpaceSymbTable)},
 * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
 * So if the element in question isRoot of c14n, it's parent is not in the
 * node set, as well as all other ancestors.
 *
 * @param element
 * @param ns
 * @return the Attr[]s to be output
 * @throws CanonicalizationException
 */
@Override
protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
    throws CanonicalizationException {
    if (!element.hasAttributes()) {
        return null;
    }

    // result will contain all the attrs declared directly on that element
    final SortedSet<Attr> result = this.result;
    result.clear();

    if (element.hasAttributes()) {
        NamedNodeMap attrs = element.getAttributes();
        int attrsLength = attrs.getLength();

        for (int i = 0; i < attrsLength; i++) {
            Attr attribute = (Attr) attrs.item(i);
            result.add(attribute);
        }
    }

    return result.iterator();
}
 
Example 4
Source File: DOMXPathTransform.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void unmarshalParams(Element paramsElem) {
    String xPath = paramsElem.getFirstChild().getNodeValue();
    // create a Map of namespace prefixes
    NamedNodeMap attributes = paramsElem.getAttributes();
    if (attributes != null) {
        int length = attributes.getLength();
        Map<String, String> namespaceMap =
            new HashMap<String, String>(length);
        for (int i = 0; i < length; i++) {
            Attr attr = (Attr)attributes.item(i);
            String prefix = attr.getPrefix();
            if (prefix != null && prefix.equals("xmlns")) {
                namespaceMap.put(attr.getLocalName(), attr.getValue());
            }
        }
        this.params = new XPathFilterParameterSpec(xPath, namespaceMap);
    } else {
        this.params = new XPathFilterParameterSpec(xPath);
    }
}
 
Example 5
Source File: DomPostInitAction.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    Set<String> declaredPrefixes = new HashSet<String>();
    for( Node n=node; n!=null && n.getNodeType()==Node.ELEMENT_NODE; n=n.getParentNode() ) {
        NamedNodeMap atts = n.getAttributes();
        if(atts==null)      continue; // broken DOM. but be graceful.
        for( int i=0; i<atts.getLength(); i++ ) {
            Attr a = (Attr)atts.item(i);
            String nsUri = a.getNamespaceURI();
            if(nsUri==null || !nsUri.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI))
                continue;   // not a namespace declaration
            String prefix = a.getLocalName();
            if(prefix==null)
                continue;   // broken DOM. skip to be safe
            if(prefix.equals("xmlns")) {
                prefix = "";
            }
            String value = a.getValue();
            if(value==null)
                continue;   // broken DOM. skip to be safe
            if(declaredPrefixes.add(prefix)) {
                serializer.addInscopeBinding(value,prefix);
            }
        }
    }
}
 
Example 6
Source File: DOMUtil.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Replaces ${property[:default value]} references in all attributes
 * and text nodes of supplied node.  If the property is not defined neither in the
 * given Properties instance nor in System.getProperty and no
 * default value is provided, a runtime exception is thrown.
 *
 * @param node DOM node to walk for substitutions
 * @param properties the Properties instance from which a value can be looked up
 */
public static void substituteProperties(Node node, Properties properties) {
  // loop through child nodes
  Node child;
  Node next = node.getFirstChild();
  while ((child = next) != null) {

    // set next before we change anything
    next = child.getNextSibling();

    // handle child by node type
    if (child.getNodeType() == Node.TEXT_NODE) {
      child.setNodeValue(PropertiesUtil.substituteProperty(child.getNodeValue(), properties));
    } else if (child.getNodeType() == Node.ELEMENT_NODE) {
      // handle child elements with recursive call
      NamedNodeMap attributes = child.getAttributes();
      for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        attribute.setNodeValue(PropertiesUtil.substituteProperty(attribute.getNodeValue(), properties));
      }
      substituteProperties(child, properties);
    }
  }
}
 
Example 7
Source File: NodeUtils.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
static Node duplicateNode(Document document, Node node) {
    Node newNode;
    if (node.getNamespaceURI() != null) {
        newNode = document.createElementNS(node.getNamespaceURI(), node.getLocalName());
    } else {
        newNode = document.createElement(node.getNodeName());
    }

    // copy the attributes
    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0 ; i < attributes.getLength(); i++) {
        Attr attr = (Attr) attributes.item(i);

        Attr newAttr;
        if (attr.getNamespaceURI() != null) {
            newAttr = document.createAttributeNS(attr.getNamespaceURI(), attr.getLocalName());
            newNode.getAttributes().setNamedItemNS(newAttr);
        } else {
            newAttr = document.createAttribute(attr.getName());
            newNode.getAttributes().setNamedItem(newAttr);
        }

        newAttr.setValue(attr.getValue());
    }

    // then duplicate the sub-nodes.
    NodeList children = node.getChildNodes();
    for (int i = 0 ; i < children.getLength() ; i++) {
        Node child = children.item(i);
        if (child.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        Node duplicatedChild = duplicateNode(document, child);
        newNode.appendChild(duplicatedChild);
    }

    return newNode;
}
 
Example 8
Source File: Xml.java    From RADL with Apache License 2.0 5 votes vote down vote up
public static Iterable<Node> getAttributes(Node node) {
  Collection<Node> result = new ArrayList<>();
  NamedNodeMap attributes = node.getAttributes();
  for (int i = 0; i < attributes.getLength(); i++) {
    Node attribute = attributes.item(i);
    if (!isNamespaceAttribute(attribute)) {
      result.add(attribute);
    }
  }
  return result;
}
 
Example 9
Source File: JAXPPrefixResolver.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Given a prefix and a Context Node, get the corresponding namespace.
 * Warning: This will not work correctly if namespaceContext
 * is an attribute node.
 * @param prefix Prefix to resolve.
 * @param namespaceContext Node from which to start searching for a
 * xmlns attribute that binds a prefix to a namespace.
 * @return Namespace that prefix resolves to, or null if prefix
 * is not bound.
 */
public String getNamespaceForPrefix(String prefix,
                                  org.w3c.dom.Node namespaceContext) {
    Node parent = namespaceContext;
    String namespace = null;

    if (prefix.equals("xml")) {
        namespace = S_XMLNAMESPACEURI;
    } else {
        int type;

        while ((null != parent) && (null == namespace)
            && (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
                || (type == Node.ENTITY_REFERENCE_NODE))) {

            if (type == Node.ELEMENT_NODE) {
                NamedNodeMap nnm = parent.getAttributes();

                for (int i = 0; i < nnm.getLength(); i++) {
                    Node attr = nnm.item(i);
                    String aname = attr.getNodeName();
                    boolean isPrefix = aname.startsWith("xmlns:");

                    if (isPrefix || aname.equals("xmlns")) {
                        int index = aname.indexOf(':');
                        String p =isPrefix ?aname.substring(index + 1) :"";

                        if (p.equals(prefix)) {
                            namespace = attr.getNodeValue();
                            break;
                        }
                    }
                }
            }

            parent = parent.getParentNode();
        }
    }
    return namespace;
}
 
Example 10
Source File: XSDocumentInfo.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Initialize namespace support by collecting all of the namespace
 * declarations in the root's ancestors. This is necessary to
 * support schemas fragments, i.e. schemas embedded in other
 * documents. See,
 *
 * https://jaxp.dev.java.net/issues/show_bug.cgi?id=43
 *
 * Requires the DOM to be created with namespace support enabled.
 */
private void initNamespaceSupport(Element schemaRoot) {
    fNamespaceSupport = new SchemaNamespaceSupport();
    fNamespaceSupport.reset();

    Node parent = schemaRoot.getParentNode();
    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE
            && !parent.getNodeName().equals("DOCUMENT_NODE"))
    {
        Element eparent = (Element) parent;
        NamedNodeMap map = eparent.getAttributes();
        int length = (map != null) ? map.getLength() : 0;
        for (int i = 0; i < length; i++) {
            Attr attr = (Attr) map.item(i);
            String uri = attr.getNamespaceURI();

            // Check if attribute is an ns decl -- requires ns support
            if (uri != null && uri.equals("http://www.w3.org/2000/xmlns/")) {
                String prefix = attr.getLocalName().intern();
                if (prefix == "xmlns") prefix = "";
                // Declare prefix if not set -- moving upwards
                if (fNamespaceSupport.getURI(prefix) == null) {
                    fNamespaceSupport.declarePrefix(prefix,
                            attr.getValue().intern());
                }
            }
        }
        parent = parent.getParentNode();
    }
}
 
Example 11
Source File: CustomDifferenceListener.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Converts the XMLUnit {@link NamedNodeMap} into a map of {@link QName} to {@link Node},
 * <em>excluding</em> {@code xsi:type} attributes.
 */
private Map<QName, Node> createAttributesMapExcludingXsiType(NamedNodeMap attributes) {
  Map<QName, Node> attributesMap = Maps.newHashMap();
  for (int i = 0; i < attributes.getLength(); i++) {
    Node item = attributes.item(i);
    String itemNamespace = getNamespaceURI(item);
    String localName = item.getLocalName();
    if (!("http://www.w3.org/2001/XMLSchema-instance".equals(itemNamespace)
        && "type".equals(localName))) {
      attributesMap.put(new QName(itemNamespace, item.getLocalName()), item);
    }
  }
  return attributesMap;
}
 
Example 12
Source File: DTMNodeProxy.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
     * DOM Level 3
     * Look up the namespace URI associated to the given prefix, starting from this node.
     * Use lookupNamespaceURI(null) to lookup the default namespace
     *
     * @param namespaceURI
     * @return th URI for the namespace
     * @since DOM Level 3
     */
    @Override
    public String lookupNamespaceURI(String specifiedPrefix) {
        short type = this.getNodeType();
        switch (type) {
        case Node.ELEMENT_NODE : {

                String namespace = this.getNamespaceURI();
                String prefix = this.getPrefix();
                if (namespace !=null) {
                    // REVISIT: is it possible that prefix is empty string?
                    if (specifiedPrefix== null && prefix==specifiedPrefix) {
                        // looking for default namespace
                        return namespace;
                    } else if (prefix != null && prefix.equals(specifiedPrefix)) {
                        // non default namespace
                        return namespace;
                    }
                }
                if (this.hasAttributes()) {
                    NamedNodeMap map = this.getAttributes();
                    int length = map.getLength();
                    for (int i=0;i<length;i++) {
                        Node attr = map.item(i);
                        String attrPrefix = attr.getPrefix();
                        String value = attr.getNodeValue();
                        namespace = attr.getNamespaceURI();
                        if (namespace !=null && namespace.equals("http://www.w3.org/2000/xmlns/")) {
                            // at this point we are dealing with DOM Level 2 nodes only
                            if (specifiedPrefix == null &&
                                attr.getNodeName().equals("xmlns")) {
                                // default namespace
                                return value;
                            } else if (attrPrefix !=null &&
                                       attrPrefix.equals("xmlns") &&
                                       attr.getLocalName().equals(specifiedPrefix)) {
                 // non default namespace
                                return value;
                            }
                        }
                    }
                }
                /*
                NodeImpl ancestor = (NodeImpl)getElementAncestor(this);
                if (ancestor != null) {
                    return ancestor.lookupNamespaceURI(specifiedPrefix);
                }
                */

                return null;


            }
/*
        case Node.DOCUMENT_NODE : {
                return((NodeImpl)((Document)this).getDocumentElement()).lookupNamespaceURI(specifiedPrefix) ;
            }
*/
        case Node.ENTITY_NODE :
        case Node.NOTATION_NODE:
        case Node.DOCUMENT_FRAGMENT_NODE:
        case Node.DOCUMENT_TYPE_NODE:
            // type is unknown
            return null;
        case Node.ATTRIBUTE_NODE:{
                if (this.getOwnerElement().getNodeType() == Node.ELEMENT_NODE) {
                    return getOwnerElement().lookupNamespaceURI(specifiedPrefix);

                }
                return null;
            }
        default:{
           /*
                NodeImpl ancestor = (NodeImpl)getElementAncestor(this);
                if (ancestor != null) {
                    return ancestor.lookupNamespaceURI(specifiedPrefix);
                }
             */
                return null;
            }

        }
    }
 
Example 13
Source File: JFIFMarkerSegment.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Updates the data in this object from the given DOM Node tree.
 * If fromScratch is true, this object is being constructed.
 * Otherwise an existing object is being modified.
 * Throws an IIOInvalidTreeException if the tree is invalid in
 * any way.
 */
void updateFromNativeNode(Node node, boolean fromScratch)
    throws IIOInvalidTreeException {
    // none of the attributes are required
    NamedNodeMap attrs = node.getAttributes();
    if (attrs.getLength() > 0) {
        int value = getAttributeValue(node, attrs, "majorVersion",
                                      0, 255, false);
        majorVersion = (value != -1) ? value : majorVersion;
        value = getAttributeValue(node, attrs, "minorVersion",
                                  0, 255, false);
        minorVersion = (value != -1) ? value : minorVersion;
        value = getAttributeValue(node, attrs, "resUnits", 0, 2, false);
        resUnits = (value != -1) ? value : resUnits;
        value = getAttributeValue(node, attrs, "Xdensity", 1, 65535, false);
        Xdensity = (value != -1) ? value : Xdensity;
        value = getAttributeValue(node, attrs, "Ydensity", 1, 65535, false);
        Ydensity = (value != -1) ? value : Ydensity;
        value = getAttributeValue(node, attrs, "thumbWidth", 0, 255, false);
        thumbWidth = (value != -1) ? value : thumbWidth;
        value = getAttributeValue(node, attrs, "thumbHeight", 0, 255, false);
        thumbHeight = (value != -1) ? value : thumbHeight;
    }
    if (node.hasChildNodes()) {
        NodeList children = node.getChildNodes();
        int count = children.getLength();
        if (count > 2) {
            throw new IIOInvalidTreeException
                ("app0JFIF node cannot have > 2 children", node);
        }
        for (int i = 0; i < count; i++) {
            Node child = children.item(i);
            String name = child.getNodeName();
            if (name.equals("JFXX")) {
                if ((!extSegments.isEmpty()) && fromScratch) {
                    throw new IIOInvalidTreeException
                        ("app0JFIF node cannot have > 1 JFXX node", node);
                }
                NodeList exts = child.getChildNodes();
                int extCount = exts.getLength();
                for (int j = 0; j < extCount; j++) {
                    Node ext = exts.item(j);
                    extSegments.add(new JFIFExtensionMarkerSegment(ext));
                }
            }
            if (name.equals("app2ICC")) {
                if ((iccSegment != null) && fromScratch) {
                    throw new IIOInvalidTreeException
                        ("> 1 ICC APP2 Marker Segment not supported", node);
                }
                iccSegment = new ICCMarkerSegment(child);
            }
        }
    }
}
 
Example 14
Source File: XMLUtils.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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.
 */
public static boolean protectAgainstWrappingAttack(
    Node startNode, Element knownElement, String value
) {
    Node startParent = startNode.getParentNode();
    Node processedNode = null;

    String id = value.trim();
    if (!id.isEmpty() && 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.log(java.util.logging.Level.FINE, "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;
}
 
Example 15
Source File: HtmlUtils.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
private static void appendAttributes(StringBuilder builder, DeclarationMap styleMap, Element element, StylesEmbeddingOptions options) {
    if (element.hasAttributes()) {
        NamedNodeMap attributes = element.getAttributes();

        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);

            String name = attribute.getNodeName();
            String value = attribute.getNodeValue();

            switch (name) {
                case "style":
                    // All the styles (inline ones as well) are already accumulated in a style map - do nothing
                    break;

                case "src":
                    if (options.getBaseUrl() != null && StringUtils.equals(element.getTagName(), "img") && !value.startsWith("[")) {
                        value = HttpUtils.resolveRelativeUri(options.getBaseUrl(), value);
                    }
                    //$FALL-THROUGH$

                default:
                    value = value.replace("\n", "&#10;");
                    if (options.isEscapeAgnTags()) {
                        value = AgnTagUtils.escapeAgnTags(value);
                    }
                    builder.append(' ').append(name).append("=\"").append(value).append("\"");
                    break;
            }
        }
    }

    List<Declaration> declarations = styleMap.get(element);

    if (CollectionUtils.isNotEmpty(declarations)) {
        String styles = declarations.stream()
                .map(declaration -> {
                    resolveUris(declaration);
                    return toString(declaration);
                }).collect(Collectors.joining(" "));

        // Hack for IE (See GWUA-2423)
        if (StringUtils.equals(element.getTagName(), "img") && StringUtils.isBlank(element.getAttribute("border"))) {
            final String noBorder = "border:none;";
            final String noBottomBorder = "border-bottom-style:none;";
            final String noLeftBorder = "border-left-style:none;";
            final String noRightBorder = "border-right-style:none;";
            final String noTopBorder = "border-top-style:none;";

            final String s = styles.replaceAll("\\s+", "");

            if (s.contains(noBorder) || (s.contains(noBottomBorder) && s.contains(noLeftBorder) && s.contains(noRightBorder) && s.contains(noTopBorder))) {
                if (!s.contains(noBorder)) {
                    styles += " border: none;";
                }
                builder.append(" border=\"0\"");
            }
        }

        builder.append(" style=\"").append(styles).append('\"');
    }
}
 
Example 16
Source File: XMLUtils.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("fallthrough")
private static void getSetRec(final Node rootNode, final Set<Node> result,
                            final Node exclude, final boolean com) {
    if (rootNode == exclude) {
        return;
    }
    switch (rootNode.getNodeType()) {
    case Node.ELEMENT_NODE:
        result.add(rootNode);
        Element el = (Element)rootNode;
        if (el.hasAttributes()) {
            NamedNodeMap nl = el.getAttributes();
            for (int i = 0;i < nl.getLength(); i++) {
                result.add(nl.item(i));
            }
        }
        //no return keep working
    case Node.DOCUMENT_NODE:
        for (Node r = rootNode.getFirstChild(); r != null; r = r.getNextSibling()) {
            if (r.getNodeType() == Node.TEXT_NODE) {
                result.add(r);
                while ((r != null) && (r.getNodeType() == Node.TEXT_NODE)) {
                    r = r.getNextSibling();
                }
                if (r == null) {
                    return;
                }
            }
            getSetRec(r, result, exclude, com);
        }
        return;
    case Node.COMMENT_NODE:
        if (com) {
            result.add(rootNode);
        }
        return;
    case Node.DOCUMENT_TYPE_NODE:
        return;
    default:
        result.add(rootNode);
    }
}
 
Example 17
Source File: XMLUtils.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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.
 */
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.log(java.util.logging.Level.FINE, "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;
}
 
Example 18
Source File: XMLUtils.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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.
 */
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.log(java.util.logging.Level.FINE, "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;
}
 
Example 19
Source File: Canonicalizer20010315.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns the Attr[]s to be output for the given element.
 * <br>
 * The code of this method is a copy of {@link #handleAttributes(Element,
 * NameSpaceSymbTable)},
 * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
 * So if the element in question isRoot of c14n, it's parent is not in the
 * node set, as well as all other ancestors.
 *
 * @param element
 * @param ns
 * @return the Attr[]s to be output
 * @throws CanonicalizationException
 */
@Override
protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
    throws CanonicalizationException {
    if (!element.hasAttributes() && !firstCall) {
        return null;
    }
    // result will contain the attrs which have to be output
    final SortedSet<Attr> result = this.result;
    result.clear();

    if (element.hasAttributes()) {
        NamedNodeMap attrs = element.getAttributes();
        int attrsLength = attrs.getLength();

        for (int i = 0; i < attrsLength; i++) {
            Attr attribute = (Attr) attrs.item(i);
            String NUri = attribute.getNamespaceURI();
            String NName = attribute.getLocalName();
            String NValue = attribute.getValue();

            if (!XMLNS_URI.equals(NUri)) {
                //It's not a namespace attr node. Add to the result and continue.
                result.add(attribute);
            } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) {
                //The default mapping for xml must not be output.
                Node n = ns.addMappingAndRender(NName, NValue, attribute);

                if (n != null) {
                    //Render the ns definition
                    result.add((Attr)n);
                    if (C14nHelper.namespaceIsRelative(attribute)) {
                        Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
                        throw new CanonicalizationException(
                            "c14n.Canonicalizer.RelativeNamespace", exArgs
                        );
                    }
                }
            }
        }
    }

    if (firstCall) {
        //It is the first node of the subtree
        //Obtain all the namespaces defined in the parents, and added to the output.
        ns.getUnrenderedNodes(result);
        //output the attributes in the xml namespace.
        xmlattrStack.getXmlnsAttr(result);
        firstCall = false;
    }

    return result.iterator();
}
 
Example 20
Source File: DOM2DTM.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/**
 * Construct a DOM2DTM object from a DOM node.
 *
 * @param mgr The DTMManager who owns this DTM.
 * @param domSource the DOM source that this DTM will wrap.
 * @param dtmIdentity The DTM identity ID for this DTM.
 * @param whiteSpaceFilter The white space filter for this DTM, which may
 *                         be null.
 * @param xstringfactory XMLString factory for creating character content.
 * @param doIndexing true if the caller considers it worth it to use
 *                   indexing schemes.
 */
public DOM2DTM(DTMManager mgr, DOMSource domSource,
               int dtmIdentity, DTMWSFilter whiteSpaceFilter,
               XMLStringFactory xstringfactory,
               boolean doIndexing)
{
  super(mgr, domSource, dtmIdentity, whiteSpaceFilter,
        xstringfactory, doIndexing);

  // Initialize DOM navigation
  m_pos=m_root = domSource.getNode();
  // Initialize DTM navigation
  m_last_parent=m_last_kid=NULL;
  m_last_kid=addNode(m_root, m_last_parent,m_last_kid, NULL);

  // Apparently the domSource root may not actually be the
  // Document node. If it's an Element node, we need to immediately
  // add its attributes. Adapted from nextNode().
  // %REVIEW% Move this logic into addNode and recurse? Cleaner!
  //
  // (If it's an EntityReference node, we're probably scrod. For now
  // I'm just hoping nobody is ever quite that foolish... %REVIEW%)
              //
              // %ISSUE% What about inherited namespaces in this case?
              // Do we need to special-case initialize them into the DTM model?
  if(ELEMENT_NODE == m_root.getNodeType())
  {
    NamedNodeMap attrs=m_root.getAttributes();
    int attrsize=(attrs==null) ? 0 : attrs.getLength();
    if(attrsize>0)
    {
      int attrIndex=NULL; // start with no previous sib
      for(int i=0;i<attrsize;++i)
      {
        // No need to force nodetype in this case;
        // addNode() will take care of switching it from
        // Attr to Namespace if necessary.
        attrIndex=addNode(attrs.item(i),0,attrIndex,NULL);
        m_firstch.setElementAt(DTM.NULL,attrIndex);
      }
      // Terminate list of attrs, and make sure they aren't
      // considered children of the element
      m_nextsib.setElementAt(DTM.NULL,attrIndex);

      // IMPORTANT: This does NOT change m_last_parent or m_last_kid!
    } // if attrs exist
  } //if(ELEMENT_NODE)

  // Initialize DTM-completed status
  m_nodesAreProcessed = false;
}