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.infoscoop.util.Xml2Json.java

public JSONObject xml2jsonObj(Element element) throws Exception {
    this.basePath = null;
    Node baseNode = element.getParentNode();
    if (baseNode != null && baseNode.getNodeType() == Node.ELEMENT_NODE)
        this.basePath = getXPath((Element) baseNode);
    JSONObject obj = (JSONObject) node2json(element);
    return obj;//  www.  java  2 s.c o  m
}

From source file:org.infoscoop.util.Xml2Json.java

private String getXPath(Element element) {
    if (element == null)
        return null;
    StringBuffer xpath = new StringBuffer();
    xpath.append("/");
    String uri = element.getNamespaceURI();
    String prefix = (String) namespaceResolvers.get(uri);
    if (prefix != null)
        xpath.append(prefix).append(":");
    xpath.append(getTagName(element));//from   ww w .ja  v a2  s .c om
    Element parent = element;
    try {
        while (true) {
            parent = (Element) parent.getParentNode();
            if (parent == null)
                break;
            xpath.insert(0, getTagName(parent));
            uri = parent.getNamespaceURI();
            prefix = (String) namespaceResolvers.get(uri);
            if (prefix != null)
                xpath.insert(0, prefix + ":");
            xpath.insert(0, "/");
        }
    } catch (ClassCastException e) {

    }
    String xpathStr = xpath.toString();
    if (this.basePath != null)
        xpathStr = xpathStr.replaceFirst("^" + this.basePath, "");
    return xpathStr;
}

From source file:org.jboss.tools.tycho.sitegenerator.GenerateRepositoryFacadeMojo.java

/**
 * Alter content.xml, content.jar, content.xml.xz to:
 * remove default "Uncategorized" category, 
 * remove 3rd party associate sites, and 
 * add associate sites defined in site's pom.xml
 *
 * @param p2repository//w w  w. ja  va  2  s.  com
 * @throws FileNotFoundException
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws TransformerFactoryConfigurationError
 * @throws TransformerConfigurationException
 * @throws TransformerException
 * @throws MojoFailureException
 */
private void alterContentJar(File p2repository) throws FileNotFoundException, IOException, SAXException,
        ParserConfigurationException, TransformerFactoryConfigurationError, TransformerConfigurationException,
        TransformerException, MojoFailureException {
    File contentJar = new File(p2repository, "content.jar");
    ZipInputStream contentStream = new ZipInputStream(new FileInputStream(contentJar));
    ZipEntry entry = null;
    Document contentDoc = null;
    boolean done = false;
    while (!done && (entry = contentStream.getNextEntry()) != null) {
        if (entry.getName().equals("content.xml")) {
            contentDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(contentStream);
            Element repoElement = (Element) contentDoc.getElementsByTagName("repository").item(0);
            {
                NodeList references = repoElement.getElementsByTagName("references");
                // remove default references
                for (int i = 0; i < references.getLength(); i++) {
                    Node currentRef = references.item(i);
                    currentRef.getParentNode().removeChild(currentRef);
                }
                // add associateSites
                if (this.associateSites != null && this.associateSites.size() > 0
                        && this.referenceStrategy == ReferenceStrategy.embedReferences) {
                    Element refElement = contentDoc.createElement("references");
                    refElement.setAttribute("size", Integer.valueOf(2 * associateSites.size()).toString());
                    for (String associate : associateSites) {
                        Element rep0 = contentDoc.createElement("repository");
                        rep0.setAttribute("uri", associate);
                        rep0.setAttribute("url", associate);
                        rep0.setAttribute("type", "0");
                        rep0.setAttribute("options", "1");
                        refElement.appendChild(rep0);
                        Element rep1 = (Element) rep0.cloneNode(true);
                        rep1.setAttribute("type", "1");
                        refElement.appendChild(rep1);
                    }
                    repoElement.appendChild(refElement);
                }
            }
            // remove default "Uncategorized" category
            if (this.removeDefaultCategory) {
                Element unitsElement = (Element) repoElement.getElementsByTagName("units").item(0);
                NodeList units = unitsElement.getElementsByTagName("unit");
                for (int i = 0; i < units.getLength(); i++) {
                    Element unit = (Element) units.item(i);
                    String id = unit.getAttribute("id");
                    if (id != null && id.contains(".Default")) {
                        unit.getParentNode().removeChild(unit);
                    }
                }
                unitsElement.setAttribute("size",
                        Integer.toString(unitsElement.getElementsByTagName("unit").getLength()));
            }
            done = true;
        }
    }
    // .close and .closeEntry raise exception:
    // https://issues.apache.org/bugzilla/show_bug.cgi?id=3862
    ZipOutputStream outContentStream = new ZipOutputStream(new FileOutputStream(contentJar));
    ZipEntry contentXmlEntry = new ZipEntry("content.xml");
    outContentStream.putNextEntry(contentXmlEntry);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    DOMSource source = new DOMSource(contentDoc);
    StreamResult result = new StreamResult(outContentStream);
    transformer.transform(source, result);
    contentStream.close();
    outContentStream.closeEntry();
    outContentStream.close();
    alterXzFile(new File(p2repository, "content.xml"), new File(p2repository, "content.xml.xz"), transformer,
            source);
}

From source file:org.jbpm.bpel.integration.soap.SoapUtil.java

public static void copyVisibleNamespaces(SOAPElement target, Element source) throws SOAPException {
    // copy the namespaces declared at the source element
    copyNamespaces(target, source);/*from   w w  w  .  j a  v a  2 s  .co m*/
    // go up the element hierarchy
    for (Node parent = source.getParentNode(); parent instanceof Element; parent = parent.getParentNode())
        copyNamespaces(target, (Element) parent);
}

From source file:org.jbpm.bpel.xml.util.XmlUtil.java

public static void copyVisibleNamespaces(final Element target, Element source) {
    // copy namespaces declared at source element
    copyNamespaces(target, source);/*from w w  w  .j ava 2  s.c  o  m*/
    // go up the element hierarchy
    for (Node parent = source.getParentNode(); parent instanceof Element; parent = parent.getParentNode())
        copyNamespaces(target, (Element) parent);
}

From source file:org.jbpm.bpel.xml.util.XmlUtil.java

public static Map findNamespaceDeclarations(Element elem) {
    Map namespaces = new HashMap();

    findLocalNamespaceDeclarations(elem, namespaces);

    // go up the parent hierarchy
    for (Node parent = elem.getParentNode(); parent instanceof Element; parent = parent.getParentNode())
        findLocalNamespaceDeclarations((Element) parent, namespaces);

    return namespaces;
}

From source file:org.kie.workbench.common.stunner.svg.gen.translator.css.SVGStyleTranslator.java

static List<Element> getElementsTree(final Element element) {
    final List<Element> tree = new LinkedList<>();
    tree.add(element);//from  www  .j  av a 2s.  c  o  m
    Node parent = element.getParentNode();
    while (null != parent) {
        if (parent instanceof Element) {
            tree.add((Element) parent);
        }
        parent = parent.getParentNode();
    }
    return tree;
}

From source file:org.kuali.rice.edl.impl.components.SelectControlEDLComponent.java

public void updateDOM(Document dom, Element currentDefinitionElement, EDLContext edlContext) {
    Element currentVersion = VersioningPreprocessor.findCurrentVersion(dom);
    XPath xPath = XPathHelper.newXPath(dom);
    try {// w w w.jav a  2  s  .com
        NodeList selectFieldDefs = (NodeList) xPath.evaluate(
                "//fieldDef[display/type = 'select' and display/valuesGroup] | //fieldDef[display/type = 'select_refresh' and display/valuesGroup]",
                dom, XPathConstants.NODESET);
        for (int fIndex = 0; fIndex < selectFieldDefs.getLength(); fIndex++) {
            Element fieldDef = (Element) selectFieldDefs.item(fIndex);
            NodeList valuesGroups = (NodeList) xPath.evaluate("./display/valuesGroup", fieldDef,
                    XPathConstants.NODESET);
            for (int index = 0; index < valuesGroups.getLength(); index++) {
                Element valuesGroupElem = (Element) valuesGroups.item(index);
                NodeList dependsOnFields = (NodeList) xPath.evaluate("./dependsOn/field", valuesGroupElem,
                        XPathConstants.NODESET);
                String fieldEvalExpression = "";
                for (int dIndex = 0; dIndex < dependsOnFields.getLength(); dIndex++) {
                    if (!StringUtils.isBlank(fieldEvalExpression)) {
                        fieldEvalExpression += " and ";
                    }
                    Element fieldElem = (Element) dependsOnFields.item(dIndex);
                    String name = fieldElem.getAttribute("name");
                    String value = fieldElem.getTextContent();
                    fieldEvalExpression += "./field[@name='" + name + "']/value = '" + value + "'";
                }
                if ((Boolean) xPath.evaluate(fieldEvalExpression, currentVersion, XPathConstants.BOOLEAN)) {
                    includeValuesGroup(valuesGroupElem);
                } else {
                    // remove the valuesGroup as it did not match
                    valuesGroupElem.getParentNode().removeChild(valuesGroupElem);
                }
            }
        }
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Failed to evaluate xpath expression.", e);
    }
}

From source file:org.kuali.rice.edl.impl.components.SelectControlEDLComponent.java

protected void includeValuesGroup(Element valuesGroupElem) {
    Element valuesGroupParent = (Element) valuesGroupElem.getParentNode();
    NodeList valuesGroupChildren = valuesGroupElem.getChildNodes();

    for (int index = 0; index < valuesGroupChildren.getLength(); index++) {
        Node item = valuesGroupChildren.item(index);
        if (Node.ELEMENT_NODE == item.getNodeType() && item.getNodeName().equals("values")) {
            valuesGroupParent.insertBefore(item, valuesGroupElem);
        }/*from   www .  j  a  v  a  2  s .  c om*/
    }
    valuesGroupParent.removeChild(valuesGroupElem);
}

From source file:org.kuali.rice.kew.rule.xmlrouting.StandardGenericXMLRuleAttribute.java

/**
 * Extracts the xPath expressions that should be evaluated in order to determine whether or not the rule matches.  THis should take
 * into account the value of evaluateForMissingExtensions.
 *//*from   w  w w.  j ava 2  s.  c o m*/
protected List<String> extractExpressionsToEvaluate(XPath xpath, DocumentContent docContent,
        List<RuleExtension> ruleExtensions) {
    List<String> expressionsToEvaluate = new ArrayList<String>(ruleExtensions.size() + 1);
    Element configXml = getConfigXML();
    String findFieldExpressions = "//routingConfig/" + FIELD_DEF_E + "/fieldEvaluation/xpathexpression";
    try {
        NodeList xPathExpressions = (NodeList) xpath.evaluate(findFieldExpressions, configXml,
                XPathConstants.NODESET);
        for (int index = 0; index < xPathExpressions.getLength(); index++) {
            Element expressionElement = (Element) xPathExpressions.item(index);
            String expression = expressionElement.getTextContent();
            if (!isEvaluateForMissingExtensions()) {
                Node parentNode = expressionElement.getParentNode().getParentNode();
                Node fieldAttribute = parentNode.getAttributes().getNamedItem("name");
                if (fieldAttribute == null || StringUtils.isEmpty(fieldAttribute.getNodeValue())) {
                    throw new WorkflowRuntimeException(
                            "Could not determine field name defined on fieldDef for xpath expression: "
                                    + expression);
                }
                String fieldName = fieldAttribute.getNodeValue();
                boolean foundExtension = false;
                outer: for (RuleExtension ruleExtension : ruleExtensions) {
                    if (ruleExtension.getRuleTemplateAttribute().getRuleAttribute().getName()
                            .equals(extensionDefinition.getName())) {
                        for (String ruleExtensionValueKey : ruleExtension.getExtensionValuesMap().keySet()) {
                            if (fieldName.equals(ruleExtensionValueKey)) {
                                foundExtension = true;
                                break outer;
                            }
                        }
                    }
                }
                if (!foundExtension) {
                    // if the rule does not have an extension value for the xpath expression on the corresponding field def, let's skip it
                    continue;
                }
            }

            if (!StringUtils.isEmpty(expression)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Adding routingConfig XPath expression: " + expression);
                }
                expressionsToEvaluate.add(expression);
            }
        }
    } catch (XPathExpressionException e) {
        throw new WorkflowRuntimeException(
                "Failed to evalute XPath expression for fieldDefs: " + findFieldExpressions);
    }
    String findGlobalExpressions = "//routingConfig/globalEvaluations/xpathexpression";
    try {
        NodeList xPathExpressions = (NodeList) xpath.evaluate(findGlobalExpressions, configXml,
                XPathConstants.NODESET);
        for (int index = 0; index < xPathExpressions.getLength(); index++) {
            Element expressionElement = (Element) xPathExpressions.item(index);
            //String expression = XmlJotter.jotNode(expressionElement);
            String expression = expressionElement.getTextContent();
            if (!StringUtils.isEmpty(expression)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Adding global XPath expression: " + expression);
                }
                expressionsToEvaluate.add(expression);
            }
        }
    } catch (XPathExpressionException e) {
        throw new WorkflowRuntimeException(
                "Failed to evalute global XPath expression: " + findGlobalExpressions);
    }
    return expressionsToEvaluate;
}