Example usage for org.w3c.dom Element getParentNode

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

Introduction

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

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:org.commonjava.maven.galley.maven.parse.XMLInfrastructure.java

private String getChildText(final String name, final Element parent) {
    final NodeList nl = parent.getElementsByTagName(name);
    if (nl == null || nl.getLength() < 1) {
        logger.debug("No element: {} in: {}", name, parent.getNodeName());
        return null;
    }/*from  w w  w.ja v  a2  s  .  co  m*/

    Element elem = null;
    for (int i = 0; i < nl.getLength(); i++) {
        final Element e = (Element) nl.item(i);
        if (e.getParentNode() == parent) {
            elem = e;
            break;
        }
    }

    return elem == null ? null : elem.getTextContent().trim();
}

From source file:org.devgateway.eudevfin.reports.core.utils.ReportTemplate.java

private void appendReportSumRows(HashMap<String, Node> matchingRows, HashMap<String, Node> matchingColumns,
        RowReport row, Document doc, boolean swapAxis) {
    Node rowNode = matchingRows.get("r_" + row.getName());

    if (rowNode == null)
        return;//from w  w w . j av  a  2  s  . c om
    HashMap<String, String> columns = new HashMap<String, String>();
    HashMap<String, String> emptyColumns = new HashMap<String, String>();

    XPath xPath = XPathFactory.newInstance().newXPath();

    for (String rowCode : row.getRowCodes()) {
        try {
            NodeList nodes = (NodeList) xPath
                    .evaluate("/jasperReport/detail/band/textField/reportElement[starts-with(@key, 'r_"
                            + rowCode + "_c_')]", doc.getDocumentElement(), XPathConstants.NODESET);
            for (int i = 0; i < nodes.getLength(); ++i) {
                Element e = (Element) nodes.item(i);
                String columnKey = e.getAttribute("key");
                String columnCode = columnKey.replaceFirst("r_" + rowCode + "_c_", "");
                String expression = columns.get(columnCode) != null ? columns.get(columnCode) : "";
                if (!e.getParentNode().getTextContent().equals("")) {
                    expression += e.getParentNode().getTextContent();
                    expression += "+";
                }
                columns.put(columnCode, expression);
            }
            NodeList nodesEmpty = (NodeList) xPath
                    .evaluate("/jasperReport/detail/band/staticText/reportElement[starts-with(@key, 'r_"
                            + rowCode + "_c_')]", doc.getDocumentElement(), XPathConstants.NODESET);
            for (int i = 0; i < nodesEmpty.getLength(); ++i) {
                Element e = (Element) nodesEmpty.item(i);
                String columnKey = e.getAttribute("key");
                String columnCode = columnKey.replaceFirst("r_" + rowCode + "_c_", "");
                String expression = columns.get(columnCode) != null ? columns.get(columnCode) : "";
                if (!e.getParentNode().getTextContent().equals("")) {
                    expression += e.getParentNode().getTextContent();
                    expression += "+";
                }
                emptyColumns.put(columnCode, expression);
            }
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    }

    Integer yCoord, xCoord, width, height;
    xCoord = yCoord = 0;
    //Set default height
    height = 15;
    //Set default width
    width = 55;
    if (swapAxis) {
        xCoord = rowNode.getAttributes().getNamedItem("x") != null
                ? Integer.parseInt(rowNode.getAttributes().getNamedItem("x").getNodeValue())
                : 0;
    } else {
        yCoord = rowNode.getAttributes().getNamedItem("y") != null
                ? Integer.parseInt(rowNode.getAttributes().getNamedItem("y").getNodeValue())
                : 0;
    }

    for (Map.Entry<String, String> column : columns.entrySet()) {
        String cellStyle = (rowNode.getAttributes().getNamedItem("style") != null)
                ? rowNode.getAttributes().getNamedItem("style").getNodeValue()
                : "";
        Element textField = doc.createElement("textField");
        textField.setAttribute("pattern", "#,##0.00");
        Node columnNode = matchingColumns.get("c_" + column.getKey());
        if (columnNode == null)
            continue;
        Node parentNode;
        if (swapAxis) {
            parentNode = columnNode.getParentNode().getParentNode();
            yCoord = columnNode.getAttributes().getNamedItem("y") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("y").getNodeValue())
                    : 0;
        } else {
            parentNode = rowNode.getParentNode().getParentNode();
            xCoord = columnNode.getAttributes().getNamedItem("x") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("x").getNodeValue())
                    : 0;
            width = columnNode.getAttributes().getNamedItem("width") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("width").getNodeValue())
                    : 0;
            height = rowNode.getAttributes().getNamedItem("height") != null
                    ? Integer.parseInt(rowNode.getAttributes().getNamedItem("height").getNodeValue())
                    : 0;
            if (cellStyle.equals("") && (columnNode.getAttributes().getNamedItem("style") != null)) {
                cellStyle = columnNode.getAttributes().getNamedItem("style").getNodeValue();
            }

        }
        Element reportElement = doc.createElement("reportElement");
        reportElement.setAttribute("key", "r_" + row.getName() + "_c_" + column.getKey());
        reportElement.setAttribute("x", xCoord.toString());
        reportElement.setAttribute("y", yCoord.toString());
        reportElement.setAttribute("width", width.toString());
        reportElement.setAttribute("height", height.toString());

        if (!cellStyle.equals("")) {
            reportElement.setAttribute("style", cellStyle);
        }

        Element textElement = doc.createElement("textElement");
        textElement.setAttribute("textAlignment", "Right");

        Element textFieldExpression = doc.createElement("textFieldExpression");
        String columnValue = column.getValue();
        if (columnValue.endsWith("+")) {
            columnValue = columnValue.substring(0, columnValue.length() - 1);
        }
        CDATASection cdata = doc.createCDATASection(columnValue);

        textFieldExpression.appendChild(cdata);
        textField.appendChild(reportElement);
        textField.appendChild(textElement);
        textField.appendChild(textFieldExpression);
        parentNode.appendChild(textField);

    }

    for (Map.Entry<String, String> column : emptyColumns.entrySet()) {
        if (columns.containsKey(column.getKey())) {
            continue;
        }
        String cellStyle = (rowNode.getAttributes().getNamedItem("style") != null)
                ? rowNode.getAttributes().getNamedItem("style").getNodeValue()
                : "";
        Element staticText = doc.createElement("staticText");
        Node columnNode = matchingColumns.get("c_" + column.getKey());
        if (columnNode == null)
            continue;
        Node parentNode;
        if (swapAxis) {
            parentNode = columnNode.getParentNode().getParentNode();
            yCoord = columnNode.getAttributes().getNamedItem("y") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("y").getNodeValue())
                    : 0;
        } else {
            parentNode = rowNode.getParentNode().getParentNode();
            xCoord = columnNode.getAttributes().getNamedItem("x") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("x").getNodeValue())
                    : 0;
            width = columnNode.getAttributes().getNamedItem("width") != null
                    ? Integer.parseInt(columnNode.getAttributes().getNamedItem("width").getNodeValue())
                    : 0;
            height = rowNode.getAttributes().getNamedItem("height") != null
                    ? Integer.parseInt(rowNode.getAttributes().getNamedItem("height").getNodeValue())
                    : 0;
            if (cellStyle.equals("") && (columnNode.getAttributes().getNamedItem("style") != null)) {
                cellStyle = columnNode.getAttributes().getNamedItem("style").getNodeValue();
            }

        }
        Element reportElement = doc.createElement("reportElement");
        reportElement.setAttribute("key", "r_" + row.getName() + "_c_" + column.getKey());
        reportElement.setAttribute("x", xCoord.toString());
        reportElement.setAttribute("y", yCoord.toString());
        reportElement.setAttribute("width", width.toString());
        reportElement.setAttribute("height", height.toString());

        if (!cellStyle.equals("")) {
            reportElement.setAttribute("style", cellStyle);
        }

        Element textElement = doc.createElement("textElement");
        textElement.setAttribute("textAlignment", "Right");

        Element textFieldExpression = doc.createElement("text");
        CDATASection cdata = doc.createCDATASection("////////");

        textFieldExpression.appendChild(cdata);
        staticText.appendChild(reportElement);
        staticText.appendChild(textElement);
        staticText.appendChild(textFieldExpression);
        parentNode.appendChild(staticText);

    }
}

From source file:org.dhatim.cdr.SmooksResourceConfiguration.java

/**
 * Is this resource configuration targeted at the specified DOM element
 * in context.//from  w  w w.j  a  va  2  s .  c o m
 * <p/>
 * See details about the "selector" attribute in the
 * <a href="#attribdefs">Attribute Definitions</a> section.
 * <p/>
 * Note this doesn't perform any namespace checking.
 *
 * @param element The element to check against.
 * @param executionContext
 * @return True if this resource configuration is targeted at the specified
 *         element in context, otherwise false.
 */
private boolean isTargetedAtElementContext(Element element, ExecutionContext executionContext) {
    Node currentNode = element;
    ContextIndex index = new ContextIndex(executionContext);

    index.i = selectorSteps.length - 1;

    // Unless it's **, start at the parent because the current element
    // has already been tested...
    if (!selectorSteps[index.i].isStarStar()) {
        index.i = selectorSteps.length - 2;
        currentNode = element.getParentNode();
    } else {
        // The target selector step is "**".  If the parent one is "#document" and we're at
        // the root now, then fail...
        if (selectorSteps.length == 2 && selectorSteps[0].isRooted() && element.getParentNode() == null) {
            return false;
        }
    }

    if (currentNode == null || currentNode.getNodeType() != Node.ELEMENT_NODE) {
        return false;
    }

    // Check the element name(s).
    while (index.i >= 0 && currentNode != null) {
        Element currentElement = (Element) currentNode;
        Node parentNode;

        parentNode = currentElement.getParentNode();
        if (parentNode == null || parentNode.getNodeType() != Node.ELEMENT_NODE) {
            parentNode = null;
        }

        if (!isTargetedAtElementContext(currentElement, (Element) parentNode, index)) {
            return false;
        }

        if (parentNode == null) {
            return true;
        }

        currentNode = parentNode;
    }

    return true;
}

From source file:org.dhatim.javabean.ext.WireOnElementChecker.java

private boolean isCreateOnElementSet(Element element) {
    return StringUtils.isNotEmpty(((Element) element.getParentNode()).getAttribute("createOnElement"));
}

From source file:org.dhatim.templating.AbstractTemplateProcessor.java

protected void processTemplateAction(Element element, NodeList templatingResultNodeList,
        ExecutionContext executionContext) {
    // If we're at the root element
    if (element.getParentNode() instanceof Document) {
        int count = templatingResultNodeList.getLength();

        // Iterate over the NodeList and filter the action using the
        // first element node we encounter as the transformation result...
        for (int i = 0; i < count; i++) {
            Node node = templatingResultNodeList.item(0);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                processTemplateAction(element, node, executionContext);
                break;
            }//  w  w  w  .ja v  a  2 s. com
        }
    } else if (action == Action.REPLACE) {
        // When we're not at the root element, REPLACE needs to be handled explicitly
        // by performing a series of insert-befores, followed by a remove of the
        // target element...
        processTemplateAction(element, templatingResultNodeList, Action.INSERT_BEFORE, executionContext);
        element.getParentNode().removeChild(element);
    } else {
        processTemplateAction(element, templatingResultNodeList, action, executionContext);
    }
}

From source file:org.dhatim.templating.AbstractTemplateProcessor.java

private void _processTemplateAction(Element element, Node node, Action action,
        ExecutionContext executionContext) {
    Node parent = element.getParentNode();

    // Can't insert before or after the root element...
    if (parent instanceof Document && (action == Action.INSERT_BEFORE || action == Action.INSERT_AFTER)) {
        logger.debug("Insert before/after root element not allowed.  Consider using the replace action!!");
        return;//from  w  w  w .  jav  a2s .  com
    }

    String outputStreamResourceName = getOutputStreamResource();
    if (outputStreamResourceName != null) {
        Writer writer = AbstractOutputStreamResource.getOutputWriter(outputStreamResourceName,
                executionContext);
        String text = extractTextContent(node, executionContext);
        try {
            writer.write(text);
        } catch (IOException e) {
            throw new SmooksException(
                    "Failed to write to output stream resource '" + outputStreamResourceName + "'.", e);
        }
    } else {
        if (action == Action.ADDTO) {
            element.appendChild(node);
        } else if (action == Action.INSERT_BEFORE) {
            DomUtils.insertBefore(node, element);
        } else if (action == Action.INSERT_AFTER) {
            Node nextSibling = element.getNextSibling();

            if (nextSibling == null) {
                // "element" is the last child of "parent" so just add to "parent".
                parent.appendChild(node);
            } else {
                // insert before the "nextSibling" - Node doesn't have an "insertAfter" operation!
                DomUtils.insertBefore(node, nextSibling);
            }
        } else if (action == Action.BIND_TO) {
            String text = extractTextContent(node, executionContext);

            executionContext.getBeanContext().addBean(bindBeanId, text, new Fragment(element));
        } else if (action == Action.REPLACE) {
            // Don't perform any "replace" actions here!
        }
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Remove the supplied element from its containing document.
 * <p/>/* www . j a va 2  s.  co  m*/
 * Tries to manage scenarios where a request is made to remove the root element.
 * Cannot remove the root element in any of the following situations:
 * <ul>
 *    <li>"keepChildren" parameter is false.</li>
 *    <li>root element is empty of {@link Node#ELEMENT_NODE} nodes.</li>
 * </ul>
 * @param element Element to be removed.
 * @param keepChildren Keep child content.
 */
public static void removeElement(Element element, boolean keepChildren) {
    AssertArgument.isNotNull(element, "element");

    Node parent = element.getParentNode();
    if (parent == null) {
        logger.debug("Cannot remove element [" + element + "]. [" + element + "] has no parent.");
        return;
    }

    NodeList children = element.getChildNodes();

    if (parent instanceof Document) {
        List childElements = null;

        if (!keepChildren) {
            logger.debug("Cannot remove document root element [" + DomUtils.getName(element)
                    + "] without keeping child content.");
        } else {
            if (children != null && children.getLength() > 0) {
                childElements = DomUtils.getElements(element, "*", null);
            }

            if (childElements != null && !childElements.isEmpty()) {
                parent.removeChild(element);
                parent.appendChild((Element) childElements.get(0));
            } else {
                logger.debug("Cannot remove empty document root element [" + DomUtils.getName(element) + "].");
            }
        }
    } else {
        if (keepChildren && children != null) {
            DomUtils.insertBefore(children, element);
        }
        parent.removeChild(element);
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Get the parent element of the supplied element having the
 * specified tag name.// w  w w  .  j av  a  2  s .c om
 * @param child Child element. 
 * @param parentLocalName Parent element local name.
 * @param namespaceURI Namespace URI of the required parent element,
 * or null if a non-namespaced get is to be performed.
 * @return The first parent element of "child" having the tagname "parentName",
 * or null if no such parent element exists.
 */
public static Element getParentElement(Element child, String parentLocalName, String namespaceURI) {
    AssertArgument.isNotNull(child, "child");
    AssertArgument.isNotNullAndNotEmpty(parentLocalName, "parentLocalName");

    Node parentNode = child.getParentNode();

    while (parentNode != null && parentNode.getNodeType() == Node.ELEMENT_NODE) {
        Element parentElement = (Element) parentNode;

        if (getName(parentElement).equalsIgnoreCase(parentLocalName)) {
            if (namespaceURI == null) {
                return parentElement;
            } else if (parentElement.getNamespaceURI().equals(namespaceURI)) {
                return parentElement;
            }
        }
        parentNode = parentNode.getParentNode();
    }

    return null;
}

From source file:org.directwebremoting.drapgen.generate.gi.GiType.java

/**
 * @param method/*  ww w.j  a  v a2s  .c o m*/
 */
private void removeMethod(GiMethod method) {
    Element element = method.getElement();

    Node parent = element.getParentNode();
    if (parent != null) {
        parent.removeChild(element);
    }
}

From source file:org.directwebremoting.drapgen.generate.gi.GiType.java

/**
 *
 *///from   ww  w.j a va2  s .c  om
private List<GiMethod> getImplementedMethods() {
    try {
        List<GiMethod> reply = new ArrayList<GiMethod>();

        // Find all the inherited functions, and trim the ones that are not
        // from super-classes - leaving the mixins
        NodeList nodelist = (NodeList) functionFinder.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < nodelist.getLength(); i++) {
            Element element = (Element) nodelist.item(i);
            if (element.getParentNode() == null) {
                log.debug("node without parent: " + element);
            }

            GiMethod method = new GiMethod(element, getClassName());
            reply.add(method);
        }

        return reply;
    } catch (XPathExpressionException ex) {
        throw new RuntimeException(ex);
    }
}