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:org.eclipse.uomo.xml.test.XMLTestCase.java

private String compareElements(Element e1, Element e2, String p) {
    if (!e1.getNamespaceURI().equals(e2.getNamespaceURI()))
        return "element namespaces differ at " + p;
    if (!e1.getLocalName().equals(e2.getLocalName()))
        return "element names differ at " + p;

    String msg = compareAttributes(e1, e2, p);
    if (msg != null)
        return msg;

    p = p + "/" + e1.getNodeName();

    int i = 0;/* w  w w.j  a va 2  s  .c o m*/
    Node c1 = getNextRelevantNode(e1.getFirstChild());
    Node c2 = getNextRelevantNode(e2.getFirstChild());
    while (c1 != null && c2 != null) {
        if (c1.getNodeType() != c2.getNodeType())
            return "Different node types (" + Integer.toString(c1.getNodeType()) + "/" + c2.getNodeType()
                    + ") @ " + p;
        msg = null;
        if (c1.getNodeType() == Node.TEXT_NODE) {
            msg = compareTexts((Text) c1, (Text) c2, p + "[" + Integer.toString(i) + "]");
        } else if (c1.getNodeType() == Node.ELEMENT_NODE) {
            msg = compareElements((Element) c1, (Element) c2, p + "[" + Integer.toString(i) + "]");
        } else
            msg = "unknown node type " + Integer.toString(c1.getNodeType());
        if (msg != null)
            return msg;

        c1 = getNextRelevantNode(c1.getNextSibling());
        c2 = getNextRelevantNode(c2.getNextSibling());
        i++;
    }
    if (c1 != null && c2 == null)
        return "node present in one and not in two @ " + p;
    if (c2 != null && c1 == null)
        return "node present in two and not in one @ " + p;
    return null;
}

From source file:org.eclipse.uomo.xml.test.XMLTestCase.java

private Node getNextRelevantNode(Node node) {
    while (node != null && node.getNodeType() != Node.ELEMENT_NODE
            && !(node.getNodeType() == Node.TEXT_NODE && !StringUtils.isWhitespace(node.getNodeValue())))
        node = node.getNextSibling();
    return node;/*from www .  j  av  a  2s  . c  om*/
}

From source file:org.esa.s1tbx.sentinel1.gpf.EAPPhaseCorrectionOp.java

private void readAuxCalFile() throws Exception {

    try {/*  ww  w .j  ava 2  s.  com*/
        final DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();

        final Document doc;
        if (auxCalFile.getName().toLowerCase().endsWith(".zip")) {
            final ZipFile productZip = new ZipFile(auxCalFile, ZipFile.OPEN_READ);
            final Enumeration<? extends ZipEntry> entries = productZip.entries();
            final ZipEntry folderEntry = entries.nextElement();
            final ZipEntry zipEntry = productZip.getEntry(folderEntry.getName() + "data/s1a-aux-cal.xml");

            InputStream is = productZip.getInputStream(zipEntry);
            doc = documentBuilder.parse(is);
        } else {
            doc = documentBuilder.parse(auxCalFile);
        }

        if (doc == null) {
            System.out.println("EAPPhaseCorrection: failed to create Document for AUX_CAL file");
            return;
        }

        doc.getDocumentElement().normalize();

        final org.w3c.dom.Node calibrationParamsListNode = doc.getElementsByTagName("auxiliaryCalibration")
                .item(0).getChildNodes().item(1);

        org.w3c.dom.Node childNode = calibrationParamsListNode.getFirstChild();
        while (childNode != null) {
            if (childNode.getNodeName().equals("calibrationParams")) {
                final String swath = getNodeTextContent(childNode, "swath");
                if (swath != null && swath.contains(acquisitionMode)) {
                    final String pol = getNodeTextContent(childNode, "polarisation");
                    readOneEAPVector(childNode, swath, pol.toUpperCase());
                }
            }
            childNode = childNode.getNextSibling();
        }

    } catch (IOException e) {
        System.out.println("EAPPhaseCorrection: IOException " + e.getMessage());
    } catch (ParserConfigurationException e) {
        System.out.println("EAPPhaseCorrection: ParserConfigurationException " + e.getMessage());
    } catch (SAXException e) {
        System.out.println("EAPPhaseCorrection: SAXException " + e.getMessage());
    } catch (Exception e) {
        System.out.println("EAPPhaseCorrection: Exception " + e.getMessage());
    }
}

From source file:org.esa.s1tbx.sentinel1.gpf.EAPPhaseCorrectionOp.java

private org.w3c.dom.Node getChildNode(final org.w3c.dom.Node node, final String childNodeName) {

    org.w3c.dom.Node childNode = node.getFirstChild();
    while (childNode != null) {
        if (childNode.getNodeName().equals(childNodeName)) {
            return childNode;
        }//from w  w  w  .  j  av a2s  . co m
        childNode = childNode.getNextSibling();
    }
    return null;
}

From source file:org.etudes.component.app.melete.SubSectionUtilImpl.java

public String bringOneLevelUp(String sectionsSeqXML, String section_id) throws MeleteException {
    try {//from  www.java2 s .  co  m
        org.w3c.dom.Document subSectionW3CDOM = Xml.readDocumentFromString(sectionsSeqXML);
        org.w3c.dom.Element root = subSectionW3CDOM.getDocumentElement();
        org.w3c.dom.Element bringUpThisElement = subSectionW3CDOM.getElementById(section_id);

        if (bringUpThisElement == null) {
            throw new MeleteException("indent_left_fail");
        }
        org.w3c.dom.Node makeSiblingOf = bringUpThisElement.getParentNode();
        org.w3c.dom.Node bringUpBeforeThisElement = makeSiblingOf.getNextSibling();

        //Clone the node that needs to be moved
        org.w3c.dom.Node newNode = bringUpThisElement.cloneNode(true);
        org.w3c.dom.Node nextNode = bringUpThisElement.getNextSibling();
        org.w3c.dom.Node prevNode = null;
        //Iterate through each of the node's siblings and make them its children
        //In the process, also delete the siblings
        while (nextNode != null) {
            org.w3c.dom.Node cNode = nextNode.cloneNode(true);
            prevNode = nextNode;
            newNode.appendChild(cNode);
            nextNode = nextNode.getNextSibling();
            prevNode.getParentNode().removeChild(prevNode);
        }
        //Insert the new node, inbetween or end of list, takes null or bringUpBeforeThisElement
        makeSiblingOf.getParentNode().insertBefore(newNode, bringUpBeforeThisElement);
        //Delete node from original position
        bringUpThisElement.getParentNode().removeChild(bringUpThisElement);

        return writeDocumentToString(subSectionW3CDOM);
    } catch (MeleteException mex) {
        throw mex;
    } catch (Exception ex) {
        if (logger.isDebugEnabled()) {
            logger.error("some other error on indenting right" + ex.toString());
            ex.printStackTrace();
        }
        throw new MeleteException("indent_right_fail");
    }
}

From source file:org.exist.http.SOAPServer.java

/**
 * Writes the value of a parameter for an XQuery function call
 * /*w  ww . ja  v  a2s  . c  o  m*/
 * @param param   This StringBuffer contains the serialization of the value for XQuery
 * @param nParamSeqItem   The parameter value node from the SOAP Message
 * @param prefix   The prefix for the value (casting syntax)
 * @param postfix   The postfix for the value (casting syntax)
 * @param isAtomic   Whether the value of this type should be atomic or not (or even both)
 */
private void processParameterValue(StringBuffer param, Node nParamSeqItem, String prefix, String postfix,
        int isAtomic) throws XPathException {
    boolean justOnce = false;
    final StringBuilder whiteContent = new StringBuilder();

    try {
        final Transformer tr = TransformerFactory.newInstance().newTransformer();
        tr.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        Node n = nParamSeqItem.getFirstChild();
        final StringWriter sw = new StringWriter();
        final StreamResult result = new StreamResult(sw);
        final StringBuffer psw = sw.getBuffer();
        while (n != null) {
            switch (n.getNodeType()) {
            case Node.ELEMENT_NODE:
                if (isAtomic > 0) {
                    throw new Exception(
                            "Content of " + nParamSeqItem.getNodeName() + " must be an atomic value");
                }
                isAtomic = -1;
                if (justOnce) {
                    throw new Exception(nParamSeqItem.getNodeName() + " must have ONLY ONE element child");
                }
                final DOMSource source = new DOMSource(n);
                tr.transform(source, result);
                // Only once!
                justOnce = true;
                break;
            case Node.TEXT_NODE:
            case Node.CDATA_SECTION_NODE:
                final String nodeValue = n.getNodeValue();
                final boolean isNotWhite = !nodeValue.matches("[ \n\r\t]+");
                if (isAtomic >= 0) {
                    if (isNotWhite || isAtomic > 0) {
                        if (isAtomic == 0) {
                            isAtomic = 1;
                        }
                        psw.append(nodeValue);
                    } else if (isAtomic == 0) {
                        whiteContent.append(nodeValue);
                    }
                } else if (isNotWhite) {
                    throw new Exception(nParamSeqItem.getNodeName()
                            + " has mixed content, but it must have only one element child");
                }
                break;
            }
            n = n.getNextSibling();
        }
        if (isAtomic >= 0) {
            param.append(prefix);
        }
        if (isAtomic == 0) {
            param.append(whiteContent);
        } else {
            param.append(psw);
        }
        if (isAtomic >= 0) {
            param.append(postfix);
        }
    } catch (final Exception e) {
        LOG.debug(e.getMessage());
        throw new XPathException(e.getMessage());
    }
}

From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws IOException, ServletException {
    if (rewriteConfig == null) {
        configure();//from  ww  w  .  j  a  v a  2s. c om
        rewriteConfig = new RewriteConfig(this);
    }

    final long start = System.currentTimeMillis();
    final HttpServletRequest request = servletRequest;
    final HttpServletResponse response = servletResponse;

    if (LOG.isTraceEnabled()) {
        LOG.trace(request.getRequestURI());
    }
    final Descriptor descriptor = Descriptor.getDescriptorSingleton();
    if (descriptor != null && descriptor.requestsFiltered()) {
        final String attr = (String) request.getAttribute("XQueryURLRewrite.forwarded");
        if (attr == null) {
            //                request = new HttpServletRequestWrapper(request, /*formEncoding*/ "utf-8" );
            //logs the request if specified in the descriptor
            descriptor.doLogRequestInReplayLog(request);

            request.setAttribute("XQueryURLRewrite.forwarded", "true");
        }
    }

    Subject user = defaultUser;

    Subject requestUser = HttpAccount.getUserFromServletRequest(request);
    if (requestUser != null) {
        user = requestUser;
    } else {
        // Secondly try basic authentication
        final String auth = request.getHeader("Authorization");
        if (auth != null) {
            requestUser = authenticator.authenticate(request, response);
            if (requestUser != null) {
                user = requestUser;
            }
        }
    }

    try {
        configure();
        //checkCache(user);

        final RequestWrapper modifiedRequest = new RequestWrapper(request);
        final URLRewrite staticRewrite = rewriteConfig.lookup(modifiedRequest);
        if (staticRewrite != null && !staticRewrite.isControllerForward()) {
            modifiedRequest.setPaths(staticRewrite.resolve(modifiedRequest), staticRewrite.getPrefix());

            if (LOG.isTraceEnabled()) {
                LOG.trace("Forwarding to target: " + staticRewrite.getTarget());
            }
            staticRewrite.doRewrite(modifiedRequest, response);
        } else {

            if (LOG.isTraceEnabled()) {
                LOG.trace("Processing request URI: " + request.getRequestURI());
            }
            if (staticRewrite != null) {
                // fix the request URI
                staticRewrite.updateRequest(modifiedRequest);
            }

            // check if the request URI is already in the url cache
            ModelAndView modelView = getFromCache(request.getHeader("Host") + request.getRequestURI(), user);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Checked cache for URI: " + modifiedRequest.getRequestURI() + " original: "
                        + request.getRequestURI());
            }
            // no: create a new model and view configuration
            if (modelView == null) {
                modelView = new ModelAndView();
                // Execute the query
                Sequence result = Sequence.EMPTY_SEQUENCE;
                DBBroker broker = null;
                try {
                    broker = pool.get(user);
                    modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI());

                    final Properties outputProperties = new Properties();

                    outputProperties.setProperty(OutputKeys.INDENT, "yes");
                    outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
                    outputProperties.setProperty(OutputKeys.MEDIA_TYPE, MimeType.XML_TYPE.getName());

                    result = runQuery(broker, modifiedRequest, response, modelView, staticRewrite,
                            outputProperties);

                    logResult(broker, result);

                    if (response.isCommitted()) {
                        return;
                    }

                    // process the query result
                    if (result.getItemCount() == 1) {
                        final Item resource = result.itemAt(0);
                        if (!Type.subTypeOf(resource.getType(), Type.NODE)) {
                            throw new ServletException(
                                    "XQueryURLRewrite: urlrewrite query should return an element!");
                        }
                        Node node = ((NodeValue) resource).getNode();
                        if (node.getNodeType() == Node.DOCUMENT_NODE) {
                            node = ((Document) node).getDocumentElement();
                        }
                        if (node.getNodeType() != Node.ELEMENT_NODE) {
                            //throw new ServletException("Redirect XQuery should return an XML element!");
                            response(broker, response, outputProperties, result);
                            return;
                        }
                        Element elem = (Element) node;
                        if (!(Namespaces.EXIST_NS.equals(elem.getNamespaceURI()))) {
                            response(broker, response, outputProperties, result);
                            return;
                            //                            throw new ServletException("Redirect XQuery should return an element in namespace " + Namespaces.EXIST_NS);
                        }

                        if (Namespaces.EXIST_NS.equals(elem.getNamespaceURI())
                                && "dispatch".equals(elem.getLocalName())) {
                            node = elem.getFirstChild();
                            while (node != null) {
                                if (node.getNodeType() == Node.ELEMENT_NODE
                                        && Namespaces.EXIST_NS.equals(node.getNamespaceURI())) {
                                    final Element action = (Element) node;
                                    if ("view".equals(action.getLocalName())) {
                                        parseViews(modifiedRequest, action, modelView);
                                    } else if ("error-handler".equals(action.getLocalName())) {
                                        parseErrorHandlers(modifiedRequest, action, modelView);
                                    } else if ("cache-control".equals(action.getLocalName())) {
                                        final String option = action.getAttribute("cache");
                                        modelView.setUseCache("yes".equals(option));
                                    } else {
                                        final URLRewrite urw = parseAction(modifiedRequest, action);
                                        if (urw != null) {
                                            modelView.setModel(urw);
                                        }
                                    }
                                }
                                node = node.getNextSibling();
                            }
                            if (modelView.getModel() == null) {
                                modelView.setModel(new PassThrough(config, elem, modifiedRequest));
                            }
                        } else if (Namespaces.EXIST_NS.equals(elem.getNamespaceURI())
                                && "ignore".equals(elem.getLocalName())) {
                            modelView.setModel(new PassThrough(config, elem, modifiedRequest));
                            final NodeList nl = elem.getElementsByTagNameNS(Namespaces.EXIST_NS,
                                    "cache-control");
                            if (nl.getLength() > 0) {
                                elem = (Element) nl.item(0);
                                final String option = elem.getAttribute("cache");
                                modelView.setUseCache("yes".equals(option));
                            }
                        } else {
                            response(broker, response, outputProperties, result);
                            return;
                        }
                    } else if (result.getItemCount() > 1) {
                        response(broker, response, outputProperties, result);
                        return;
                    }

                    if (modelView.useCache()) {
                        LOG.debug("Caching request to " + request.getRequestURI());
                        urlCache.put(modifiedRequest.getHeader("Host") + request.getRequestURI(), modelView);
                    }

                } finally {
                    pool.release(broker);
                }

                // store the original request URI to org.exist.forward.request-uri
                modifiedRequest.setAttribute(RQ_ATTR_REQUEST_URI, request.getRequestURI());
                modifiedRequest.setAttribute(RQ_ATTR_SERVLET_PATH, request.getServletPath());

            }
            if (LOG.isTraceEnabled()) {
                LOG.trace("URLRewrite took " + (System.currentTimeMillis() - start) + "ms.");
            }
            final HttpServletResponse wrappedResponse = new CachingResponseWrapper(response,
                    modelView.hasViews() || modelView.hasErrorHandlers());
            if (modelView.getModel() == null) {
                modelView.setModel(new PassThrough(config, modifiedRequest));
            }

            if (staticRewrite != null) {
                if (modelView.getModel().doResolve()) {
                    staticRewrite.rewriteRequest(modifiedRequest);
                } else {
                    modelView.getModel().setAbsolutePath(modifiedRequest);
                }
            }
            modifiedRequest.allowCaching(!modelView.hasViews());
            doRewrite(modelView.getModel(), modifiedRequest, wrappedResponse);

            int status = ((CachingResponseWrapper) wrappedResponse).getStatus();
            if (status == HttpServletResponse.SC_NOT_MODIFIED) {
                response.flushBuffer();
            } else if (status < 400) {
                if (modelView.hasViews()) {
                    applyViews(modelView, modelView.views, response, modifiedRequest, wrappedResponse);
                } else {
                    ((CachingResponseWrapper) wrappedResponse).flush();
                }
            } else {
                // HTTP response code indicates an error
                if (modelView.hasErrorHandlers()) {
                    final byte[] data = ((CachingResponseWrapper) wrappedResponse).getData();
                    if (data != null) {
                        modifiedRequest.setAttribute(RQ_ATTR_ERROR, new String(data, UTF_8));
                    }
                    applyViews(modelView, modelView.errorHandlers, response, modifiedRequest, wrappedResponse);
                } else {
                    flushError(response, wrappedResponse);
                }
            }
        }
        //            Sequence result;
        //            if ((result = (Sequence) request.getAttribute(RQ_ATTR_RESULT)) != null) {
        //                writeResults(response, broker, result);
        //            }
    } catch (final Throwable e) {
        LOG.error("Error while processing " + servletRequest.getRequestURI() + ": " + e.getMessage(), e);
        throw new ServletException("An error occurred while processing request to "
                + servletRequest.getRequestURI() + ": " + e.getMessage(), e);

    }
}

From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java

private void parseViews(HttpServletRequest request, Element view, ModelAndView modelView)
        throws ServletException {
    Node node = view.getFirstChild();
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE && Namespaces.EXIST_NS.equals(node.getNamespaceURI())) {
            final URLRewrite urw = parseAction(request, (Element) node);
            if (urw != null) {
                modelView.addView(urw);//from   w  w w  .  j  av  a 2 s  .  c om
            }
        }
        node = node.getNextSibling();
    }
}

From source file:org.exist.http.urlrewrite.XQueryURLRewrite.java

private void parseErrorHandlers(HttpServletRequest request, Element view, ModelAndView modelView)
        throws ServletException {
    Node node = view.getFirstChild();
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE && Namespaces.EXIST_NS.equals(node.getNamespaceURI())) {
            final URLRewrite urw = parseAction(request, (Element) node);
            if (urw != null) {
                modelView.addErrorHandler(urw);
            }//from  w ww  . ja  va  2 s .co m
        }
        node = node.getNextSibling();
    }
}

From source file:org.exist.xquery.modules.mail.SendEmailFunction.java

/**
 * Constructs a mail Object from an XML representation of an email
 *
 * The XML email Representation is expected to look something like this
 *
 * <mail>//from  ww w .  j  a v a 2  s .co  m
 *    <from></from>
 *    <reply-to></reply-to>
 *    <to></to>
 *    <cc></cc>
 *    <bcc></bcc>
 *    <subject></subject>
 *    <message>
 *       <text></text>
 *       <xhtml></xhtml>
 *    </message>
 * </mail>
 *
 * @param mailElements   The XML mail Node
 * @return      A mail Object representing the XML mail Node
 */
private List<Mail> parseMailElement(List<Element> mailElements) throws TransformerException {
    List<Mail> mails = new ArrayList<>();

    for (Element mailElement : mailElements) {
        //Make sure that message has a Mail node
        if (mailElement.getLocalName().equals("mail")) {
            //New mail Object
            Mail mail = new Mail();

            //Get the First Child
            Node child = mailElement.getFirstChild();
            while (child != null) {
                //Parse each of the child nodes
                if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) {
                    switch (child.getLocalName()) {
                    case "from":
                        mail.setFrom(child.getFirstChild().getNodeValue());
                        break;
                    case "reply-to":
                        mail.setReplyTo(child.getFirstChild().getNodeValue());
                        break;
                    case "to":
                        mail.addTo(child.getFirstChild().getNodeValue());
                        break;
                    case "cc":
                        mail.addCC(child.getFirstChild().getNodeValue());
                        break;
                    case "bcc":
                        mail.addBCC(child.getFirstChild().getNodeValue());
                        break;
                    case "subject":
                        mail.setSubject(child.getFirstChild().getNodeValue());
                        break;
                    case "message":
                        //If the message node, then parse the child text and xhtml nodes
                        Node bodyPart = child.getFirstChild();
                        while (bodyPart != null) {
                            if (bodyPart.getLocalName().equals("text")) {
                                mail.setText(bodyPart.getFirstChild().getNodeValue());
                            } else if (bodyPart.getLocalName().equals("xhtml")) {
                                //Convert everything inside <xhtml></xhtml> to text
                                TransformerFactory transFactory = TransformerFactory.newInstance();
                                Transformer transformer = transFactory.newTransformer();
                                DOMSource source = new DOMSource(bodyPart.getFirstChild());
                                StringWriter strWriter = new StringWriter();
                                StreamResult result = new StreamResult(strWriter);
                                transformer.transform(source, result);

                                mail.setXHTML(strWriter.toString());
                            }

                            //next body part
                            bodyPart = bodyPart.getNextSibling();
                        }
                        break;
                    case "attachment":
                        Element attachment = (Element) child;
                        MailAttachment ma = new MailAttachment(attachment.getAttribute("filename"),
                                attachment.getAttribute("mimetype"), attachment.getFirstChild().getNodeValue());
                        mail.addAttachment(ma);
                        break;
                    }
                }

                //next node
                child = child.getNextSibling();

            }
            mails.add(mail);
        }
    }

    return mails;
}