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:eu.transkribus.languageresources.extractor.pagexml.PAGEXMLExtractor.java

private String getCustomTagValue(Node unicodeNode) {
    Node textLineNode = unicodeNode.getParentNode().getParentNode();
    return textLineNode.getAttributes().getNamedItem("custom").getTextContent();
}

From source file:com.crawljax.plugins.adi.Report.java

/**
 * Taken from ErrorReport./*from w  ww .j a va 2  s.com*/
 */
private Document addMarker(String id, Document doc, String xpath) {
    try {

        String prefixMarker = "###BEGINMARKER" + id + "###";
        String suffixMarker = "###ENDMARKER###";

        NodeList nodeList = XPathHelper.evaluateXpathExpression(doc, xpath);

        if (nodeList.getLength() == 0 || nodeList.item(0) == null) {
            return doc;
        }

        Node element = nodeList.item(0);

        if (element.getNodeType() == Node.ELEMENT_NODE) {
            Node beginNode = doc.createTextNode(prefixMarker);
            Node endNode = doc.createTextNode(suffixMarker);

            element.getParentNode().insertBefore(beginNode, element);
            if (element.getNextSibling() == null) {
                element.getParentNode().appendChild(endNode);
            } else {
                element.getParentNode().insertBefore(endNode, element.getNextSibling());
            }
        } else if (element.getNodeType() == Node.TEXT_NODE && element.getTextContent() != null) {
            element.setTextContent(prefixMarker + element.getTextContent() + suffixMarker);
        } else if (element.getNodeType() == Node.ATTRIBUTE_NODE) {
            element.setNodeValue(prefixMarker + element.getTextContent() + suffixMarker);
        }

        return doc;
    } catch (Exception e) {
        return doc;
    }
}

From source file:com.amalto.core.save.context.PartialUpdateActionCreator.java

@Override
public List<Action> visit(ComplexTypeMetadata complexType) {
    if (mainType == null) {
        mainType = complexType;/*  ww  w . ja va  2s .c om*/
    }
    List<Action> actionList = super.visit(complexType);
    if (complexType == mainType) {
        if (!preserveCollectionOldValues) {
            /*
             * There might be elements not used for the update. In case overwrite=true, expected behavior is to append
             * unused elements at the end. The code below removes used elements in partial update (with overwrite=true)
             * then do a new partial update (with overwrite=false) so new elements are added at the end (this is the
             * behavior of a overwrite=false).
             */
            // TODO these code will be replaced by fhuaulme's new API
            List<Node> nodes = new ArrayList<Node>();
            for (String usedPath : usedPaths) {
                Accessor accessor = newDocument.createAccessor(usedPath);
                if (accessor.exist()) {
                    accessor.touch();
                    if (newDocument instanceof DOMMutableDocument) {
                        nodes.add(((DOMMutableDocument) newDocument).getLastAccessedNode());
                    }
                }
            }
            for (Node node : nodes) {
                if (node != null && node.getParentNode() != null) {
                    node.getParentNode().removeChild(node);
                }
            }
            // Since this a costly operation do this only if there are still elements under the pivot.
            int leftElementCount = newDocument
                    .createAccessor(StringUtils.substringBeforeLast(partialUpdatePivot, "/")).size(); //$NON-NLS-1$
            if (leftElementCount > 0) {
                preserveCollectionOldValues = true;
                mainType.accept(this);
            }
        }
    }
    return actionList;
}

From source file:it.greenvulcano.script.impl.ScriptExecutorImpl.java

/**
 * Initialize the instance.//from   w w  w.j  av  a 2  s. c o  m
 * 
 * @param node
 *        the configuration node
 * @throws GVScriptException
 */
public void init(Node node) throws GVScriptException {
    try {
        name = XMLConfig.get(node.getParentNode(), "@name");
        logger.debug("init script node " + name);
        lang = XMLConfig.get(node, "@lang", "js");
        String file = XMLConfig.get(node, "@file", "");
        if (!"".equals(file)) {
            scriptName = file;
            script = cache.getScript(file);
        } else {
            scriptName = ScriptCache.INTERNAL_SCRIPT;
            script = XMLConfig.get(node, ".", null);
        }

        if ((script == null) || "".equals(script)) {
            throw new GVScriptException("Empty configured script!");
        }

        ScriptEngine engine = getScriptEngine(lang);
        if (engine == null) {
            throw new GVScriptException("ScriptEngine[" + lang + "] not found!");
        }

        String bcName = XMLConfig.get(node, "@base-context", null);
        String baseContext = BaseContextManager.instance().getBaseContextScript(lang, bcName);
        if (baseContext != null) {
            script = baseContext + "\n\n" + (script != null ? script : "");
        } else if (bcName != null) {
            throw new GVScriptException("BaseContext[" + lang + "/" + bcName + "] not found!");
        }

        if (engine instanceof Compilable && PropertiesHandler.isExpanded(script)) {
            String scriptKey = DigestUtils.sha256Hex(script);

            Optional<CompiledScript> cachedCompiledScript = cache.getCompiledScript(scriptKey);

            if (cachedCompiledScript.isPresent()) {
                compScript = cachedCompiledScript.get();
            } else {
                logger.debug("Static script[" + lang + "], can be compiled for performance");
                compScript = ((Compilable) engine).compile(script);
                cache.putCompiledScript(scriptKey, compScript);
            }
        }
        bindings = engine.createBindings();

        initialized = true;
    } catch (GVScriptException exc) {
        logger.error("Error initializing ScriptExecutorImpl", exc);
        throw exc;
    } catch (Exception exc) {
        logger.error("Error initializing ScriptExecutorImpl", exc);
        throw new GVScriptException("Error initializing ScriptExecutorImpl", exc);
    }
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

private static Node getParentNode(Node node) {
    if (node instanceof Attr) {
        Attr attr = (Attr) node;
        return attr.getOwnerElement();
    } else {//from  w w w.j  a  va 2  s. co m
        return node.getParentNode();
    }
}

From source file:de.interactive_instruments.etf.testdriver.te.TeTestTask.java

private String getItemID(final Node node) {
    return EidFactory.getDefault().createUUID(etsSpecificPrefix
            + XmlUtils.getAttribute(node.getParentNode(), "name") + XmlUtils.getAttribute(node, "name"))
            .getId();//from  w w  w .ja v  a2 s.co m
}

From source file:de.interactive_instruments.etf.testdriver.te.TeTestTask.java

private String getAssertionID(final Node node) {
    return EidFactory.getDefault()
            .createUUID(etsSpecificPrefix + XmlUtils.getAttribute(node.getParentNode(), "name")
                    + XmlUtils.getAttribute(node, "name") + "Assertion")
            .getId();//from www.  j a  v  a2 s .  c om
}

From source file:com.messagehub.samples.servlet.KafkaServlet.java

public String toPrettyString(String xml, int indent) {
    try {/*  ww  w . jav a 2  s  .  c  o  m*/
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
                XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:esg.security.yadis.XrdsDoc.java

public List parse(String input, Set targetTypes) throws XrdsParseException {
    Document document = parseXmlInput(input);

    NodeList XRDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_XRD);
    Node lastXRD;// w  w w. j av a2s  . c o  m
    if (XRDs.getLength() < 1 || (lastXRD = XRDs.item(XRDs.getLength() - 1)) == null)
        throw new XrdsParseException("No XRD elements found.");

    // get the canonical ID, if any (needed for XRIs)
    String canonicalId = null;
    Node canonicalIdNode;
    NodeList canonicalIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_CANONICALID);
    for (int i = 0; i < canonicalIDs.getLength(); i++) {
        canonicalIdNode = canonicalIDs.item(i);
        if (canonicalIdNode.getParentNode() != lastXRD)
            continue;
        if (canonicalId != null)
            throw new XrdsParseException("More than one Canonical ID found.");
        canonicalId = canonicalIdNode.getFirstChild() != null
                && canonicalIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE
                        ? canonicalIdNode.getFirstChild().getNodeValue()
                        : null;
    }

    // extract the services that match the specified target types
    NodeList types = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_TYPE);
    Map serviceTypes = new HashMap();
    Set selectedServices = new HashSet();
    Node typeNode, serviceNode;
    for (int i = 0; i < types.getLength(); i++) {
        typeNode = types.item(i);
        String type = typeNode != null && typeNode.getFirstChild() != null
                && typeNode.getFirstChild().getNodeType() == Node.TEXT_NODE
                        ? typeNode.getFirstChild().getNodeValue()
                        : null;
        if (type == null)
            continue;

        serviceNode = typeNode.getParentNode();

        if (targetTypes == null)
            selectedServices.add(serviceNode);

        else if (targetTypes.contains(type))
            selectedServices.add(serviceNode);

        addServiceType(serviceTypes, serviceNode, type);
    }

    // extract local IDs
    Map serviceLocalIDs = extractElementsByParent(XRD_NS, XRD_ELEM_LOCALID, selectedServices, document);
    Map serviceDelegates = extractElementsByParent(OPENID_NS, OPENID_ELEM_DELEGATE, selectedServices, document);

    // build XrdsServiceEndpoints for all URIs in the found services
    List result = new ArrayList();
    NodeList uris = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_URI);
    Node uriNode;
    for (int i = 0; i < uris.getLength(); i++) {
        uriNode = uris.item(i);
        if (uriNode == null || !selectedServices.contains(uriNode.getParentNode()))
            continue;

        String uri = uriNode.getFirstChild() != null && uriNode.getFirstChild().getNodeType() == Node.TEXT_NODE
                ? uriNode.getFirstChild().getNodeValue()
                : null;

        serviceNode = uriNode.getParentNode();
        Set typeSet = (Set) serviceTypes.get(serviceNode);

        String localId = (String) serviceLocalIDs.get(serviceNode);
        String delegate = (String) serviceDelegates.get(serviceNode);

        XrdsServiceElem endpoint = new XrdsServiceElem(uri, typeSet, getPriority(serviceNode),
                getPriority(uriNode), localId, delegate, canonicalId);
        result.add(endpoint);
    }

    Collections.sort(result);
    return result;
}

From source file:com.centeractive.ws.builder.soap.XmlUtils.java

public static NodeList getChildElements(Element elm) {
    List<Element> list = new ArrayList<Element>();

    NodeList nl = elm.getChildNodes();
    for (int c = 0; c < nl.getLength(); c++) {
        Node item = nl.item(c);
        if (item.getParentNode() == elm && item.getNodeType() == Node.ELEMENT_NODE)
            list.add((Element) item);
    }//from ww  w . j  a v a2s. co m

    return new ElementNodeList(list);
}