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:DOMDump.java

private void dump(Node root, String prefix) {
    if (root instanceof Element) {
        System.out.println(prefix + ((Element) root).getTagName() + " / " + root.getClass().getName());
    } else if (root instanceof CharacterData) {
        String data = ((CharacterData) root).getData().trim();
        if (!data.equals("")) {
            System.out.println(prefix + "CharacterData: " + data);
        }/* w ww.  j a v  a  2  s  . c o m*/
    } else {
        System.out.println(prefix + root.getClass().getName());
    }
    NamedNodeMap attrs = root.getAttributes();
    if (attrs != null) {
        int len = attrs.getLength();
        for (int i = 0; i < len; i++) {
            Node attr = attrs.item(i);
            System.out.print(prefix + HALF_INDENT + "attribute " + i + ": " + attr.getNodeName());
            if (attr instanceof Attr) {
                System.out.print(" = " + ((Attr) attr).getValue());
            }
            System.out.println();
        }
    }

    if (root.hasChildNodes()) {
        NodeList children = root.getChildNodes();
        if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++) {
                dump(children.item(i), prefix + INDENT);
            }
        }
    }
}

From source file:ar.com.zauber.commons.web.transformation.sanitizing.impl.AbstractElementNodeSanitizer.java

/**
 * Recursive tree traversal//from w  ww  .  j av a 2 s.c o  m
 * @param node
 * @param invalidElements
 */
private void sanitizeNode(final Node node, final List<Element> invalidElements) {
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        final Element element = (Element) node;
        if (!tagSecurityStrategy.isTagAllowed(element.getNodeName())) {
            invalidElements.add(element);
            return;
        } else {
            final NamedNodeMap attributes = node.getAttributes();

            if (attributes.getLength() > 0) {

                final List<Attr> invalidAttributes = new ArrayList<Attr>();

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

                    final Attr attribute = (Attr) attributes.item(i);

                    if (!tagSecurityStrategy.isAttributeAllowedForTag(attribute.getNodeName(),
                            element.getNodeName())
                            || !tagSecurityStrategy.isAttributeValueValidForTag(attribute.getNodeValue(),
                                    attribute.getNodeName(), element.getNodeName())) {

                        invalidAttributes.add(attribute);
                    }
                }
                processInvalidElementAttributes(element, invalidAttributes);
            }
        }
    }
    final NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); ++i) {
        sanitizeNode(children.item(i), invalidElements);
    }
}

From source file:org.carewebframework.shell.BaseXmlParser.java

/**
 * Adds all attributes of the specified elements as properties in the current builder.
 * /*from   w  w w. ja v  a 2  s  . c  om*/
 * @param element Element whose attributes are to be added.
 * @param builder Target builder.
 */
protected void addProperties(Element element, BeanDefinitionBuilder builder) {
    NamedNodeMap attributes = element.getAttributes();

    for (int i = 0; i < attributes.getLength(); i++) {
        Node node = attributes.item(i);
        String attrName = getNodeName(node);
        attrName = "class".equals(attrName) ? "clazz" : attrName;
        builder.addPropertyValue(attrName, node.getNodeValue());
    }
}

From source file:edu.mayo.cts2.framework.core.xml.PatchedCastorMarshaller.java

protected Object unmarshalDomSource(DOMSource domSource) throws XmlMappingException {

    Node node = domSource.getNode();
    if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;

        Node parent = node.getParentNode();
        while (parent != null) {
            NamedNodeMap atts = parent.getAttributes();
            if (atts != null) {
                for (int i = 0, j = atts.getLength(); i < j; i++) {

                    Attr att = (Attr) atts.item(i);
                    if (XMLNS_NS.equals(att.getNamespaceURI())) {
                        String name = att.getName();
                        String value = att.getValue();
                        if (!element.hasAttributeNS(XMLNS_NS, name)) {
                            element.setAttributeNS(XMLNS_NS, name, value);
                        }//from   w ww.j a  v a2s.c o m
                    }

                }
            }
            parent = parent.getParentNode();
        }
    }

    return super.unmarshalDomSource(domSource);
}

From source file:org.jetbrains.webdemo.help.HelpLoader.java

private String getTagValueWithTagName(Node node) {
    StringBuilder result = new StringBuilder();

    if (node.getNodeType() == 3) {
        result.append(node.getNodeValue());
    } else {// w w  w . j av  a 2s .c o m
        result.append("<");
        result.append(node.getNodeName());
        if (node.getNodeName().equals("a")) {
            result.append(" target=\"_blank\" ");
        }
        if (node.hasAttributes()) {
            result.append(" ");
            NamedNodeMap map = node.getAttributes();
            for (int i = 0; i < map.getLength(); i++) {
                result.append(map.item(i).getNodeName());
                result.append("=\"");
                result.append(map.item(i).getTextContent());
                result.append("\" ");
            }
        }
        result.append(">");
        if (node.hasChildNodes()) {
            NodeList nodeList = node.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                result.append(getTagValueWithTagName(nodeList.item(i)));
            }
        }
        result.append("</");
        result.append(node.getNodeName());
        result.append(">");
    }
    return result.toString();
}

From source file:cn.edu.bit.whitesail.parser.HtmlParser.java

private void getLinks(Node node, List<URL> URLsToFill, String anchor) {
    URL u = null;//  w w w .j a v a  2  s  .  c  o m

    if (node.getNodeName().equalsIgnoreCase("a") || node.getNodeName().equalsIgnoreCase("link")) {
        NamedNodeMap map = node.getAttributes();
        int length = map.getLength();
        for (int i = 0; i < length; i++) {
            Node item = map.item(i);
            if (item.getNodeName().equalsIgnoreCase("href")) {
                u = URLFormat(item.getNodeValue(), anchor);
                if (null != u) {
                    URLsToFill.add(u);
                }
            }
        }
    }
    Node child = node.getFirstChild();
    while (child != null) {
        getLinks(child, URLsToFill, anchor);
        child = child.getNextSibling();
    }
}

From source file:jp.sf.fess.solr.plugin.suggest.util.SolrConfigUtil.java

public static SuggestUpdateConfig getUpdateHandlerConfig(final SolrConfig config) {
    final SuggestUpdateConfig suggestUpdateConfig = new SuggestUpdateConfig();

    final Node solrServerNode = config.getNode("updateHandler/suggest/solrServer", false);
    if (solrServerNode != null) {
        try {//from  ww w . ja  v a 2 s .c  om
            final Node classNode = solrServerNode.getAttributes().getNamedItem("class");
            String className;
            if (classNode != null) {
                className = classNode.getTextContent();
            } else {
                className = "org.codelibs.solr.lib.server.SolrLibHttpSolrServer";
            }
            @SuppressWarnings("unchecked")
            final Class<? extends SolrServer> clazz = (Class<? extends SolrServer>) Class.forName(className);
            final String arg = config.getVal("updateHandler/suggest/solrServer/arg", false);
            SolrServer solrServer;
            if (StringUtils.isNotBlank(arg)) {
                final Constructor<? extends SolrServer> constructor = clazz.getConstructor(String.class);
                solrServer = constructor.newInstance(arg);
            } else {
                solrServer = clazz.newInstance();
            }

            final String username = config.getVal("updateHandler/suggest/solrServer/credentials/username",
                    false);
            final String password = config.getVal("updateHandler/suggest/solrServer/credentials/password",
                    false);
            if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)
                    && solrServer instanceof SolrLibHttpSolrServer) {
                final SolrLibHttpSolrServer solrLibHttpSolrServer = (SolrLibHttpSolrServer) solrServer;
                final URL u = new URL(arg);
                final AuthScope authScope = new AuthScope(u.getHost(), u.getPort());
                final Credentials credentials = new UsernamePasswordCredentials(username, password);
                solrLibHttpSolrServer.setCredentials(authScope, credentials);
                solrLibHttpSolrServer.addRequestInterceptor(new PreemptiveAuthInterceptor());
            }

            final NodeList childNodes = solrServerNode.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                final Node node = childNodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    final String name = node.getNodeName();
                    if (!"arg".equals(name) && !"credentials".equals(name)) {
                        final String value = node.getTextContent();
                        final Node typeNode = node.getAttributes().getNamedItem("type");
                        final Method method = clazz.getMethod(
                                "set" + name.substring(0, 1).toUpperCase() + name.substring(1),
                                getMethodArgClass(typeNode));
                        method.invoke(solrServer, getMethodArgValue(typeNode, value));
                    }
                }
            }
            if (solrServer instanceof SolrLibHttpSolrServer) {
                ((SolrLibHttpSolrServer) solrServer).init();
            }
            suggestUpdateConfig.setSolrServer(solrServer);
        } catch (final Exception e) {
            throw new FessSuggestException("Failed to load SolrServer.", e);
        }
    }

    final String labelFields = config.getVal("updateHandler/suggest/labelFields", false);
    if (StringUtils.isNotBlank(labelFields)) {
        suggestUpdateConfig.setLabelFields(labelFields.trim().split(","));
    }
    final String roleFields = config.getVal("updateHandler/suggest/roleFields", false);
    if (StringUtils.isNotBlank(roleFields)) {
        suggestUpdateConfig.setRoleFields(roleFields.trim().split(","));
    }

    final String expiresField = config.getVal("updateHandler/suggest/expiresField", false);
    if (StringUtils.isNotBlank(expiresField)) {
        suggestUpdateConfig.setExpiresField(expiresField);
    }
    final String segmentField = config.getVal("updateHandler/suggest/segmentField", false);
    if (StringUtils.isNotBlank(segmentField)) {
        suggestUpdateConfig.setSegmentField(segmentField);
    }
    final String updateInterval = config.getVal("updateHandler/suggest/updateInterval", false);
    if (StringUtils.isNotBlank(updateInterval) && StringUtils.isNumeric(updateInterval)) {
        suggestUpdateConfig.setUpdateInterval(Long.parseLong(updateInterval));
    }

    //set suggestFieldInfo
    final NodeList nodeList = config.getNodeList("updateHandler/suggest/suggestFieldInfo", true);
    for (int i = 0; i < nodeList.getLength(); i++) {
        try {
            final SuggestUpdateConfig.FieldConfig fieldConfig = new SuggestUpdateConfig.FieldConfig();
            final Node fieldInfoNode = nodeList.item(i);
            final NamedNodeMap fieldInfoAttributes = fieldInfoNode.getAttributes();
            final Node fieldNameNode = fieldInfoAttributes.getNamedItem("fieldName");
            final String fieldName = fieldNameNode.getNodeValue();
            if (StringUtils.isBlank(fieldName)) {
                continue;
            }
            fieldConfig.setTargetFields(fieldName.trim().split(","));
            if (logger.isInfoEnabled()) {
                for (final String s : fieldConfig.getTargetFields()) {
                    logger.info("fieldName : " + s);
                }
            }

            final NodeList fieldInfoChilds = fieldInfoNode.getChildNodes();
            for (int j = 0; j < fieldInfoChilds.getLength(); j++) {
                final Node fieldInfoChildNode = fieldInfoChilds.item(j);
                final String fieldInfoChildNodeName = fieldInfoChildNode.getNodeName();

                if ("tokenizerFactory".equals(fieldInfoChildNodeName)) {
                    //field tokenier settings
                    final SuggestUpdateConfig.TokenizerConfig tokenizerConfig = new SuggestUpdateConfig.TokenizerConfig();

                    final NamedNodeMap tokenizerFactoryAttributes = fieldInfoChildNode.getAttributes();
                    final Node tokenizerClassNameNode = tokenizerFactoryAttributes.getNamedItem("class");
                    final String tokenizerClassName = tokenizerClassNameNode.getNodeValue();
                    tokenizerConfig.setClassName(tokenizerClassName);
                    if (logger.isInfoEnabled()) {
                        logger.info("tokenizerFactory : " + tokenizerClassName);
                    }

                    final Map<String, String> args = new HashMap<String, String>();
                    for (int k = 0; k < tokenizerFactoryAttributes.getLength(); k++) {
                        final Node attribute = tokenizerFactoryAttributes.item(k);
                        final String key = attribute.getNodeName();
                        final String value = attribute.getNodeValue();
                        if (!"class".equals(key)) {
                            args.put(key, value);
                        }
                    }
                    if (!args.containsKey(USER_DICT_PATH)) {
                        final String userDictPath = System.getProperty(SuggestConstants.USER_DICT_PATH, "");
                        if (StringUtils.isNotBlank(userDictPath)) {
                            args.put(USER_DICT_PATH, userDictPath);
                        }
                        final String userDictEncoding = System.getProperty(SuggestConstants.USER_DICT_ENCODING,
                                "");
                        if (StringUtils.isNotBlank(userDictEncoding)) {
                            args.put(USER_DICT_ENCODING, userDictEncoding);
                        }
                    }
                    tokenizerConfig.setArgs(args);

                    fieldConfig.setTokenizerConfig(tokenizerConfig);
                } else if ("suggestReadingConverter".equals(fieldInfoChildNodeName)) {
                    //field reading converter settings
                    final NodeList converterNodeList = fieldInfoChildNode.getChildNodes();
                    for (int k = 0; k < converterNodeList.getLength(); k++) {
                        final SuggestUpdateConfig.ConverterConfig converterConfig = new SuggestUpdateConfig.ConverterConfig();

                        final Node converterNode = converterNodeList.item(k);
                        if (!"converter".equals(converterNode.getNodeName())) {
                            continue;
                        }

                        final NamedNodeMap converterAttributes = converterNode.getAttributes();
                        final Node classNameNode = converterAttributes.getNamedItem("class");
                        final String className = classNameNode.getNodeValue();
                        converterConfig.setClassName(className);
                        if (logger.isInfoEnabled()) {
                            logger.info("converter : " + className);
                        }

                        final Map<String, String> properties = new HashMap<String, String>();
                        for (int l = 0; l < converterAttributes.getLength(); l++) {
                            final Node attribute = converterAttributes.item(l);
                            final String key = attribute.getNodeName();
                            final String value = attribute.getNodeValue();
                            if (!"class".equals(key)) {
                                properties.put(key, value);
                            }
                        }
                        converterConfig.setProperties(properties);
                        if (logger.isInfoEnabled()) {
                            logger.info("converter properties = " + properties);
                        }
                        fieldConfig.addConverterConfig(converterConfig);
                    }
                } else if ("suggestNormalizer".equals(fieldInfoChildNodeName)) {
                    //field normalizer settings
                    final NodeList normalizerNodeList = fieldInfoChildNode.getChildNodes();
                    for (int k = 0; k < normalizerNodeList.getLength(); k++) {
                        final SuggestUpdateConfig.NormalizerConfig normalizerConfig = new SuggestUpdateConfig.NormalizerConfig();

                        final Node normalizerNode = normalizerNodeList.item(k);
                        if (!"normalizer".equals(normalizerNode.getNodeName())) {
                            continue;
                        }

                        final NamedNodeMap normalizerAttributes = normalizerNode.getAttributes();
                        final Node classNameNode = normalizerAttributes.getNamedItem("class");
                        final String className = classNameNode.getNodeValue();
                        normalizerConfig.setClassName(className);
                        if (logger.isInfoEnabled()) {
                            logger.info("normalizer : " + className);
                        }

                        final Map<String, String> properties = new HashMap<String, String>();
                        for (int l = 0; l < normalizerAttributes.getLength(); l++) {
                            final Node attribute = normalizerAttributes.item(l);
                            final String key = attribute.getNodeName();
                            final String value = attribute.getNodeValue();
                            if (!"class".equals(key)) {
                                properties.put(key, value);
                            }
                        }
                        normalizerConfig.setProperties(properties);
                        if (logger.isInfoEnabled()) {
                            logger.info("normalize properties = " + properties);
                        }
                        fieldConfig.addNormalizerConfig(normalizerConfig);
                    }
                }
            }

            suggestUpdateConfig.addFieldConfig(fieldConfig);
        } catch (final Exception e) {
            throw new FessSuggestException("Failed to load Suggest Field Info.", e);
        }
    }

    return suggestUpdateConfig;
}

From source file:org.shareok.data.plosdata.PlosApiDataImpl.java

private Map<String, String> getArticleMapData(Element ele) {
    Map<String, String> mapData = new HashMap<>();
    NodeList eleChildren = ele.getChildNodes();
    for (int childIndex = 0; childIndex < eleChildren.getLength(); childIndex++) {
        Node node = eleChildren.item(childIndex);
        String nodeName = node.getNodeName();
        NamedNodeMap attributes = node.getAttributes();
        if (attributes.getLength() > 0) {
            Node item = attributes.item(0);
            String attributeVal = item.getNodeValue();
            String val = "";
            if (nodeName.equals("arr")) {
                NodeList children = node.getChildNodes();
                for (int j = 0; j < children.getLength(); j++) {
                    Node child = children.item(j);
                    if (child.getNodeName().equals("str")) {
                        val += child.getTextContent() + ";  ";
                    }//w w w.  j  a v  a 2  s . c om
                }
            } else {
                val = node.getTextContent();
            }
            val = val.trim();
            if (val.endsWith(";")) {
                val = val.substring(0, val.length() - 1);
            }
            if (attributeVal.equals("publication_date")) {
                attributeVal = "publication date";
                try {
                    val = DataHandlersUtil.convertPubTimeFormat(val);
                } catch (ParseException ex) {
                    logger.error(
                            "Cannot convert the publication time from yyyy-MM-dd'T'HH:mm:ss to yyyy-MM-dd format",
                            ex);
                }
            }
            mapData.put(attributeVal, val);
        }
    }

    return mapData;
}

From source file:com.apporiented.spring.override.GenericBeanDefinitionParser.java

/**
 * Parse the supplied {@link org.w3c.dom.Element} and populate the supplied
 * {@link org.springframework.beans.factory.support.BeanDefinitionBuilder} as required.
 * <p>This implementation maps any attributes present on the
 * supplied element to {@link org.springframework.beans.PropertyValue}
 * instances, and//from w  w w  . j  a v  a 2  s  .  co m
 * {@link org.springframework.beans.factory.support.BeanDefinitionBuilder#addPropertyValue(String, Object) adds them}
 * to the
 * {@link org.springframework.beans.factory.config.BeanDefinition builder}.
 * <p>The {@link #extractPropertyName(String)} method is used to
 * reconcile the name of an attribute with the name of a JavaBean
 * property.
 * @param element the XML element being parsed
 * @param parserContext the object encapsulating the current state of the parsing process
 * @param builder used to define the <code>BeanDefinition</code>
 * @see #extractPropertyName(String)
 */
protected final void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {

    NamedNodeMap attributes = element.getAttributes();
    for (int x = 0; x < attributes.getLength(); x++) {
        Attr attribute = (Attr) attributes.item(x);
        String name = attribute.getLocalName();
        if (isEligibleAttribute(name, parserContext)) {
            String propertyName = extractPropertyName(name);
            Assert.state(StringUtils.hasText(propertyName),
                    "Illegal property name returned from 'extractPropertyName(String)': cannot be null or empty.");

            Object value;
            if (references.contains(propertyName)) {
                value = new RuntimeBeanReference(attribute.getValue());
            } else {
                value = attribute.getValue();
            }
            builder.addPropertyValue(propertyName, value);
        }
    }
    postProcess(builder, parserContext, element);
}

From source file:com.diversityarrays.dalclient.DalUtil.java

public static Map<String, String> asRowdata(Node node) {
    Map<String, String> result = null;

    NamedNodeMap attributes = node.getAttributes();
    if (attributes != null) {
        int nAttributes = attributes.getLength();
        result = new LinkedHashMap<>(nAttributes);
        for (int ai = 0; ai < nAttributes; ++ai) {
            Node attr = attributes.item(ai);
            result.put(attr.getNodeName(), attr.getNodeValue());
        }//from   www . jav  a  2 s. c  om
    }
    return result;
}