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:org.jahia.services.importexport.ExternalUsersImportUpdater.java

private boolean transform(InputStream inputStream, OutputStream outputStream, Map<String, String> pathMapping)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException,
        TransformerException {//www  .  ja  v a 2 s  .c  om
    Document doc = JahiaDocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new InputSource(inputStream));

    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xpath.evaluate(
            "//*[@*[name()='jcr:primaryType'] = 'jnt:user' and @*[name()='j:external'] = 'true']", doc,
            XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node legacyExtUser = nodes.item(i);
        ArrayList<Node> tree = new ArrayList<Node>();
        Element extUser = (Element) legacyExtUser.cloneNode(true);
        extUser.setAttribute("jcr:primaryType", "jnt:externalUser");
        String externalSource = extUser.getAttribute("j:externalSource");
        extUser.setAttribute("j:externalSource", externalSource + ".users");
        tree.add(extUser);

        Node parent = legacyExtUser.getParentNode();
        parent.removeChild(legacyExtUser);
        boolean removeParent = !hasChildElement(parent);
        while (parent != null && !"users".equals(parent.getNodeName())) {
            tree.add(0, parent.cloneNode(false));
            Node n = parent.getParentNode();
            if (removeParent) {
                n.removeChild(parent);
                removeParent = !hasChildElement(n);
            }
            parent = n;
        }
        if (parent == null)
            continue;
        StringBuilder mappingSrc = new StringBuilder(getNodePath(parent));
        StringBuilder mappingDst = new StringBuilder(getNodePath(parent));

        NodeList nodeList = ((Element) parent).getElementsByTagName("providers");
        if (nodeList.getLength() == 0) {
            Element e = doc.createElement("providers");
            e.setAttribute("jcr:primaryType", "jnt:usersFolder");
            e.setAttribute("jcr:mixinTypes", "jmix:hasExternalProviderExtension");
            e.setAttribute("j:published", "true");
            e.setAttribute("j:publicationStatus", "1");
            parent.appendChild(e);
            parent = e;
        } else {
            parent = nodeList.item(0);
        }
        mappingDst.append("/").append(parent.getNodeName());

        nodeList = ((Element) parent).getElementsByTagName(externalSource);
        if (nodeList.getLength() == 0) {
            Element e = doc.createElement(externalSource);
            e.setAttribute("jcr:primaryType", "jnt:usersFolder");
            e.setAttribute("provider", externalSource + ".users");
            e.setAttribute("j:publicationStatus", "4");
            parent.appendChild(e);
            parent = e;
        } else {
            parent = nodeList.item(0);
        }
        mappingDst.append("/").append(parent.getNodeName());

        for (Node n : tree) {
            String nodeName = n.getNodeName();
            mappingSrc.append("/").append(nodeName);
            mappingDst.append("/").append(nodeName);
            nodeList = ((Element) parent).getElementsByTagName(nodeName);
            if (nodeList.getLength() == 0) {
                Node node = parent.appendChild(n);
                parent = node;
            } else {
                parent = nodeList.item(0);
            }
        }
        pathMapping.put(mappingSrc.toString(), mappingDst.toString());
    }

    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(new DOMSource(doc), new StreamResult(outputStream));

    return nodes.getLength() > 0;
}

From source file:org.jahia.services.importexport.ExternalUsersImportUpdater.java

private String getNodePath(Node node) {
    if (node.getParentNode() == null || node.getParentNode() instanceof Document) {
        return "";
    } else {/*w  w w.j  av a  2s .  c  o m*/
        return getNodePath(node.getParentNode()) + "/" + node.getNodeName();
    }
}

From source file:org.jasig.portal.layout.simple.RDBMUserLayoutStore.java

private String getName(Document descr) {
    NodeList names = descr.getElementsByTagName("name");
    Node name = null;
    for (int i = names.getLength() - 1; i >= 0; i--) {
        name = names.item(i);/*  w  w  w.java2 s . c  o  m*/
        if (name.getParentNode().getNodeName().equals("stylesheetdescription"))
            break;
        else
            name = null;
    }
    if (name != null) {
        return this.getTextChildNodeValue(name);
    } else {
        if (log.isDebugEnabled())
            log.debug(
                    "RDBMUserLayoutStore::getName() : no \"name\" element was found under the \"stylesheetdescription\" node!");
        return null;
    }
}

From source file:org.jasig.portal.layout.simple.RDBMUserLayoutStore.java

private String getRootElementTextValue(Document descr, String elementName) {
    NodeList names = descr.getElementsByTagName(elementName);
    Node name = null;
    for (int i = names.getLength() - 1; i >= 0; i--) {
        name = names.item(i);/*from   ww  w  .  jav  a2 s .c  om*/

        if (name.getParentNode().getNodeName().equals("stylesheetdescription"))
            break;
        else
            name = null;
    }
    if (name != null) {
        return this.getTextChildNodeValue(name);
    } else {
        if (log.isDebugEnabled())
            log.debug("RDBMUserLayoutStore::getRootElementTextValue() : no \"" + elementName
                    + "\" element was found under the \"stylesheetdescription\" node!");
        return null;
    }
}

From source file:org.jasig.portal.layout.simple.RDBMUserLayoutStore.java

private String getDescription(Document descr) {
    NodeList descriptions = descr.getElementsByTagName("description");
    Node description = null;
    for (int i = descriptions.getLength() - 1; i >= 0; i--) {
        description = descriptions.item(i);
        if (description.getParentNode().getNodeName().equals("stylesheetdescription"))
            break;
        else// www .j ava2 s.  co m
            description = null;
    }
    if (description != null) {
        return this.getTextChildNodeValue(description);
    } else {
        if (log.isDebugEnabled())
            log.debug(
                    "RDBMUserLayoutStore::getDescription() : no \"description\" element was found under the \"stylesheetdescription\" node!");
        return null;
    }
}

From source file:org.jboss.bpm.console.server.util.DOMUtils.java

/** Gets parent element or null if there is none
 *//*ww  w.ja va  2 s  .c  o  m*/
public static Element getParentElement(Node node) {
    Node parent = node.getParentNode();
    return (parent instanceof Element ? (Element) parent : null);
}

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//from w  ww.j  a  va 2s.  c om
 * @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.jboss.windup.util.xml.LocationAwareContentHandler.java

@Override
public void endElement(final String uri, final String localName, final String qName) {
    if (current == null) {
        return;/*from  www.  ja v  a 2s. co m*/
    }

    Node parent = current.getParentNode();
    // If the parent is the document itself, then we're done.
    if (parent.getParentNode() == null) {
        current.normalize();
        current = null;
    } else {
        current = (Element) current.getParentNode();
    }
}

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

/**
 * Retrieves the prefix associated with a namespace URI in the given context node.
 * @param namespaceURI the namespace whose prefix is required
 * @param contextNode the node where to search for namespace declarations
 * @return the prefix associated with the namespace URI; the empty string indicates the default
 * namespace, while <code>null</code> indicates no association
 */// w  w w  .  j  ava 2s  .c  o m
public static String getPrefix(String namespaceURI, Node contextNode) {
    switch (contextNode.getNodeType()) {
    case Node.ATTRIBUTE_NODE:
        contextNode = ((Attr) contextNode).getOwnerElement();
        break;
    case Node.ELEMENT_NODE:
        break;
    default:
        contextNode = contextNode.getParentNode();
    }

    while (contextNode != null && contextNode.getNodeType() == Node.ELEMENT_NODE) {
        NamedNodeMap attributes = contextNode.getAttributes();
        for (int i = 0, n = attributes.getLength(); i < n; i++) {
            Node attr = attributes.item(i);

            // is attribute a namespace declaration and matches the given URI?
            if (BpelConstants.NS_XMLNS.equals(attr.getNamespaceURI())
                    && namespaceURI.equals(attr.getNodeValue())) {
                String prefix = attr.getLocalName();
                return "xmlns".equals(prefix) ? "" : prefix;
            }
        }
        contextNode = contextNode.getParentNode();
    }
    return null;
}

From source file:org.kie.server.services.jbpm.ui.form.InMemoryFormProvider.java

protected String filterXML(String document, String lang, String deploymentId, Map inputs, Map outputs) {
    try {/*from w  w  w  .ja  v a 2s  .co m*/
        if (inputs == null) {
            inputs = Collections.emptyMap();
        }
        if (outputs == null) {
            outputs = Collections.emptyMap();
        }

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.parse(new ByteArrayInputStream(document.getBytes()));
        NodeList nodes = doc.getElementsByTagName(NODE_FORM);
        Node nodeForm = nodes.item(0);
        NodeList childNodes = nodeForm.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node node = childNodes.item(i);
            if (node.getNodeName().equals(NODE_FIELD)) {

                String fieldType = node.getAttributes().getNamedItem(ATTR_TYPE).getNodeValue();
                if (SUB_FORM_TYPE.equals(fieldType)) {

                    String defaultSubForm = findPropertyValue(node, "defaultSubform");
                    if (defaultSubForm != null) {

                        String subFormContent = formManagerService.getFormByKey(deploymentId, defaultSubForm);

                        if (subFormContent != null) {
                            // read once to find out input binding name
                            Document tmpSubForm = builder
                                    .parse(new ByteArrayInputStream(subFormContent.getBytes()));

                            Node firstFieldNode = tmpSubForm.getElementsByTagName(NODE_FIELD).item(0);
                            // inputs - current node
                            String currentNodeInputBinding = findPropertyValue(node, "inputBinding");
                            currentNodeInputBinding = currentNodeInputBinding.replaceAll("/", ".");

                            // outputs current node
                            String currentNodeOutputBinding = findPropertyValue(node, "outputBinding");
                            currentNodeOutputBinding = currentNodeOutputBinding.replaceAll("/", ".");

                            // inputs sub form
                            String inputBindingSubForm = findPropertyValue(firstFieldNode, "inputBinding");
                            inputBindingSubForm = inputBindingSubForm.split("/")[0];

                            // outputs sub form
                            String outputBindingSubForm = findPropertyValue(firstFieldNode, "outputBinding");
                            outputBindingSubForm = outputBindingSubForm.split("/")[0];

                            Map<String, Object> subFormInputs = new HashMap<String, Object>(inputs);
                            try {
                                subFormInputs.put(inputBindingSubForm,
                                        MVELSafeHelper.getEvaluator().eval(currentNodeInputBinding, inputs));
                            } catch (Exception e) {

                            }

                            Map<String, Object> subFormOutputs = new HashMap<String, Object>(outputs);
                            try {
                                subFormOutputs.put(outputBindingSubForm,
                                        MVELSafeHelper.getEvaluator().eval(currentNodeOutputBinding, outputs));
                            } catch (Exception e) {

                            }

                            // run the transformation
                            String filtered = filterXML(subFormContent, lang, deploymentId, subFormInputs,
                                    subFormOutputs);

                            Document docSubForm = builder.parse(new ByteArrayInputStream(filtered.getBytes()));
                            NodeList nodesSubForm = docSubForm.getElementsByTagName(NODE_FORM);
                            Node nodeFormSubForm = nodesSubForm.item(0);

                            Node imported = doc.importNode(nodeFormSubForm, true);

                            node.getParentNode().replaceChild(imported, node);
                        }
                    }
                } else if (MULTI_SUB_FORM_TYPE.equals(fieldType)) {

                    String defaultSubForm = findPropertyValue(node, "defaultSubform");
                    if (defaultSubForm != null) {

                        String subFormContent = formManagerService.getFormByKey(deploymentId, defaultSubForm);
                        if (subFormContent != null) {

                            String inputBinding = findPropertyValue(node, "inputBinding");
                            inputBinding = inputBinding.replaceAll("/", ".");

                            String outputBinding = findPropertyValue(node, "outputBinding");
                            outputBinding = outputBinding.replaceAll("/", ".");

                            Collection<Object> list = new ArrayList<Object>();
                            Collection<Object> listOut = new ArrayList<Object>();
                            Map<String, Object> subFormInputs = new HashMap<String, Object>(inputs);
                            Map<String, Object> subFormOutputs = new HashMap<String, Object>(outputs);
                            try {
                                list = (Collection<Object>) MVELSafeHelper.getEvaluator().eval(inputBinding,
                                        inputs);
                            } catch (Exception e) {
                                // no elements found add simple object to generate single line
                                list.add(new Object());
                            }
                            try {
                                listOut = (Collection<Object>) MVELSafeHelper.getEvaluator().eval(outputBinding,
                                        outputs);
                            } catch (Exception e) {
                                // no elements found add simple object to generate single line
                                list.add(new Object());
                            }

                            // read once to find out input binding name
                            Document tmpSubForm = builder
                                    .parse(new ByteArrayInputStream(subFormContent.getBytes()));

                            Node firstFieldNode = tmpSubForm.getElementsByTagName(NODE_FIELD).item(0);

                            String inputBindingSubForm = findPropertyValue(firstFieldNode, "inputBinding");
                            inputBindingSubForm = inputBindingSubForm.split("/")[0];

                            String outputBindingSubForm = findPropertyValue(firstFieldNode, "outputBinding");
                            outputBindingSubForm = outputBindingSubForm.split("/")[0];
                            // inputs
                            for (Object element : list) {
                                subFormInputs.put(inputBindingSubForm, element);

                                String filtered = filterXML(subFormContent, lang, deploymentId, subFormInputs,
                                        subFormOutputs);

                                Document docSubForm = builder
                                        .parse(new ByteArrayInputStream(filtered.getBytes()));
                                NodeList nodesSubForm = docSubForm.getElementsByTagName(NODE_FORM);
                                Node nodeFormSubForm = nodesSubForm.item(0);

                                Node imported = doc.importNode(nodeFormSubForm, true);

                                node.getParentNode().appendChild(imported);
                            }
                            // outputs
                            for (Object element : listOut) {
                                subFormOutputs.put(outputBindingSubForm, element);

                                String filtered = filterXML(subFormContent, lang, deploymentId,
                                        Collections.emptyMap(), subFormOutputs);

                                Document docSubForm = builder
                                        .parse(new ByteArrayInputStream(filtered.getBytes()));
                                NodeList nodesSubForm = docSubForm.getElementsByTagName(NODE_FORM);
                                Node nodeFormSubForm = nodesSubForm.item(0);

                                Node imported = doc.importNode(nodeFormSubForm, true);

                                node.getParentNode().appendChild(imported);
                            }

                            node.getParentNode().removeChild(node);
                        }

                    }

                } else {

                    NodeList fieldPropsNodes = node.getChildNodes();
                    for (int j = 0; j < fieldPropsNodes.getLength(); j++) {
                        Node nodeFieldProp = fieldPropsNodes.item(j);
                        if (nodeFieldProp.getNodeName().equals(NODE_PROPERTY)) {
                            String propName = nodeFieldProp.getAttributes().getNamedItem(ATTR_NAME)
                                    .getNodeValue();
                            String value = StringEscapeUtils.unescapeXml(
                                    nodeFieldProp.getAttributes().getNamedItem(ATTR_VALUE).getNodeValue());
                            if (inputs != null && propName != null && value != null
                                    && "inputBinding".equals(propName)) {
                                if (!value.isEmpty()) {
                                    value = value.replaceAll("/", ".");
                                    try {
                                        Object actualValue = MVELSafeHelper.getEvaluator().eval(value, inputs);

                                        nodeFieldProp.getAttributes().getNamedItem(ATTR_VALUE)
                                                .setNodeValue(String.valueOf(actualValue));
                                    } catch (Exception e) {
                                        // no elements found add simple object to generate single line

                                    }
                                }
                            } else if (outputs != null && propName != null && value != null
                                    && "outputBinding".equals(propName)) {
                                if (!value.isEmpty()) {
                                    value = value.replaceAll("/", ".");
                                    try {
                                        Object actualValue = MVELSafeHelper.getEvaluator().eval(value, outputs);

                                        nodeFieldProp.getAttributes().getNamedItem(ATTR_VALUE)
                                                .setNodeValue(String.valueOf(actualValue));
                                    } catch (Exception e) {
                                        // no elements found add simple object to generate single line

                                    }
                                }
                            } else if (propName != null && value != null
                                    && ATTR_LANG_NAMES.contains(propName)) {
                                filterProperty(nodeFieldProp, lang, value);
                            }
                        }
                    }
                }
            }
        }

        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        document = writer.toString();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return document;
}