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:com.ikanow.infinit.e.harvest.enrichment.custom.UnstructuredAnalysisHarvester.java

private static HashMap<String, Object> parseHtmlTable(Node table_node, String replaceWith) {
    if (table_node.getNodeName().equalsIgnoreCase("table") && table_node.hasChildNodes()) {
        Node topNode = table_node;

        boolean tbody = table_node.getFirstChild().getNodeName().equalsIgnoreCase("tbody");

        if (tbody)
            topNode = table_node.getFirstChild();

        if (topNode.hasChildNodes()) {
            NodeList rows = topNode.getChildNodes();

            List<String> headers = null;
            ArrayList<HashMap<String, String>> data = null;
            int headerLength = 0;
            boolean[] skip = null;

            if (null != replaceWith) {
                if (replaceWith.equals("[]")) {
                    headers = new ArrayList<String>();
                    headerLength = 0;/*from   w w  w.  ja v  a2s  .  co m*/
                } // TESTED (by eye - 2)
                else {
                    //Remove square brackets
                    if (replaceWith.startsWith("[") && replaceWith.endsWith("]"))
                        replaceWith = replaceWith.substring(1, replaceWith.length() - 1);
                    //Turn the provided list of headers into a list object
                    headers = Arrays.asList(replaceWith.split("\\s*,\\s*"));
                    headerLength = headers.size();
                    skip = new boolean[headerLength];
                    for (int h = 0; h < headerLength; h++) {
                        String val = headers.get(h);
                        if (val.length() == 0 || val.equalsIgnoreCase("null"))
                            skip[h] = true;
                        else
                            skip[h] = false;
                    }

                } // TESTED (by eye - 3a)
            }

            //traverse rows
            for (int i = 0; i < rows.getLength(); i++) {
                Node row = rows.item(i);
                if (row.getNodeName().equalsIgnoreCase("tr") || row.getNodeName().equalsIgnoreCase("th")) {
                    //If the header value has not been set, the first row will be set as the headers
                    if (null == headers) {
                        //Traverse through cells
                        headers = new ArrayList<String>();
                        if (row.hasChildNodes()) {
                            NodeList cells = row.getChildNodes();
                            headerLength = cells.getLength();
                            skip = new boolean[headerLength];
                            for (int j = 0; j < headerLength; j++) {
                                headers.add(cells.item(j).getTextContent());
                                skip[j] = false;
                            }
                        } // TESTED (by eye - 1)
                    } else {
                        if (null == data) {
                            data = new ArrayList<HashMap<String, String>>();
                        }
                        if (row.hasChildNodes()) {
                            HashMap<String, String> cellList = new HashMap<String, String>();
                            NodeList cells = row.getChildNodes();
                            for (int j = 0; j < cells.getLength(); j++) {
                                // Skip Code (TESTED by eye - 4)
                                if (headerLength == 0 || (j < headerLength && skip[j] == false)) {
                                    String key = Integer.toString(j); // TESTED (by eye - 3b)
                                    if (j < headerLength)
                                        key = headers.get(j);

                                    cellList.put(key, cells.item(j).getTextContent());
                                }
                            }
                            data.add(cellList);
                        }

                    }
                }
            }
            //Create final hashmap containing attributes
            HashMap<String, Object> table_attrib = new HashMap<String, Object>();

            NamedNodeMap nnm = table_node.getAttributes();
            for (int i = 0; i < nnm.getLength(); i++) {
                Node att = nnm.item(i);
                table_attrib.put(att.getNodeName(), att.getNodeValue());
            }
            table_attrib.put("table", data);

            //TESTED (by eye) attributes added to table value
            // eg: {"id":"search","cellpadding":"1","table":[{"Status":"B","two":"ONE6313" ......

            return table_attrib;
        }
    }
    return null;
}

From source file:com.globalsight.everest.tda.TdaHelper.java

private void domNodeVisitor(Node p_node, ArrayList matchList, long tmProfileThreshold) {
    HashMap TDAResults = new HashMap();
    LeverageTDAResult tdaResult = null;// w ww  .j  a va  2  s. co  m

    if (matchList.size() > 0) {
        tdaResult = (LeverageTDAResult) matchList.get(matchList.size() - 1);
    }

    while (true) {
        if (p_node == null) {
            return;
        }

        switch (p_node.getNodeType()) {
        case Node.DOCUMENT_NODE:
            domNodeVisitor(p_node.getFirstChild(), matchList, tmProfileThreshold);
            return;
        case Node.ELEMENT_NODE:
            String nodeName = p_node.getNodeName().toLowerCase();

            if (nodeName.equals("alt-trans")) {
                String tuid = "-1";

                NamedNodeMap parentAttrs = p_node.getParentNode().getAttributes();

                for (int i = 0; i < parentAttrs.getLength(); ++i) {
                    Node att = parentAttrs.item(i);
                    String attname = att.getNodeName();
                    String value = att.getNodeValue();

                    if (attname.equals("id")) {
                        tuid = value;
                    }
                }

                NamedNodeMap attrs = p_node.getAttributes();
                boolean fromTDA = false;
                String percentValue = "";

                for (int i = 0; i < attrs.getLength(); ++i) {
                    Node att = attrs.item(i);
                    String attname = att.getNodeName();
                    String value = att.getNodeValue();

                    if (attname.equals("tda:provider")) {
                        fromTDA = true;
                    }

                    if (attname.equals("match-quality")) {
                        percentValue = value;
                    }

                }

                if (fromTDA) {
                    if (PecentToInt(percentValue) > tmProfileThreshold
                            || PecentToInt(percentValue) == tmProfileThreshold) {
                        tdaResult = new LeverageTDAResult();
                        tdaResult.setTuid(Long.parseLong(tuid));
                        tdaResult.setMatchPercent(percentValue);
                        matchList.add(tdaResult);
                    } else {
                        p_node = p_node.getNextSibling();
                        break;
                    }
                }
            }

            domNodeVisitor(p_node.getFirstChild(), matchList, tmProfileThreshold);
            p_node = p_node.getNextSibling();
            break;
        case Node.TEXT_NODE:
            nodeName = p_node.getNodeName().toLowerCase();

            if (p_node.getParentNode() != null && p_node.getParentNode().getParentNode() != null) {
                String parentNodeName = p_node.getParentNode().getNodeName().toLowerCase();
                String grandNodeName = p_node.getParentNode().getParentNode().getNodeName().toLowerCase();

                if (grandNodeName.equals("alt-trans") && parentNodeName.equals("target")) {
                    if (tdaResult != null) {
                        tdaResult.setResultText(p_node.getNodeValue());
                    }
                } else if (grandNodeName.equals("alt-trans") && parentNodeName.equals("source")) {
                    if (tdaResult != null) {
                        tdaResult.setSourceText(p_node.getNodeValue());
                    }
                }
            }

            p_node = p_node.getNextSibling();
            break;
        }
    }
}

From source file:com.francelabs.datafari.servlets.admin.FieldWeight.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response) Checks if the files still exist Used to modify the weight of
 *      a field//from   www  .  jav a 2  s  .  c  o  m
 */
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    try {
        if ((config == null) || !new File(env + File.separator + "solrconfig.xml").exists()) {// If
            // the
            // files
            // did
            // not
            // existed
            // when
            // the
            // constructor
            // was
            // runned
            if (!new File(env + File.separator + "solrconfig.xml").exists()) {
                LOGGER.error(
                        "Error while opening the configuration file, solrconfig.xml, in FieldWeight doPost, please make sure this file exists at "
                                + env + "conf/ . Error 69029"); // If
                // not
                // an
                // error
                // is
                // printed
                final PrintWriter out = response.getWriter();
                out.append(
                        "Error while opening the configuration file, please retry, if the problem persists contact your system administrator. Error Code : 69029");
                out.close();
                return;
            } else {
                config = new File(env + File.separator + "solrconfig.xml");
            }
        }

        if (customSearchHandler == null) {
            if (new File(
                    env + File.separator + "customs_solrconfig" + File.separator + "custom_search_handler.incl")
                            .exists()) {
                customSearchHandler = new File(env + File.separator + "customs_solrconfig" + File.separator
                        + "custom_search_handler.incl");
            }
        }

        try {
            final String type = request.getParameter("type");

            if (searchHandler == null) {
                findSearchHandler();
            }

            if (!usingCustom) { // The custom search handler is not used.
                // That means that the current config must
                // be commented in the solrconfig.xml file
                // and the modifications must be saved in
                // the custom search handler file

                // Get the content of solrconfig.xml file as a string
                String configContent = FileUtils.getFileContent(config);

                // Retrieve the searchHandler from the configContent
                final Node originalSearchHandler = XMLUtils.getSearchHandlerNode(config);
                final String strSearchHandler = XMLUtils.nodeToString(originalSearchHandler);

                // Create a commented equivalent of the strSearchHandler
                final String commentedSearchHandler = "<!--" + strSearchHandler + "-->";

                // Replace the searchHandler in the solrconfig.xml file by
                // the commented version
                configContent = configContent.replace(strSearchHandler, commentedSearchHandler);
                FileUtils.saveStringToFile(config, configContent);

                // create the new custom_search_handler document
                doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

                // Import the search handler node from the solrconfig doc to
                // the custom search handler doc
                searchHandler = doc.importNode(searchHandler, true);

                // Make the new node an actual item in the target document
                searchHandler = doc.appendChild(searchHandler);

                final Node n = run(searchHandler.getChildNodes(), type);
                childList = n.getParentNode().getChildNodes();

                // Save the custom_search_handler.incl file
                XMLUtils.docToFile(doc, customSearchHandler);
            }

            if (childList == null) {
                final Node n = run(searchHandler.getChildNodes(), type);
                childList = n.getParentNode().getChildNodes();
            }

            for (int i = 0; i < childList.getLength(); i++) { // Get the str
                // node
                final Node n = childList.item(i);
                if (n.getNodeName().equals("str")) {
                    String name = ""; // Get it's attributes
                    final NamedNodeMap map = n.getAttributes();
                    for (int j = 0; j < map.getLength(); j++) {
                        if (map.item(j).getNodeName().equals("name")) {// Get
                            // the
                            // name
                            name = map.item(j).getNodeValue();
                        }
                    }
                    if (name.equals(type)) { // If it's pf or qf according
                        // to what the user selected
                        // Get the parameters
                        final String field = request.getParameter("field").toString();
                        final String value = request.getParameter("value").toString();
                        final String text = n.getTextContent(); // Get the
                        // value of
                        // the node,
                        // Search for the requested field, if it is there
                        // return the weight, if not return 0
                        final int index = text.indexOf(field + "^");
                        if (index != -1) { // If the field is already
                            // weighted
                            final int pas = field.length() + 1;
                            final String textCut = text.substring(index + pas);
                            if (value.equals("0")) { // If the user entered
                                // 0
                                if (textCut.indexOf(" ") == -1) {
                                    // field is
                                    // the last
                                    // one then
                                    // we just
                                    // cut the
                                    // end of
                                    // the text
                                    // content
                                    n.setTextContent((text.substring(0, index)).trim());
                                } else {
                                    // the field and the part after
                                    n.setTextContent((text.substring(0, index)
                                            + text.substring(index + pas + textCut.indexOf(" "))).trim());
                                }
                            } else { // If the user typed any other values
                                if (textCut.indexOf(" ") == -1) {
                                    n.setTextContent(text.substring(0, index + pas) + value);
                                } else {
                                    n.setTextContent(text.substring(0, index + pas) + value
                                            + text.substring(index + pas + textCut.indexOf(" ")));
                                }
                            }
                        } else { // If it's not weighted
                            if (!value.equals("0")) {
                                // append the field and
                                // it's value
                                n.setTextContent((n.getTextContent() + " " + field + "^" + value).trim());
                            }
                        }
                        break;
                    }
                }
            }
            // Apply the modifications
            final TransformerFactory transformerFactory = TransformerFactory.newInstance();
            final Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            final DOMSource source = new DOMSource(searchHandler);
            final StreamResult result = new StreamResult(customSearchHandler);
            transformer.transform(source, result);

        } catch (final TransformerException e) {
            LOGGER.error(
                    "Error while modifying the solrconfig.xml, in FieldWeight doPost, pls make sure the file is valid. Error 69030",
                    e);
            final PrintWriter out = response.getWriter();
            out.append(
                    "Error while modifying the config file, please retry, if the problem persists contact your system administrator. Error Code : 69030");
            out.close();
            return;
        }

    } catch (final Exception e) {
        final PrintWriter out = response.getWriter();
        out.append(
                "Something bad happened, please retry, if the problem persists contact your system administrator. Error code : 69511");
        out.close();
        LOGGER.error("Unindentified error in FieldWeight doPost. Error 69511", e);
    }
}

From source file:it.unibo.alchemist.language.EnvironmentBuilder.java

private it.unibo.alchemist.model.interfaces.Node<T> buildNode(final Node rootNode,
        final Map<String, Object> env) throws InstantiationException, IllegalAccessException,
        InvocationTargetException, ClassNotFoundException {
    final NamedNodeMap attributes = rootNode.getAttributes();
    final Node nameNode = attributes.getNamedItem(NAME);
    final String name = nameNode == null ? "" : nameNode.getNodeValue();
    String type = attributes.getNamedItem(TYPE).getNodeValue();
    type = type.contains(".") ? type : "it.unibo.alchemist.model.implementations.nodes." + type;
    final it.unibo.alchemist.model.interfaces.Node<T> res = coreOperations(env, rootNode, type, random);
    if (res == null) {
        L.error("Failed to build " + type);
    }//from   ww  w  .ja v  a  2  s  . co  m
    env.put(name, res);
    env.put("NODE", res);
    final NodeList children = rootNode.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        final Node son = children.item(i);
        final String kind = son.getNodeName();
        if (!kind.equals(TEXT)) {
            final Node sonNameAttr = son.getAttributes().getNamedItem(NAME);
            final String sonName = sonNameAttr == null ? "" : sonNameAttr.getNodeValue();
            String objType = null;
            Object sonInstance = null;
            if (kind.equals("condition")) {
                final Condition<T> cond = buildCondition(son, env);
                sonInstance = cond;
                objType = "CONDITION";
            } else if (kind.equals("action")) {
                final Action<T> act = buildAction(son, env);
                sonInstance = act;
                objType = "ACTION";
            } else if (kind.equals("content")) {
                final NamedNodeMap moleculesMap = son.getAttributes();
                for (int j = 0; j < moleculesMap.getLength(); j++) {
                    final Node molNode = moleculesMap.item(j);
                    final String molName = molNode.getNodeName();
                    L.debug("checking molecule " + molName);
                    if (env.containsKey(molName)) {
                        L.debug(molName + " found");
                        final Object molObj = env.get(molName);
                        if (molObj instanceof Molecule) {
                            L.debug(molName + " matches in environment");
                            final Molecule mol = (Molecule) molObj;
                            final T conc = buildConcentration(molNode, env);
                            L.debug(molName + " concentration: " + conc);
                            sonInstance = conc;
                            res.setConcentration(mol, conc);
                        } else {
                            L.warn(molObj + "(class " + molObj.getClass().getCanonicalName()
                                    + " is not subclass of Molecule!");
                        }
                    } else {
                        L.warn("molecule " + molName + " is not yet defined.");
                    }
                }
            } else if (kind.equals("reaction")) {
                final Reaction<T> reaction = buildReaction(son, env);
                res.addReaction(reaction);
                sonInstance = reaction;
                objType = "REACTION";
            } else if (kind.equals("time")) {
                sonInstance = buildTime(son, env);
            } else if (kind.equals("timedistribution")) {
                sonInstance = buildTimeDist(son, env);
                objType = "TIMEDIST";
            }
            updateEnv(sonName, objType, sonInstance, env);
        }
    }
    env.remove(name);
    env.remove("NODE");
    return res;
}

From source file:com.github.zhanhb.ckfinder.connector.support.XmlConfigurationParser.java

/**
 * Creates plugin data from configuration file.
 *
 * @param element XML plugin node./*ww  w. j  a  va2s. com*/
 * @return PluginInfo data
 */
private PluginInfo createPluginFromNode(Node element) {
    PluginInfo.Builder builder = PluginInfo.builder();
    NodeList list = element.getChildNodes();
    for (int i = 0, l = list.getLength(); i < l; i++) {
        Node childElem = list.item(i);
        String nodeName = childElem.getNodeName();
        String textContent = nullNodeToString(childElem);
        switch (nodeName) {
        case "name":
            builder.name(textContent);
            break;
        case "params":
            NodeList paramLlist = childElem.getChildNodes();
            for (int j = 0, m = paramLlist.getLength(); j < m; j++) {
                Node node = paramLlist.item(j);
                if ("param".equals(node.getNodeName())) {
                    NamedNodeMap map = node.getAttributes();
                    String name = null;
                    String value = null;
                    for (int k = 0, o = map.getLength(); k < o; k++) {
                        Node item = map.item(k);
                        String nodeName1 = item.getNodeName();
                        if ("name".equals(nodeName1)) {
                            name = nullNodeToString(item);
                        } else if ("value".equals(nodeName1)) {
                            value = nullNodeToString(item);
                        }
                    }
                    builder.param(name, value);
                }
            }
            break;
        }
    }
    return builder.build();
}

From source file:XMLConfig.java

private void getMultipleAddAttributesHelper(String path, Node n, List<Node> accum) {
    if ((path.indexOf('.') > -1) || (path.indexOf('/') > -1)) {
        throw new XMLConfigException(
                "An attribute cannot have subparts (foo.bar.fum and foo.bar/fum not allowed)");
    }/*from   w ww  .j a va 2 s.  c o m*/
    NamedNodeMap attrMap = n.getAttributes();
    if (path.equals("*")) {
        for (int i = 0; i < attrMap.getLength(); ++i) {
            Node attr = attrMap.item(i);
            accum.add(attr);
        }
    } else {
        Node attr = attrMap.getNamedItem(path);
        if (attr != null) {
            accum.add(attr);
        }
    }
}

From source file:com.krawler.workflow.bizservice.WorkflowServiceImpl.java

private void getGraphicsNodeInfo(Node node, ObjectInfo obj) {
    String name = "";
    NamedNodeMap attribute = node.getAttributes();
    for (int b = 0; b < attribute.getLength(); b++) {
        Node attribute1 = attribute.item(b);
        name = attribute1.getNodeName();
        if (name.compareToIgnoreCase("Height") == 0) {
            obj.height = attribute1.getNodeValue();
        } else if (name.compareToIgnoreCase("Width") == 0) {
            obj.width = attribute1.getNodeValue();
        }//from   w  w w.j  a  v a  2 s  . c o  m
    }
    NodeList innerchildren = node.getChildNodes();
    for (int c = 0; c < innerchildren.getLength(); c++) {
        Node cordinateNode = innerchildren.item(c);
        if (cordinateNode.getNodeType() == Node.ELEMENT_NODE) {
            NamedNodeMap attr = cordinateNode.getAttributes();
            for (int b = 0; b < attr.getLength(); b++) {
                Node attribute1 = attr.item(b);
                name = attribute1.getNodeName();
                if (name.compareToIgnoreCase("XCoordinate") == 0) {
                    obj.xpos = attribute1.getNodeValue();
                } else if (name.compareToIgnoreCase("YCoordinate") == 0) {
                    obj.ypos = attribute1.getNodeValue();
                }
            }
        }
    }
}

From source file:DOMProcessor.java

/** Searches the given node for a given attribute and returns the value associated with it.
  * This version does not recurse to children of the given node.
  * @param attributeName Attribute to search for.
  * @param node Node from which to start search.
  * @return Value associated with the attribute, or null if not found.  
  *//*from   w  w  w  .j a va  2  s .  c o  m*/
public String getNodeAttribute(String attributeName, Node node) {
    // Only consider document or element nodes.
    if ((node.getNodeType() != Node.DOCUMENT_NODE) && (node.getNodeType() != Node.ELEMENT_NODE)) {
        return null;
    }

    // Search attributes associated with the node.
    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        if (attribute.getNodeName().equalsIgnoreCase(attributeName)) {
            return attribute.getNodeValue();
        }
    }

    // If we get this far, the attribute has not been found.
    return null;
}

From source file:com.krawler.workflow.bizservice.WorkflowServiceImpl.java

private void getNodeInfo(Node node, ObjectInfo obj) {
    int a;/*from  w  w  w .j  av  a  2s.c  om*/
    String name = "";
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        NamedNodeMap attributes = node.getAttributes();
        for (a = 0; a < attributes.getLength(); a++) {
            Node attribute = attributes.item(a);
            name = attribute.getNodeName();
            if (name.compareToIgnoreCase("Id") == 0) {
                obj.objId = attribute.getNodeValue();
            } else if (name.compareToIgnoreCase("Name") == 0) {
                obj.name = attribute.getNodeValue();
            } else if (name.compareToIgnoreCase("Parent") == 0) {
                obj.parentId = attribute.getNodeValue();
            } else if (name.compareToIgnoreCase("ParentPool") == 0) {
                obj.domEl = attribute.getNodeValue();
            } else if (name.compareToIgnoreCase("refId") == 0) {
                obj.refId = attribute.getNodeValue();
            } else if (name.compareToIgnoreCase("hasStart") == 0) {
                obj.hasStart = attribute.getNodeValue();
            } else if (name.compareToIgnoreCase("hasEnd") == 0) {
                obj.hasEnd = attribute.getNodeValue();
            } else if (name.compareToIgnoreCase("startRefId") == 0) {
                obj.startRefId = attribute.getNodeValue();
            } else if (name.compareToIgnoreCase("endRefId") == 0) {
                obj.endRefId = attribute.getNodeValue();
            } else if (name.compareToIgnoreCase("derivationRule") == 0) {
                obj.derivationRule = attribute.getNodeValue();
            } else if (name.compareToIgnoreCase("domEl") == 0) {
                obj.domEl = attribute.getNodeValue();
            }

        }
    }
}

From source file:DOMProcessor.java

/** Searches for a given attribute in the given node and updates list
  * of attribute values. Recursively searches for sub-nodes of the given one.
  * @param element Element to search for.
  * @param node Node to start search from.
  *///www.ja va 2 s  . c o  m
private void searchAttributes(String element, Node node) {
    // Only consider document or element nodes.
    if ((node.getNodeType() != Node.DOCUMENT_NODE) && (node.getNodeType() != Node.ELEMENT_NODE)) {
        return;
    }

    // Search attributes associated with current node.
    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        if (attribute.getNodeName().equalsIgnoreCase(element)) {
            //matches.add(attribute.getNodeValue());
            matches.add(attribute);
        }
    }

    // Search child nodes.
    NodeList children = node.getChildNodes();

    for (int i = 0; i < children.getLength(); i++) {
        searchAttributes(element, children.item(i));
    }
}