Example usage for org.w3c.dom NamedNodeMap item

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

Introduction

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

Prototype

public Node item(int index);

Source Link

Document

Returns the indexth item in the map.

Usage

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   www  .j a va2 s. co  m*/
            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:com.cellngine.util.FXMLValidator.java

private void checkNode(final Node node) throws InvalidFXMLException {
    final String nodeName = node.getNodeName();
    final short nodeType = node.getNodeType();

    if (nodeType == Node.ELEMENT_NODE) {
        if (!ALLOWED_ELEMENTS.isElementAllowed(nodeName)) {
            throw new InvalidFXMLException("Element type \"" + nodeName + "\" not allowed");
        }//  w ww.  ja  va  2  s  . c  o  m

        final NamedNodeMap nodeAttributes = node.getAttributes();
        for (int i = 0; i < nodeAttributes.getLength(); i++) {
            checkAttributeNode(nodeAttributes.item(i), nodeName);
        }
    } else if (nodeType == Node.TEXT_NODE || nodeType == Node.DOCUMENT_NODE) {
    } else if (nodeType == Node.PROCESSING_INSTRUCTION_NODE && node.getNodeName().equals("import")) {
        if (!ALLOWED_IMPORTS.contains(node.getNodeValue())) {
            throw new InvalidFXMLException("Import \"" + node.getNodeValue() + "\" not allowed.");
        }
    } else if (nodeType != Node.COMMENT_NODE) {
        throw new InvalidFXMLException("Unrecognized node: type: \"" + nodeType + "\", name: \""
                + node.getNodeName() + "\", value: \"" + node.getNodeValue() + "\"");
    }

    final NodeList nodeChildren = node.getChildNodes();
    for (int i = 0; i < nodeChildren.getLength(); i++) {
        checkNode(nodeChildren.item(i));
    }
}

From source file:com.ryantenney.metrics.spring.reporter.AbstractReporterElementParser.java

protected void addDefaultProperties(Element element, BeanDefinitionBuilder beanDefBuilder) {
    final Map<String, String> properties = new HashMap<String, String>();
    final NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        final Node attribute = attributes.item(i);
        final String name = attribute.getNodeName();
        if (name.equals(METRIC_REGISTRY_REF) || name.equals(ID) || name.equals(TYPE)) {
            continue;
        }/*ww  w.  ja v a2  s.com*/
        properties.put(name, attribute.getNodeValue());
    }

    validate(properties);

    beanDefBuilder.addPropertyReference("metricRegistry", element.getAttribute(METRIC_REGISTRY_REF));
    beanDefBuilder.addPropertyValue("properties", properties);
}

From source file:com.amalto.core.storage.record.XmlDOMDataRecordReader.java

private void _read(MetadataRepository repository, DataRecord dataRecord, ComplexTypeMetadata type,
        Element element) {//from w w  w  .j ava2  s. c o m
    // TODO Don't use getChildNodes() but getNextSibling() calls (but cause regressions -> see TMDM-5410).
    String tagName = element.getTagName();
    NodeList children = element.getChildNodes();
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        if (!type.hasField(attribute.getNodeName())) {
            continue;
        }
        FieldMetadata field = type.getField(attribute.getNodeName());
        dataRecord.set(field, StorageMetadataUtils.convert(attribute.getNodeValue(), field));
    }
    for (int i = 0; i < children.getLength(); i++) {
        Node currentChild = children.item(i);
        if (currentChild instanceof Element) {
            Element child = (Element) currentChild;
            if (METADATA_NAMESPACE.equals(child.getNamespaceURI())) {
                DataRecordMetadataHelper.setMetadataValue(dataRecord.getRecordMetadata(), child.getLocalName(),
                        child.getTextContent());
            } else {
                if (!type.hasField(child.getTagName())) {
                    continue;
                }
                FieldMetadata field = type.getField(child.getTagName());
                if (field.getType() instanceof ContainedComplexTypeMetadata) {
                    ComplexTypeMetadata containedType = (ComplexTypeMetadata) field.getType();
                    String xsiType = child.getAttributeNS(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "type"); //$NON-NLS-1$
                    if (xsiType.startsWith("java:")) { //$NON-NLS-1$
                        // Special format for 'java:' type names (used in Castor XML to indicate actual class name)
                        xsiType = ClassRepository.format(StringUtils
                                .substringAfterLast(StringUtils.substringAfter(xsiType, "java:"), ".")); //$NON-NLS-1$ //$NON-NLS-2$
                    }
                    if (!xsiType.isEmpty()) {
                        for (ComplexTypeMetadata subType : containedType.getSubTypes()) {
                            if (subType.getName().equals(xsiType)) {
                                containedType = subType;
                                break;
                            }
                        }
                    }
                    DataRecord containedRecord = new DataRecord(containedType,
                            UnsupportedDataRecordMetadata.INSTANCE);
                    dataRecord.set(field, containedRecord);
                    _read(repository, containedRecord, containedType, child);
                } else if (ClassRepository.EMBEDDED_XML.equals(field.getType().getName())) {
                    try {
                        dataRecord.set(field, Util.nodeToString(element));
                    } catch (TransformerException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    _read(repository, dataRecord, type, child);
                }
            }
        } else if (currentChild instanceof Text) {
            StringBuilder builder = new StringBuilder();
            for (int j = 0; j < element.getChildNodes().getLength(); j++) {
                String nodeValue = element.getChildNodes().item(j).getNodeValue();
                if (nodeValue != null) {
                    builder.append(nodeValue.trim());
                }
            }
            String textContent = builder.toString();
            if (!textContent.isEmpty()) {
                FieldMetadata field = type.getField(tagName);
                if (field instanceof ReferenceFieldMetadata) {
                    ComplexTypeMetadata actualType = ((ReferenceFieldMetadata) field).getReferencedType();
                    String mdmType = element.getAttributeNS(SkipAttributeDocumentBuilder.TALEND_NAMESPACE,
                            "type"); //$NON-NLS-1$
                    if (!mdmType.isEmpty()) {
                        actualType = repository.getComplexType(mdmType);
                    }
                    if (actualType == null) {
                        throw new IllegalArgumentException("Type '" + mdmType + "' does not exist.");
                    }
                    dataRecord.set(field, StorageMetadataUtils.convert(textContent, field, actualType));
                } else {
                    dataRecord.set(field, StorageMetadataUtils.convert(textContent, field, type));
                }
            }
        }
    }
}

From source file:br.com.elotech.sits.service.AbstractService.java

public Node getXSDNotaFiscal(File file) throws ParserConfigurationException, SAXException, IOException {

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);//  w  w w.j a v  a 2  s  . c o m
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(file);

    Node root = (Node) doc.getDocumentElement();

    NamedNodeMap attributes = root.getAttributes();
    if (attributes != null) {
        for (int i = 0; i < attributes.getLength(); i++) {
            Node node = attributes.item(i);
            if (node.getNodeType() == Node.ATTRIBUTE_NODE) {

                if (ATRIBUTO_PRINCIPAL_NOTA_FISCAL.equals(node.getNodeName())) {
                    return node;
                }
            }
        }
    }

    return null;

}

From source file:eu.europa.esig.dss.validation.report.SimpleReport.java

private List<Conclusion.BasicInfo> getBasicInfo(final String signatureId, final String basicInfoType) {

    final List<XmlDom> elementList = getElements("/SimpleReport/Signature[@Id='%s']/" + basicInfoType,
            signatureId);/*from  w  ww  .j a v  a2  s . c om*/
    final List<Conclusion.BasicInfo> infoList = new ArrayList<Conclusion.BasicInfo>();
    for (final XmlDom infoElement : elementList) {

        Conclusion.BasicInfo basicInfo = new Conclusion.BasicInfo(basicInfoType);
        basicInfo.setValue(infoElement.getText());
        final NamedNodeMap attributes = infoElement.getAttributes();
        for (int index = 0; index < attributes.getLength(); index++) {

            final Node attribute = attributes.item(index);
            basicInfo.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
        }
        infoList.add(basicInfo);
    }
    return infoList;
}

From source file:com.limegroup.gnutella.metadata.audio.reader.WRMXML.java

/**
 * Parses the attributes of a given node.
 * 'parentNodeName' is the parent node of this child, and child is the node
 * which the attributes are part of./*from   ww w . j a va  2  s  .c  o  m*/
 * Attributes are sent to parseChild for parsing.
 */
protected void parseAttributes(String parentNodeName, Node child) {
    NamedNodeMap nnm = child.getAttributes();
    String name = child.getNodeName();
    for (int i = 0; i < nnm.getLength(); i++) {
        Node attribute = nnm.item(i);
        String attrName = attribute.getNodeName();
        String attrValue = attribute.getNodeValue();
        if (attrValue == null)
            continue;
        attrValue = attrValue.trim();
        if (attrValue.equals(""))
            continue;
        parseChild(parentNodeName, name, attrName, attrValue);
    }
}

From source file:com.swdouglass.joid.consumer.Discoverer.java

private String nodeToString(Node inNode) {
    StringBuilder sb = new StringBuilder();
    sb.append("[Node: name=");
    sb.append(inNode.getNodeName());//from   ww  w .j a  v  a2 s.c  o m
    if (inNode.hasAttributes()) {
        sb.append(", attributes={");
        NamedNodeMap nnmap = inNode.getAttributes();
        for (int i = 0; i < nnmap.getLength(); i++) {
            sb.append(nnmap.item(i).getNodeName());
            sb.append("=");
            sb.append(nnmap.item(i).getNodeValue());
            sb.append(" ");
        }
    }
    sb.append("}]");
    return sb.toString();
}

From source file:jp.igapyon.selecrawler.SeleCrawlerWebContentTrimmer.java

public void processElement(final Element element) throws IOException {
    final NodeList nodeList = element.getChildNodes();
    for (int index = nodeList.getLength() - 1; index >= 0; index--) {
        final Node node = nodeList.item(index);
        if (node instanceof Element) {
            final Element lookup = (Element) node;

            if ("script".equals(lookup.getTagName())) {
                // REMOVE script tag.
                element.removeChild(node);
                continue;
            }// ww w . j a va  2s.c om

            if ("noscript".equals(lookup.getTagName())) {
                // REMOVE noscript tag.
                element.removeChild(node);
                continue;
            }

            if ("iframe".equals(lookup.getTagName())) {
                final NamedNodeMap nnm = lookup.getAttributes();
                for (int indexNnm = 0; indexNnm < nnm.getLength(); indexNnm++) {
                    final Attr attr = (Attr) nnm.item(indexNnm);

                    // System.out.println(" " + attr.getName() + " [" +
                    // attr.getValue() + "]");
                    if ("style".equals(attr.getName())) {
                        final String value = attr.getValue().replaceAll(" ", "");
                        if (value.indexOf("display:none") >= 0) {
                            // REMOVE iframe tag which is display:none
                            // style..
                            element.removeChild(node);
                            continue;
                        }
                    }
                }
            }

            processElement(lookup);
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XMLSerializer.java

private void toXml(final int indent, final DomNode node, final StringBuilder buffer) {
    final String nodeName = node.getNodeName();
    buffer.append('<').append(nodeName);

    final String optionalPrefix = "";
    final String namespaceURI = node.getNamespaceURI();
    final String prefix = node.getPrefix();
    if (namespaceURI != null && prefix != null) {
        boolean sameNamespace = false;
        for (DomNode parentNode = node
                .getParentNode(); parentNode instanceof DomElement; parentNode = parentNode.getParentNode()) {
            if (namespaceURI.equals(parentNode.getNamespaceURI())) {
                sameNamespace = true;/*from w  w  w .  j ava 2s  .c  om*/
            }
        }
        if (node.getParentNode() == null || !sameNamespace) {
            ((DomElement) node).setAttribute("xmlns:" + prefix, namespaceURI);
        }
    }

    final NamedNodeMap attributesMap = node.getAttributes();
    for (int i = 0; i < attributesMap.getLength(); i++) {
        final DomAttr attrib = (DomAttr) attributesMap.item(i);
        buffer.append(' ').append(attrib.getQualifiedName()).append('=').append('"').append(attrib.getValue())
                .append('"');
    }
    boolean startTagClosed = false;
    for (final DomNode child : node.getChildren()) {
        if (!startTagClosed) {
            buffer.append(optionalPrefix).append('>');
            startTagClosed = true;
        }
        switch (child.getNodeType()) {
        case Node.ELEMENT_NODE:
            toXml(indent + 1, child, buffer);
            break;

        case Node.TEXT_NODE:
            String value = child.getNodeValue();
            value = StringUtils.escapeXmlChars(value);
            if (preserveWhiteSpace_) {
                buffer.append(value.replace("\n", "\r\n"));
            } else if (org.apache.commons.lang3.StringUtils.isBlank(value)) {
                buffer.append("\r\n");
                final DomNode sibling = child.getNextSibling();
                if (sibling != null && sibling.getNodeType() == Node.ELEMENT_NODE) {
                    for (int i = 0; i < indent; i++) {
                        buffer.append('\t');
                    }
                }
            } else {
                buffer.append(value.replace("\n", "\r\n"));
            }
            break;

        case Node.CDATA_SECTION_NODE:
        case Node.COMMENT_NODE:
            if (!preserveWhiteSpace_ && buffer.charAt(buffer.length() - 1) == '\n') {
                for (int i = 0; i < indent; i++) {
                    buffer.append('\t');
                }
            }
            buffer.append(child.asXml());
            break;

        default:

        }
    }
    if (!startTagClosed) {
        buffer.append(optionalPrefix).append("/>");
    } else {
        if (!preserveWhiteSpace_ && buffer.charAt(buffer.length() - 1) == '\n') {
            for (int i = 0; i < indent - 1; i++) {
                buffer.append('\t');
            }
        }
        buffer.append('<').append('/').append(nodeName).append('>');
    }
}