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:de.elbe5.base.data.XmlData.java

public Map<String, String> getAttributes(Node node) {
    Map<String, String> map = new HashMap<>();
    if (node.hasAttributes()) {
        NamedNodeMap attrMap = node.getAttributes();
        for (int i = 0; i < attrMap.getLength(); i++) {
            Node attr = attrMap.item(i);
            map.put(attr.getNodeName(), attr.getNodeValue());
        }//from  w ww .j  ava2  s . c o m
    }
    return map;
}

From source file:com.enonic.esl.xml.XMLTool.java

public static Element renameElement(Element elem, String newName) {
    Document doc = elem.getOwnerDocument();

    // Create an element with the new name
    Element elem2 = doc.createElement(newName);

    // Copy the attributes to the new element
    NamedNodeMap attrs = elem.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr2 = (Attr) doc.importNode(attrs.item(i), true);
        elem2.getAttributes().setNamedItem(attr2);
    }//  w w  w  .  j  a  va2s.  c  om

    // Move all the children
    while (elem.hasChildNodes()) {
        elem2.appendChild(elem.getFirstChild());
    }

    // Replace the old node with the new node
    elem.getParentNode().replaceChild(elem2, elem);

    return elem2;
}

From source file:com.subgraph.vega.impl.scanner.urls.ResponseAnalyzer.java

private void analyzeHtmlElement(IInjectionModuleContext ctx, HttpUriRequest req, IHttpResponse res,
        Element elem) {/*from   w w  w.  java  2s  .  c o  m*/
    boolean remoteScript = false;
    NamedNodeMap attributes = elem.getAttributes();
    final String tag = elem.getTagName().toLowerCase();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node item = attributes.item(i);
        if (item instanceof Attr) {
            String n = ((Attr) item).getName().toLowerCase();
            String v = ((Attr) item).getValue().toLowerCase();
            if (match(tag, "script") && match(n, "src"))
                remoteScript = true;
            if ((v != null) && (match(n, "href", "src", "action", "codebase")
                    || (match(n, "value") && !match(tag, "input")))) {
                if (v.startsWith("vega://"))
                    alert(ctx, "vinfo-url-inject", "URL injection into <" + tag + "> tag", req, res);

                if (v.startsWith("http://vega.invalid/") || v.startsWith("//vega.invalid/")) {
                    if (match(tag, "script", "link"))
                        alert(ctx, "vinfo-url-inject",
                                "URL injection into actively fetched field in tag <" + tag + "> (high risk)",
                                req, res);
                    else if (match(tag, "a"))
                        alert(ctx, "vinfo-url-inject", "URL injection into anchor tag (low risk)", req, res);
                    else
                        alert(ctx, "vinfo-url-inject", "URL injection into tag <" + tag + ">", req, res);
                }

            }

            if ((v != null) && (n.startsWith("on") || n.equals("style"))) {
                checkJavascriptXSS(ctx, req, res, v);
            }

            if (n.contains("vvv"))
                possibleXssAlert(ctx, req, res, n, n.indexOf("vvv"), "xss-inject",
                        "Injected XSS tag into HTML attribute value");

        }
    }

    if (tag.startsWith("vvv"))
        possibleXssAlert(ctx, req, res, tag, 0, "vinfo-xss-inject", "Injected XSS tag into HTML tag name");

    if (tag.equals("style") || (tag.equals("script") && !remoteScript)) {
        String content = elem.getTextContent();
        if (content != null)
            checkJavascriptXSS(ctx, req, res, content);
    }
}

From source file:DOM2SAX.java

/**
 * Writes a node using the given writer.
 * @param node node to serialize/*  w  w  w. j a va 2  s  . com*/
 * @throws SAXException In case of a problem while writing XML
 */
private void writeNode(Node node) throws SAXException {
    if (node == null) {
        return;
    }

    switch (node.getNodeType()) {
    case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE
    case Node.DOCUMENT_FRAGMENT_NODE:
    case Node.DOCUMENT_TYPE_NODE:
    case Node.ENTITY_NODE:
    case Node.ENTITY_REFERENCE_NODE:
    case Node.NOTATION_NODE:
        // These node types are ignored!!!
        break;
    case Node.CDATA_SECTION_NODE:
        final String cdata = node.getNodeValue();
        if (lexicalHandler != null) {
            lexicalHandler.startCDATA();
            contentHandler.characters(cdata.toCharArray(), 0, cdata.length());
            lexicalHandler.endCDATA();
        } else {
            // in the case where there is no lex handler, we still
            // want the text of the cdate to make its way through.
            contentHandler.characters(cdata.toCharArray(), 0, cdata.length());
        }
        break;

    case Node.COMMENT_NODE: // should be handled!!!
        if (lexicalHandler != null) {
            final String value = node.getNodeValue();
            lexicalHandler.comment(value.toCharArray(), 0, value.length());
        }
        break;
    case Node.DOCUMENT_NODE:
        contentHandler.startDocument();
        Node next = node.getFirstChild();
        while (next != null) {
            writeNode(next);
            next = next.getNextSibling();
        }
        contentHandler.endDocument();
        break;

    case Node.ELEMENT_NODE:
        String prefix;
        List pushedPrefixes = new java.util.ArrayList();
        final AttributesImpl attrs = new AttributesImpl();
        final NamedNodeMap map = node.getAttributes();
        final int length = map.getLength();

        // Process all namespace declarations
        for (int i = 0; i < length; i++) {
            final Node attr = map.item(i);
            final String qnameAttr = attr.getNodeName();

            // Ignore everything but NS declarations here
            if (qnameAttr.startsWith(XMLNS_PREFIX)) {
                final String uriAttr = attr.getNodeValue();
                final int colon = qnameAttr.lastIndexOf(':');
                prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING;
                if (startPrefixMapping(prefix, uriAttr)) {
                    pushedPrefixes.add(prefix);
                }
            }
        }

        // Process all other attributes
        for (int i = 0; i < length; i++) {
            final Node attr = map.item(i);
            final String qnameAttr = attr.getNodeName();

            // Ignore NS declarations here
            if (!qnameAttr.startsWith(XMLNS_PREFIX)) {
                final String uriAttr = attr.getNamespaceURI();

                // Uri may be implicitly declared
                if (uriAttr != null) {
                    final int colon = qnameAttr.lastIndexOf(':');
                    prefix = (colon > 0) ? qnameAttr.substring(0, colon) : EMPTYSTRING;
                    if (startPrefixMapping(prefix, uriAttr)) {
                        pushedPrefixes.add(prefix);
                    }
                }

                // Add attribute to list
                attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr), qnameAttr, "CDATA",
                        attr.getNodeValue());
            }
        }

        // Now process the element itself
        final String qname = node.getNodeName();
        final String uri = node.getNamespaceURI();
        final String localName = getLocalName(node);

        // Uri may be implicitly declared
        if (uri != null) {
            final int colon = qname.lastIndexOf(':');
            prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING;
            if (startPrefixMapping(prefix, uri)) {
                pushedPrefixes.add(prefix);
            }
        }

        // Generate SAX event to start element
        contentHandler.startElement(uri, localName, qname, attrs);

        // Traverse all child nodes of the element (if any)
        next = node.getFirstChild();
        while (next != null) {
            writeNode(next);
            next = next.getNextSibling();
        }

        // Generate SAX event to close element
        contentHandler.endElement(uri, localName, qname);

        // Generate endPrefixMapping() for all pushed prefixes
        final int nPushedPrefixes = pushedPrefixes.size();
        for (int i = 0; i < nPushedPrefixes; i++) {
            endPrefixMapping((String) pushedPrefixes.get(i));
        }
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        contentHandler.processingInstruction(node.getNodeName(), node.getNodeValue());
        break;

    case Node.TEXT_NODE:
        final String data = node.getNodeValue();
        contentHandler.characters(data.toCharArray(), 0, data.length());
        break;
    default:
        //nop
    }
}

From source file:org.gvnix.dynamic.configuration.roo.addon.config.XmlDynamicConfiguration.java

/**
 * Create the dynamic properties related to this node attributes.
 * /*  w  w w. j  av a  2s  .c  om*/
 * @param node Node to add to list
 * @param xpath Xpath expression of this node
 * @return Dynamic property list
 */
protected DynPropertyList getPropertyAttributes(Node node, String xpath) {

    DynPropertyList dynProps = new DynPropertyList();

    // Iterate all node attributes, if exists
    NamedNodeMap attrs = node.getAttributes();
    if (attrs != null) {
        for (int j = 0; j < attrs.getLength(); j++) {

            // Get attribute and it name
            Node attr = attrs.item(j);
            String attrName = attr.getNodeName();

            // Create dynamic property, except attribute references
            if (!attrName.equals(REF_ATTRIBUTE_NAME)) {
                dynProps.add(new DynProperty(
                        xpath + XPATH_ARRAY_PREFIX + XPATH_ATTRIBUTE_PREFIX + attrName + XPATH_ARRAY_SUFIX,
                        attr.getNodeValue()));
            }
        }
    }

    return dynProps;
}

From source file:com.nridge.core.base.io.xml.DataTableXML.java

/**
 * Parses an XML DOM element and loads it into a bag/table.
 *
 * @param anElement DOM element.//  w  w  w.jav a 2  s.c o m
 * @throws java.io.IOException I/O related exception.
 */
@Override
public void load(Element anElement) throws IOException {
    Node nodeItem;
    Attr nodeAttr;
    Element nodeElement;
    String nodeName, nodeValue, attrValue;

    attrValue = anElement.getAttribute("name");
    if (StringUtils.isNotEmpty(attrValue))
        mDataTable.setName(attrValue);

    NamedNodeMap namedNodeMap = anElement.getAttributes();
    int attrCount = namedNodeMap.getLength();
    for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) {
        nodeAttr = (Attr) namedNodeMap.item(attrOffset);
        nodeName = nodeAttr.getNodeName();
        nodeValue = nodeAttr.getNodeValue();

        if (StringUtils.isNotEmpty(nodeValue)) {
            if (!StringUtils.equalsIgnoreCase(nodeName, "name"))
                mDataTable.addFeature(nodeName, nodeValue);
        }
    }

    NodeList nodeList = anElement.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        nodeItem = nodeList.item(i);

        if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
            continue;

        nodeName = nodeItem.getNodeName();
        if (nodeName.equalsIgnoreCase("Context")) {
            nodeElement = (Element) nodeItem;
            attrValue = nodeElement.getAttribute("start");
            if (StringUtils.isNumeric(attrValue))
                mContextStart = Integer.parseInt(attrValue);
            attrValue = nodeElement.getAttribute("limit");
            if (StringUtils.isNumeric(attrValue))
                mContextLimit = Integer.parseInt(attrValue);
            attrValue = nodeElement.getAttribute("total");
            if (StringUtils.isNumeric(attrValue))
                mContextTotal = Integer.parseInt(attrValue);
        } else if (nodeName.equalsIgnoreCase("Columns")) {
            nodeElement = (Element) nodeItem;
            DataBagXML dataBagXML = new DataBagXML();
            dataBagXML.load(nodeElement);
            DataBag dataBag = dataBagXML.getBag();
            dataBag.setName(mDataTable.getName());
            mDataTable = new DataTable(dataBag);
        } else if (nodeName.equalsIgnoreCase("Rows")) {
            nodeElement = (Element) nodeItem;
            loadRows(nodeElement);
        }
    }
}

From source file:com.twinsoft.convertigo.engine.util.WsReference.java

private static void extractSoapVariables(XmlSchema xmlSchema, List<RequestableHttpVariable> variables,
        Node node, String longName, boolean isMulti, QName variableType) throws EngineException {
    if (node == null)
        return;//from w w w  . j a  v  a2 s . c om
    int type = node.getNodeType();

    if (type == Node.ELEMENT_NODE) {
        Element element = (Element) node;
        if (element != null) {
            String elementName = element.getLocalName();
            if (longName != null)
                elementName = longName + "_" + elementName;

            if (!element.getAttribute("soapenc:arrayType").equals("") && !element.hasChildNodes()) {
                String avalue = element.getAttribute("soapenc:arrayType");
                element.setAttribute("soapenc:arrayType", avalue.replaceAll("\\[\\]", "[1]"));

                Element child = element.getOwnerDocument().createElement("item");
                String atype = avalue.replaceAll("\\[\\]", "");
                child.setAttribute("xsi:type", atype);
                if (atype.startsWith("xsd:")) {
                    String variableName = elementName + "_item";
                    child.appendChild(
                            element.getOwnerDocument().createTextNode("$(" + variableName.toUpperCase() + ")"));
                    RequestableHttpVariable httpVariable = createHttpVariable(true, variableName,
                            new QName(Constants.URI_2001_SCHEMA_XSD, atype.split(":")[1]));
                    variables.add(httpVariable);
                }
                element.appendChild(child);
            }

            // extract from attributes
            NamedNodeMap map = element.getAttributes();
            for (int i = 0; i < map.getLength(); i++) {
                Node child = map.item(i);
                if (child.getNodeName().equals("soapenc:arrayType"))
                    continue;
                if (child.getNodeName().equals("xsi:type"))
                    continue;
                if (child.getNodeName().equals("soapenv:encodingStyle"))
                    continue;

                String variableName = getVariableName(variables, elementName + "_" + child.getLocalName());

                child.setNodeValue("$(" + variableName.toUpperCase() + ")");

                RequestableHttpVariable httpVariable = createHttpVariable(false, variableName,
                        Constants.XSD_STRING);
                variables.add(httpVariable);
            }

            // extract from children nodes
            boolean multi = false;
            QName qname = Constants.XSD_STRING;
            NodeList children = element.getChildNodes();
            if (children.getLength() > 0) {
                Node child = element.getFirstChild();
                while (child != null) {
                    if (child.getNodeType() == Node.COMMENT_NODE) {
                        String value = child.getNodeValue();
                        if (value.startsWith("type:")) {
                            String schemaType = child.getNodeValue().substring("type:".length()).trim();
                            qname = getVariableSchemaType(xmlSchema, schemaType);
                        }
                        if (value.indexOf("repetitions:") != -1) {
                            multi = true;
                        }
                    } else if (child.getNodeType() == Node.TEXT_NODE) {
                        String value = child.getNodeValue().trim();
                        if (value.equals("?") || !value.equals("")) {
                            String variableName = getVariableName(variables, elementName);

                            child.setNodeValue("$(" + variableName.toUpperCase() + ")");

                            RequestableHttpVariable httpVariable = createHttpVariable(isMulti, variableName,
                                    variableType);
                            variables.add(httpVariable);
                        }
                    } else if (child.getNodeType() == Node.ELEMENT_NODE) {
                        extractSoapVariables(xmlSchema, variables, child, elementName, multi, qname);
                        multi = false;
                        qname = Constants.XSD_STRING;
                    }

                    child = child.getNextSibling();
                }
            }

        }
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

private static boolean compareAttributesIsSubset(NamedNodeMap subset, NamedNodeMap superset,
        boolean considerNamespacePrefixes) {
    for (int i = 0; i < subset.getLength(); i++) {
        Node aItem = subset.item(i);
        Attr aAttr = (Attr) aItem;
        if (!considerNamespacePrefixes && isNamespaceDefinition(aAttr)) {
            continue;
        }//from  w  w w.  j  av  a 2  s  .  c o m
        if (StringUtils.isBlank(aAttr.getLocalName())) {
            // this is strange, but it can obviously happen
            continue;
        }
        QName aQname = new QName(aAttr.getNamespaceURI(), aAttr.getLocalName());
        Attr bAttr = findAttributeByQName(superset, aQname);
        if (bAttr == null) {
            return false;
        }
        if (!StringUtils.equals(aAttr.getTextContent(), bAttr.getTextContent())) {
            return false;
        }
    }
    return true;
}

From source file:info.ajaxplorer.client.model.Node.java

public void initFromXmlNode(org.w3c.dom.Node xmlNode) {
    if (this.resourceType.equals(NODE_TYPE_REPOSITORY)) {
        this.addProperty("icon", "repository.png");
        NodeList children = xmlNode.getChildNodes();
        for (int k = 0; k < children.getLength(); k++) {
            if (children.item(k).getNodeName().equals("label")) {
                this.label = children.item(k).getTextContent();
            } /*else if(children.item(k).getNodeName().equals("client_settings")){
                this.addProperty("icon", children.item(k).getAttributes().getNamedItem("icon").getNodeValue());
              }*//*w  w w  .j  av a2  s  .c  om*/
        }
    }
    NamedNodeMap map = xmlNode.getAttributes();
    for (int i = 0; i < map.getLength(); i++) {
        String name = map.item(i).getNodeName();
        String value = map.item(i).getTextContent();
        if (name == "icon" || name == "openicon") {
            value = value.replace("-", "_");
        }
        if (this.resourceType.equals(NODE_TYPE_REPOSITORY)) {
            if (name.equals("id")) {
                this.addProperty("repository_id", value);
            } else if (name.equals("repositorySlug")) {
                this.addProperty("slug", value);
            } else {
                this.addProperty(name, value);
            }
        } else {
            if (name.equals("text")) {
                this.label = value;
            } else if (name.equals("is_file")) {
                if (value.equalsIgnoreCase("true")) {
                    this.setLeaf();
                }
            } else if (name.equals("ajxp_modiftime")) {
                this.lastModified = new Date(Long.parseLong(value) * 1000);
            } else if (name.equals("filename")) {
                this.path = value;
            } else {
                this.addProperty(name, value);
            }
        }
    }
    if (getPropertyValue("ajxp_mime") != null
            && getPropertyValue("ajxp_mime").equalsIgnoreCase("ajxp_browsable_archive")) {
        this.leaf = false;
    }
    this.uuid = UUID.randomUUID();
    this.setStatus(NODE_STATUS_FRESH);
}

From source file:com.nridge.core.base.io.xml.DocumentXML.java

private Document loadDocument(Element anElement) throws IOException {
    Node nodeItem;//from   ww w.ja v  a2 s  . c  om
    Attr nodeAttr;
    Document document;
    Element nodeElement;
    String nodeName, nodeValue;

    String docName = anElement.getAttribute("name");
    String typeName = anElement.getAttribute("type");
    String docTitle = anElement.getAttribute("title");
    String schemaVersion = anElement.getAttribute("schemaVersion");
    if ((StringUtils.isNotEmpty(typeName)) && (StringUtils.isNotEmpty(schemaVersion)))
        document = new Document(typeName);
    else
        document = new Document("Unknown");
    if (StringUtils.isNotEmpty(docName))
        document.setName(docName);
    if (StringUtils.isNotEmpty(docTitle))
        document.setName(docTitle);

    NamedNodeMap namedNodeMap = anElement.getAttributes();
    int attrCount = namedNodeMap.getLength();
    for (int attrOffset = 0; attrOffset < attrCount; attrOffset++) {
        nodeAttr = (Attr) namedNodeMap.item(attrOffset);
        nodeName = nodeAttr.getNodeName();
        nodeValue = nodeAttr.getNodeValue();

        if (StringUtils.isNotEmpty(nodeValue)) {
            if ((StringUtils.equalsIgnoreCase(nodeName, "name"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "type"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "title"))
                    || (StringUtils.equalsIgnoreCase(nodeName, "schemaVersion")))
                continue;
            else
                document.addFeature(nodeName, nodeValue);
        }
    }

    NodeList nodeList = anElement.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        nodeItem = nodeList.item(i);

        if (nodeItem.getNodeType() != Node.ELEMENT_NODE)
            continue;

        nodeName = nodeItem.getNodeName();
        if (StringUtils.equalsIgnoreCase(nodeName, IO.XML_TABLE_NODE_NAME)) {
            nodeElement = (Element) nodeItem;
            DataTableXML dataTableXML = new DataTableXML();
            dataTableXML.load(nodeElement);
            document.setTable(dataTableXML.getTable());
        } else if (StringUtils.equalsIgnoreCase(nodeName, IO.XML_RELATED_NODE_NAME)) {
            nodeElement = (Element) nodeItem;
            loadRelated(document, nodeElement);
        } else if (StringUtils.equalsIgnoreCase(nodeName, IO.XML_ACL_NODE_NAME)) {
            nodeElement = (Element) nodeItem;
            loadACL(document, nodeElement);
        }
    }

    return document;
}