Example usage for org.w3c.dom Node getNextSibling

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

Introduction

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

Prototype

public Node getNextSibling();

Source Link

Document

The node immediately following this node.

Usage

From source file:ApplyXPathDOM.java

/** Process input args and execute the XPath.  */
public void doMain(String[] args) throws Exception {
    filename = args[0];//from   w  w w  .  j  ava 2s  .c om
    xpath = args[1];

    if ((filename != null) && (filename.length() > 0) && (xpath != null) && (xpath.length() > 0)) {
        // Tell that we're loading classes and parsing, so the time it 
        // takes to do this doesn't get confused with the time to do 
        // the actual query and serialization.
        System.out.println("Loading classes, parsing " + filename + ", and setting up serializer");

        // Set up a DOM tree to query.
        InputSource in = new InputSource(new FileInputStream(filename));
        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
        dfactory.setNamespaceAware(true);
        Document doc = dfactory.newDocumentBuilder().parse(in);

        // Set up an identity transformer to use as serializer.
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        // Use the DOM L3 XPath API to apply the xpath expression to the doc.
        System.out.println("Querying DOM using " + xpath);

        // Create an XPath evaluator and pass in the document.
        XPathEvaluator evaluator = new XPathEvaluatorImpl(doc);
        XPathNSResolver resolver = evaluator.createNSResolver(doc);

        // Evaluate the xpath expression
        XPathResult result = (XPathResult) evaluator.evaluate(xpath, doc, resolver,
                XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

        // Serialize the found nodes to System.out.
        System.out.println("<output>");

        Node n;
        while ((n = result.iterateNext()) != null) {
            if (isTextNode(n)) {
                // DOM may have more than one node corresponding to a 
                // single XPath text node.  Coalesce all contiguous text nodes
                // at this level
                StringBuffer sb = new StringBuffer(n.getNodeValue());
                for (Node nn = n.getNextSibling(); isTextNode(nn); nn = nn.getNextSibling()) {
                    sb.append(nn.getNodeValue());
                }
                System.out.print(sb);
            } else {
                serializer.transform(new DOMSource(n), new StreamResult(new OutputStreamWriter(System.out)));
            }
            System.out.println();
        }
        System.out.println("</output>");
    } else {
        System.out.println("Bad input args: " + filename + ", " + xpath);
    }
}

From source file:com.meltmedia.cadmium.core.util.WarUtils.java

/**
 * <p>Adds a child xml element to a parent element relative to other elements with a tagname.</p>
 * <p>If first is true then the child is added before any elements with a tagname, the opposite happens when first is false.</p> 
 * @param parent The parent xml element.
 * @param child The child xml element to add.
 * @param tagname The tagname to be relative to.
 * @param first A flag that describes the relative relationship between the child element and its siblings named by tagname.
 *///from w w w .  j  av a 2s.c o m
public static void addRelativeTo(Element parent, Element child, String tagname, boolean first) {
    NodeList nodes = parent.getChildNodes();
    if (nodes.getLength() > 0) {
        Node relativeEl = null;
        boolean found = false;
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element el = (Element) node;
                if (el.getTagName().equals(tagname)) {
                    if (relativeEl == null || !first) {
                        relativeEl = el;
                    } else if (first && !found) {
                        relativeEl = el;
                    }
                    found = true;
                }
            }
        }
        if (relativeEl != null && !first) {
            relativeEl = relativeEl.getNextSibling();
        }
        if (relativeEl == null && first) {
            relativeEl = nodes.item(0);
        } else {
            parent.appendChild(child);
        }
        if (relativeEl != null) {
            parent.insertBefore(child, relativeEl);
        }
    } else {
        //There are no elements in the parent node so lets just append child.
        parent.appendChild(child);
    }
}

From source file:org.alfresco.web.config.ConfigRuntime.java

protected void insertChildAfter(Node parent, Node child, Node sibling) {
    if (sibling == null) {
        if (parent.getFirstChild() != null) {
            parent.insertBefore(child, parent.getFirstChild());
        } else {/*from   w w  w .  j a  v a 2s . c  om*/
            appendChild(parent, child);
        }
    } else {
        if (sibling.getNextSibling() == null) {
            appendChild(parent, child);
        } else {
            parent.insertBefore(child, sibling.getNextSibling());
        }
    }
}

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

/**
 * Taken from ErrorReport./* www.  ja  va  2s .  c  om*/
 */
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:Main.java

/**
 * This method is a tree-search to help prevent against wrapping attacks. It checks that no
 * two Elements have ID Attributes that match the "value" argument, if this is the case then
 * "false" is returned. Note that a return value of "true" does not necessarily mean that
 * a matching Element has been found, just that no wrapping attack has been detected.
 *///from   w  w  w . j  ava 2s . c  o m
public static boolean protectAgainstWrappingAttack(Node startNode, String value) {
    Node startParent = startNode.getParentNode();
    Node processedNode = null;
    Element foundElement = null;

    String id = value.trim();
    if (id.charAt(0) == '#') {
        id = id.substring(1);
    }

    while (startNode != null) {
        if (startNode.getNodeType() == Node.ELEMENT_NODE) {
            Element se = (Element) startNode;

            NamedNodeMap attributes = se.getAttributes();
            if (attributes != null) {
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attr = (Attr) attributes.item(i);
                    if (attr.isId() && id.equals(attr.getValue())) {
                        if (foundElement == null) {
                            // Continue searching to find duplicates
                            foundElement = attr.getOwnerElement();
                        } else {
                            //log.debug("Multiple elements with the same 'Id' attribute value!");
                            return false;
                        }
                    }
                }
            }
        }

        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }

        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return true;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return true;
}

From source file:com.amalto.core.history.accessor.UnaryFieldAccessor.java

private Element internalCreate() {
    parent.create();/*from w  w w. j a  v a  2  s  . co  m*/
    Document domDocument = document.asDOM();
    Element element = getElement();
    if (element == null) {
        Element newElement = domDocument.createElementNS(domDocument.getNamespaceURI(), fieldName);
        Node parentNode = parent.getNode();
        Node lastAccessedNode = document.getLastAccessedNode();
        if (parentNode == lastAccessedNode) {
            parentNode.insertBefore(newElement, parentNode.getFirstChild());
        } else if (lastAccessedNode != null && lastAccessedNode.getParentNode() == parentNode) {
            parentNode.insertBefore(newElement, lastAccessedNode.getNextSibling());
        } else {
            parentNode.appendChild(newElement);
        }
        element = newElement;
        document.setLastAccessedNode(element);
    }
    return element;
}

From source file:com.gargoylesoftware.htmlunit.xml.XmlPage.java

/**
 * Creates an instance./* w  ww .j  a  va  2  s.c  om*/
 * A warning is logged if an exception is thrown while parsing the XML content
 * (for instance when the content is not a valid XML and can't be parsed).
 *
 * @param webResponse the response from the server
 * @param enclosingWindow the window that holds the page
 * @param ignoreSAXException Whether to ignore {@link SAXException} or throw it as {@link IOException}
 * @param handleXHTMLAsHTML if true elements from the XHTML namespace are handled as HTML elements instead of
 *     DOM elements
 * @throws IOException if the page could not be created
 */
public XmlPage(final WebResponse webResponse, final WebWindow enclosingWindow, final boolean ignoreSAXException,
        final boolean handleXHTMLAsHTML) throws IOException {
    super(webResponse, enclosingWindow);

    try {
        try {
            final Document document = XmlUtil.buildDocument(webResponse);
            node_ = document.getFirstChild();
        } catch (final SAXException e) {
            LOG.warn("Failed parsing XML document " + webResponse.getWebRequest().getUrl() + ": "
                    + e.getMessage());
            if (!ignoreSAXException) {
                throw new IOException(e.getMessage());
            }
        }
    } catch (final ParserConfigurationException e) {
        if (null == webResponse) {
            LOG.warn("Failed parsing XML empty document: " + e.getMessage());
        } else {
            LOG.warn("Failed parsing XML empty document " + webResponse.getWebRequest().getUrl() + ": "
                    + e.getMessage());
        }
    }

    Node node = node_;
    while (node != null) {
        XmlUtil.appendChild(this, this, node, handleXHTMLAsHTML);
        node = node.getNextSibling();
    }
}

From source file:com.mdt.rtm.Invoker.java

public Element invoke(Param... params) throws ServiceException {
    Element result;/*from   ww  w.j  av  a2 s .c om*/

    long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation;
    if (timeSinceLastInvocation < INVOCATION_INTERVAL) {
        // In order not to invoke the RTM service too often
        try {
            Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation);
        } catch (InterruptedException e) {
            throw new ServiceInternalException(
                    "Unexpected interruption while attempting to pause for some time before invoking the RTM service back",
                    e);
        }
    }

    log.debug("Invoker running at " + new Date());

    HttpClient client = new HttpClient();
    if (proxyHostName != null) {
        // Sets an HTTP proxy and the credentials for authentication
        client.getHostConfiguration().setProxy(proxyHostName, proxyPortNumber);
        if (proxyLogin != null) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyLogin, proxyPassword));
        }
    }
    GetMethod method = new GetMethod(serviceBaseUrl + REST_SERVICE_URL_POSTFIX);
    method.setRequestHeader(HttpMethodParams.HTTP_URI_CHARSET, "UTF-8");
    NameValuePair[] pairs = new NameValuePair[params.length + 1];
    int i = 0;
    for (Param param : params) {
        log.debug("  setting " + param.getName() + "=" + param.getValue());
        pairs[i++] = param.toNameValuePair();
    }
    pairs[i++] = new NameValuePair(API_SIG_PARAM, calcApiSig(params));
    method.setQueryString(pairs);

    try {
        URI methodUri;
        try {
            methodUri = method.getURI();
            log.info("Executing the method:" + methodUri);
        } catch (URIException exception) {
            String message = "Cannot determine the URI of the web method";
            log.error(message);
            throw new ServiceInternalException(message, exception);
        }
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
            throw new ServiceInternalException("method failed: " + method.getStatusLine());
        }

        // THINK: this method is deprecated, but the only way to get the body as a string, without consuming
        // the body input stream: the HttpMethodBase issues a warning but does not let you call the "setResponseStream()" method!
        String responseBodyAsString = method.getResponseBodyAsString();
        log.info("  Invocation response:\r\n" + responseBodyAsString);
        Document responseDoc = builder.parse(method.getResponseBodyAsStream());
        Element wrapperElt = responseDoc.getDocumentElement();
        if (!wrapperElt.getNodeName().equals("rsp")) {
            throw new ServiceInternalException(
                    "unexpected response returned by RTM service: " + responseBodyAsString);
        } else {
            String stat = wrapperElt.getAttribute("stat");
            if (stat.equals("fail")) {
                Node errElt = wrapperElt.getFirstChild();
                while (errElt != null
                        && (errElt.getNodeType() != Node.ELEMENT_NODE || !errElt.getNodeName().equals("err"))) {
                    errElt = errElt.getNextSibling();
                }
                if (errElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by RTM service: " + responseBodyAsString);
                } else {
                    throw new ServiceException(Integer.parseInt(((Element) errElt).getAttribute("code")),
                            ((Element) errElt).getAttribute("msg"));
                }
            } else {
                Node dataElt = wrapperElt.getFirstChild();
                while (dataElt != null && (dataElt.getNodeType() != Node.ELEMENT_NODE
                        || dataElt.getNodeName().equals("transaction") == true)) {
                    try {
                        Node nextSibling = dataElt.getNextSibling();
                        if (nextSibling == null) {
                            break;
                        } else {
                            dataElt = nextSibling;
                        }
                    } catch (IndexOutOfBoundsException exception) {
                        // Some implementation may throw this exception, instead of returning a null sibling
                        break;
                    }
                }
                if (dataElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by RTM service: " + responseBodyAsString);
                } else {
                    result = (Element) dataElt;
                }
            }
        }

    } catch (HttpException e) {
        throw new ServiceInternalException("", e);
    } catch (IOException e) {
        throw new ServiceInternalException("", e);
    } catch (SAXException e) {
        throw new ServiceInternalException("", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    lastInvocation = System.currentTimeMillis();
    return result;
}

From source file:org.weloveastrid.hive.api.Invoker.java

public Element invoke(boolean repeat, Param... params) throws ServiceException {
    long timeSinceLastInvocation = System.currentTimeMillis() - lastInvocation;
    if (timeSinceLastInvocation < INVOCATION_INTERVAL) {
        // In order not to invoke the Hiveminder service too often
        try {/*from  w w  w.ja  va2 s .c o m*/
            Thread.sleep(INVOCATION_INTERVAL - timeSinceLastInvocation);
        } catch (InterruptedException e) {
            return null;
        }
    }

    // We compute the URI
    final StringBuffer requestUri = computeRequestUri(params);
    HttpResponse response = null;

    final HttpGet request = new HttpGet("http://" //$NON-NLS-1$
            + ServiceImpl.SERVER_HOST_NAME + requestUri.toString());
    final String methodUri = request.getRequestLine().getUri();

    Element result;
    try {
        Log.i(TAG, "Executing the method:" + methodUri); //$NON-NLS-1$
        response = httpClient.execute(request);
        lastInvocation = System.currentTimeMillis();

        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            Log.e(TAG, "Method failed: " + response.getStatusLine()); //$NON-NLS-1$

            // Tim: HTTP error. Let's wait a little bit
            if (!repeat) {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    // ignore
                }
                response.getEntity().consumeContent();
                return invoke(true, params);
            }

            throw new ServiceInternalException("method failed: " + response.getStatusLine());
        }

        final Document responseDoc = builder.parse(response.getEntity().getContent());
        final Element wrapperElt = responseDoc.getDocumentElement();
        if (!wrapperElt.getNodeName().equals("rsp")) {
            throw new ServiceInternalException(
                    "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeName());
        } else {
            String stat = wrapperElt.getAttribute("stat");
            if (stat.equals("fail")) {
                Node errElt = wrapperElt.getFirstChild();
                while (errElt != null
                        && (errElt.getNodeType() != Node.ELEMENT_NODE || !errElt.getNodeName().equals("err"))) {
                    errElt = errElt.getNextSibling();
                }
                if (errElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeValue());
                } else {
                    if (SERVICE_UNAVAILABLE_CODE.equals(((Element) errElt).getAttribute("code")) && !repeat) {
                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            // ignore
                        }
                        return invoke(true, params);
                    }

                    throw new ServiceException(Integer.parseInt(((Element) errElt).getAttribute("code")),
                            ((Element) errElt).getAttribute("msg"));
                }
            } else {
                Node dataElt = wrapperElt.getFirstChild();
                while (dataElt != null && (dataElt.getNodeType() != Node.ELEMENT_NODE
                        || dataElt.getNodeName().equals("transaction") == true)) {
                    try {
                        Node nextSibling = dataElt.getNextSibling();
                        if (nextSibling == null) {
                            break;
                        } else {
                            dataElt = nextSibling;
                        }
                    } catch (IndexOutOfBoundsException exception) {
                        // Some implementation may throw this exception,
                        // instead of returning a null sibling
                        break;
                    }
                }
                if (dataElt == null) {
                    throw new ServiceInternalException(
                            "unexpected response returned by Hiveminder service: " + wrapperElt.getNodeValue());
                } else {
                    result = (Element) dataElt;
                }
            }
        }
    } catch (IOException e) {
        throw new ServiceInternalException("Error making connection: " + e.getMessage(), e);
    } catch (SAXException e) {
        // repeat call if possible.
        if (!repeat)
            return invoke(true, params);
        else
            throw new ServiceInternalException("Error parsing response. " + "Please try sync again!", e);
    } finally {
        httpClient.getConnectionManager().closeExpiredConnections();
    }

    return result;
}