Example usage for org.w3c.dom Node getParentNode

List of usage examples for org.w3c.dom Node getParentNode

Introduction

In this page you can find the example usage for org.w3c.dom Node getParentNode.

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:com.taobao.ad.easyschedule.security.ActionSecurityBean.java

/**
 * ???//from   w  ww  .ja  va  2 s.c  o m
 * 
 * @return
 * @throws Exception
 */
private List<MenuItem> readMenuFromFile() throws Exception {
    List<MenuItem> tmpMenu;
    Map<Long, Module> tmpModuleIndex;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document dom = db.parse(new InputSource(new InputStreamReader(xml.getInputStream(), encoding)));
        NodeList items = dom.getElementsByTagName("item");
        tmpMenu = new LinkedList<MenuItem>();
        tmpModuleIndex = new HashMap<Long, Module>();
        MenuItem currentTopMenu = null;
        for (int i = 0; i < items.getLength(); i++) {
            Node item = items.item(i);
            String name = item.getAttributes().getNamedItem("name").getNodeValue();
            String link = "#";
            if (item.getAttributes().getNamedItem("link") != null)
                link = item.getAttributes().getNamedItem("link").getNodeValue();
            Node parent = item.getParentNode();
            if ("menu".equals(parent.getNodeName())) {
                currentTopMenu = new MenuItem(name, link);
                tmpMenu.add(currentTopMenu);
            } else if ("item".equals(parent.getNodeName())) {
                MenuItem subMenu = new MenuItem(name);
                currentTopMenu.addSubItem(subMenu); // add the sub node to
                // parent node
                if (item.getAttributes().getNamedItem("link") != null)
                    subMenu.link = item.getAttributes().getNamedItem("link").getNodeValue();
                if (item.getAttributes().getNamedItem("target") != null)
                    subMenu.target = item.getAttributes().getNamedItem("target").getNodeValue();
                if (item.getAttributes().getNamedItem("state") != null) {
                    if ("show".equalsIgnoreCase(item.getAttributes().getNamedItem("state").getNodeValue())) {
                        subMenu.state = 1;
                    } else if ("hide"
                            .equalsIgnoreCase(item.getAttributes().getNamedItem("state").getNodeValue())) {
                        subMenu.state = -1;
                    }
                }

                setModules(subMenu, item, tmpModuleIndex);
            }
        }
    } catch (Exception e) {
        throw e;
    }
    this.moduleIndex = tmpModuleIndex;
    return tmpMenu;
}

From source file:org.opengeoportal.proxy.controllers.DynamicOgcController.java

private String extractWmsLayerNodes(Document xmlDocument, Set<String> nameList) throws Exception {
    String featureTypeInfo = "";
    NodeList layerNodeList = xmlDocument.getElementsByTagName("Name");
    if (layerNodeList.getLength() == 0) {
        throw new Exception("Malformed GetCapabilities Document.");
    }//from w  w  w  . j  a  v a  2  s.  co m

    for (int j = 0; j < layerNodeList.getLength(); j++) {
        Node currentLayerNode = layerNodeList.item(j);
        if (currentLayerNode.getParentNode().getNodeName().equals("Layer")) {
            String layerName = currentLayerNode.getTextContent().toLowerCase();

            if (OgpUtils.getSetAsLowerCase(nameList).contains(layerName)) {
                featureTypeInfo += xmlToString(currentLayerNode.getParentNode());
            }

        }
    }

    return featureTypeInfo;
}

From source file:DOMProcessor.java

/** Adds the given comment to the given node.
  * @param comment Comment text./*from   w w  w  .j ava  2 s .co m*/
  * @param node Element to attach comment.
  */
public void addComment(String comment, Node node) {
    node.getParentNode().insertBefore(dom.createComment(comment), node);
}

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   w  ww . j a v  a  2s . c om
 */
@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:org.alfresco.web.config.WebConfigRuntime.java

/**
 * @param parent//from   www  .  ja  v  a  2s. c o  m
 * @param child
 */
private void appendChild(Node parent, Node child) {
    parent.appendChild(child);
    Node previousNode = child.getPreviousSibling();
    if (previousNode != null && previousNode instanceof org.w3c.dom.Text) {
        previousNode.getParentNode().removeChild(previousNode);
    }
}

From source file:com.autentia.mvn.plugin.changes.BugzillaChangesMojo.java

/**
 * Removes the nodes from document/*ww  w.  j  av a2  s .  com*/
 * 
 * @param nodeList
 */
private void removeNodes(final NodeList nodeList) {
    for (int i = 0; i < nodeList.getLength(); i++) {
        final Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
        // hay que quitarle uno debido a la implementacin del
        // borrado que tambin elimina del nodelist
        i--;
    }
}

From source file:com.zimbra.common.util.QuotedTextUtil.java

/**
 * Removes all subsequent siblings of the given node, and then does the same
 * for its parent. The effect is that all nodes that come after the given
 * node in a depth-first traversal of the DOM will be removed.
 *
 * @param node/*  w ww .  ja v a2 s . c o  m*/
 * @param clipNode if true, also remove the node
 */
private void prune(Node node, boolean clipNode) {
    Node tempNode = null;
    if (node != null && node.getParentNode() != null) {
        tempNode = node.getParentNode();

        // clip all subsequent nodes
        while (tempNode.getLastChild() != null && tempNode.getLastChild() != node) {
            tempNode.removeChild(tempNode.getLastChild());
        }
        // clip the node if asked
        if (clipNode && tempNode.getLastChild() != null && tempNode.getLastChild() == node) {
            tempNode.removeChild(tempNode.getLastChild());
        }

        String nodeName = tempNode.getNodeName() != null ? tempNode.getNodeName() : "";

        if (!nodeName.equals("body") && !nodeName.equals("html")) {
            prune(tempNode, false);
        }
    }

}

From source file:edu.virginia.speclab.juxta.author.model.JuxtaXMLParser.java

private static String nodeToSimpleXPath(Node node, Node root) {
    // recursion ahoy
    if (node == null)
        return "";

    // need to get my index by looping through previous siblings for nodes with the same name as me
    Node sibling = node.getPreviousSibling();
    int index = 1;
    while (sibling != null) {
        if (sibling.getNodeType() == node.getNodeType() && sibling.getNodeName().equals(node.getNodeName()))
            index++;//from w w  w  .  ja  v  a 2s.  c o m
        sibling = sibling.getPreviousSibling();
    }

    String path = "/" + node.getNodeName();
    if (!node.isSameNode(root))
        path = path + "[" + index + "]";
    else
        return path;

    // If we've picked anything other than an element node, ignore it, and walk up
    // the tree for other things. We get this when someone asks for /blah/blah/text() or something,
    // which we don't support.
    if (node.getNodeType() != Node.ELEMENT_NODE)
        path = "";

    return (nodeToSimpleXPath(node.getParentNode(), root) + path);
}

From source file:DomPrintUtil.java

private Node getVisibleParent(Node target) {
    if (target == walkerRoot) {
        return null;
    }/*from   w  w w .  jav  a2 s. c o m*/
    Node tmpN = target.getParentNode();
    if (null == tmpN) {
        return null;
    }
    switch (eval(tmpN)) {
    case NodeFilter.FILTER_ACCEPT:
        return tmpN;
    // case NodeFilter.FILTER_SKIP:
    // case NodeFilter.FILTER_REJECT:
    default:
        return getVisibleParent(tmpN);
    }
}

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

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response) Used to free a semaphore on an other select without any
 *      confirl Checks if the files still exist Gets the list of the fields
 *      Gets the weight of a field in a type of query
 *///from  w  ww.ja v  a 2 s . c  o  m
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    final PrintWriter out = response.getWriter();
    usingCustom = false; // Reinit the usingCustom value to false in order
    // to check again if the
    // custom_search_handler.xml file is used

    try {
        if (request.getParameter("sem") != null) { // If it's called just to
            // clean the semaphore
            return;
        }
        if ((config == null) || !new File(env + "/solrconfig.xml").exists()) {// If
            // the
            // files
            // did
            // not
            // existed
            // when
            // the
            // constructor
            // was
            // run
            // Checks if they exist now
            if (!new File(env + "/solrconfig.xml").exists()) {
                LOGGER.error(
                        "Error while opening the configuration files, solrconfig.xml and/or schema.xml, in FieldWeight doGet, please make sure those files exist at "
                                + env + " . Error 69025"); // If
                // not
                // an
                // error
                // is
                // printed
                out.append(
                        "Error while opening the configuration files, please retry, if the problem persists contact your system administrator. Error Code : 69025");
                out.close();
                return;
            } else {
                config = new File(env + "/solrconfig.xml");
            }
        }

        if (customFields == null) {
            if (new File(env + "/customs_schema/custom_fields.incl").exists()) {
                customFields = new File(env + "/customs_schema/custom_fields.incl");
            }
        }

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

        if (request.getParameter("type") == null) { // If called at the
            // creation of the HTML
            // ==> retrieve the
            // fields list

            try {
                // Define the Solr hostname, port and protocol
                final String solrserver = "localhost";
                final String solrport = "8983";
                final String protocol = "http";

                // Use Solr Schema REST API to get the list of fields
                final HttpClient httpClient = HttpClientBuilder.create().build();
                final HttpHost httpHost = new HttpHost(solrserver, Integer.parseInt(solrport), protocol);
                final HttpGet httpGet = new HttpGet("/solr/FileShare/schema/fields");
                final HttpResponse httpResponse = httpClient.execute(httpHost, httpGet);

                // Construct the jsonResponse
                final JSONObject jsonResponse = new JSONObject();
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    // Status of the API response is OK
                    final JSONObject json = new JSONObject(EntityUtils.toString(httpResponse.getEntity()));
                    final JSONArray fieldsJson = json.getJSONArray("fields");
                    jsonResponse.put("field", fieldsJson);

                    response.getWriter().write(jsonResponse.toString()); // Answer
                    // to
                    // the
                    // request
                    response.setStatus(200);
                    response.setContentType("text/json;charset=UTF-8");
                } else {
                    // Status of the API response is an error
                    LOGGER.error("Error while retrieving the fields from the Schema API of Solr: "
                            + httpResponse.getStatusLine().toString());
                    out.append(
                            "Error while retrieving the fields from the Schema API of Solr, please retry, if the problem persists contact your system administrator. Error Code : 69026");
                }
                out.close();
            } catch (final IOException e) {
                LOGGER.error("Error while retrieving the fields from the Schema API of Solr", e);
                out.append(
                        "Error while retrieving the fields from the Schema API of Solr, please retry, if the problem persists contact your system administrator. Error Code : 69026");
                out.close();
            }

        } else { // If the weight of a field has been requested

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

                // if (searchHandler == null && customSearchHandler != null
                // && customSearchHandler.exists()) { // search
                // // handler
                // // not
                // // found
                // // in
                // // the
                // // standard solrconfig.xml find, try
                // // to find it in the
                // // custom_search_handler.xml file
                // usingCustom = true;
                // doc = dBuilder.parse(customSearchHandler);
                // searchHandler =
                // getSearchHandler(doc.getElementsByTagName("requestHandler"));
                // }

                if (searchHandler != null) {
                    final Node n = run(searchHandler.getChildNodes(), type);
                    childList = n.getParentNode().getChildNodes();
                    final String elemValue = n.getTextContent(); // Get the
                    // text
                    // content
                    // of
                    // the
                    // node
                    int index = elemValue.indexOf(field + "^");
                    if (index != -1) { // If the field is weighted
                        index += field.length() + 1; // Gets the number of
                        // the
                        // char that is the
                        // first figure of
                        // the
                        // number
                        final String elemValueCut = elemValue.substring(index);// Get
                        // the
                        // text
                        // content
                        // cutting
                        // everything
                        // before
                        // the
                        // requested
                        // field
                        if (elemValueCut.indexOf(" ") != -1) {
                            // the
                            // last
                            // field,
                            // returns
                            // what's
                            // between
                            // the
                            // "^" and
                            // the
                            // next
                            // whitespace
                            response.getWriter()
                                    .write(elemValue.substring(index, index + elemValueCut.indexOf(" ")));
                        } else {
                            // that
                            // is after the "field^"
                            response.getWriter().write(elemValue.substring(index));
                        }
                    } else {
                        response.getWriter().write("0");
                    }
                    response.setStatus(200);
                    response.setContentType("text;charset=UTF-8");
                    return;
                } else {
                    LOGGER.error(
                            "No searchHandler found either in solrconfig.xml or in custom_search_handler.xml ! Make sure your files are valid. Error 69028");
                    out.append(
                            "Something bad happened, please retry, if the problem persists contact your system administrator. Error code : 69028");
                    out.close();
                    return;
                }
            } catch (SAXException | ParserConfigurationException e) {
                LOGGER.error(
                        "Error while parsing the solrconfig.xml, in FieldWeight doGet, make sure the file is valid. Error 69028",
                        e);
                out.append(
                        "Something bad happened, please retry, if the problem persists contact your system administrator. Error code : 69028");
                out.close();
                return;
            }
        }
    } catch (final Exception e) {
        out.append(
                "Something bad happened, please retry, if the problem persists contact your system administrator. Error code : 69510");
        out.close();
        LOGGER.error("Unindentified error in FieldWeight doGet. Error 69510", e);
    }
}