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.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  www.j  av a 2s .c om
 *    <from></from>
 *    <reply-to></reply-to>
 *    <to></to>
 *    <cc></cc>
 *    <bcc></bcc>
 *    <subject></subject>
 *    <message>
 *       <text charset="" encoding=""></text>
 *       <xhtml charset="" encoding=""></xhtml>
 *       <generic charset="" type="" encoding=""></generic>
 *    </message>
 *    <attachment mimetype="" filename=""></attachment>
 * </mail>
 *
 * @param mailElements   The XML mail Node
 * @return      A mail Object representing the XML mail Node
 */
private List<Message> parseMessageElement(Session session, List<Element> mailElements)
        throws IOException, MessagingException, TransformerException {
    List<Message> mails = new ArrayList<>();

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

            ArrayList<InternetAddress> replyTo = new ArrayList<>();
            boolean fromWasSet = false;
            MimeBodyPart body = null;
            Multipart multibody = null;
            ArrayList<MimeBodyPart> attachments = new ArrayList<>();
            String firstContent = null;
            String firstContentType = null;
            String firstCharset = null;
            String firstEncoding = null;

            //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":
                        // set the from and to address
                        InternetAddress[] addressFrom = {
                                new InternetAddress(child.getFirstChild().getNodeValue()) };
                        msg.addFrom(addressFrom);
                        fromWasSet = true;
                        break;
                    case "reply-to":
                        // As we can only set the reply-to, not add them, let's keep
                        // all of them in a list
                        replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue()));
                        msg.setReplyTo(replyTo.toArray(new InternetAddress[0]));
                        break;
                    case "to":
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "cc":
                        msg.addRecipient(Message.RecipientType.CC,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "bcc":
                        msg.addRecipient(Message.RecipientType.BCC,
                                new InternetAddress(child.getFirstChild().getNodeValue()));
                        break;
                    case "subject":
                        msg.setSubject(child.getFirstChild().getNodeValue());
                        break;
                    case "header":
                        // Optional : You can also set your custom headers in the Email if you Want
                        msg.addHeader(((Element) child).getAttribute("name"),
                                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.getNodeType() != Node.ELEMENT_NODE)
                                continue;

                            Element elementBodyPart = (Element) bodyPart;
                            String content = null;
                            String contentType = null;

                            if (bodyPart.getLocalName().equals("text")) {
                                // Setting the Subject and Content Type
                                content = bodyPart.getFirstChild().getNodeValue();
                                contentType = "plain";
                            } 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);

                                content = strWriter.toString();
                                contentType = "html";
                            } else if (bodyPart.getLocalName().equals("generic")) {
                                // Setting the Subject and Content Type
                                content = elementBodyPart.getFirstChild().getNodeValue();
                                contentType = elementBodyPart.getAttribute("type");
                            }

                            // Now, time to store it
                            if (content != null && contentType != null && contentType.length() > 0) {
                                String charset = elementBodyPart.getAttribute("charset");
                                String encoding = elementBodyPart.getAttribute("encoding");

                                if (body != null && multibody == null) {
                                    multibody = new MimeMultipart("alternative");
                                    multibody.addBodyPart(body);
                                }

                                if (StringUtils.isEmpty(charset)) {
                                    charset = "UTF-8";
                                }

                                if (StringUtils.isEmpty(encoding)) {
                                    encoding = "quoted-printable";
                                }

                                if (body == null) {
                                    firstContent = content;
                                    firstCharset = charset;
                                    firstContentType = contentType;
                                    firstEncoding = encoding;
                                }
                                body = new MimeBodyPart();
                                body.setText(content, charset, contentType);
                                if (encoding != null) {
                                    body.setHeader("Content-Transfer-Encoding", encoding);
                                }
                                if (multibody != null)
                                    multibody.addBodyPart(body);
                            }

                            //next body part
                            bodyPart = bodyPart.getNextSibling();
                        }
                        break;
                    case "attachment":
                        Element attachment = (Element) child;
                        MimeBodyPart part;
                        // if mimetype indicates a binary resource, assume the content is base64 encoded
                        if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) {
                            part = new MimeBodyPart();
                        } else {
                            part = new PreencodedMimeBodyPart("base64");
                        }
                        StringBuilder content = new StringBuilder();
                        Node attachChild = attachment.getFirstChild();
                        while (attachChild != null) {
                            if (attachChild.getNodeType() == Node.ELEMENT_NODE) {
                                TransformerFactory transFactory = TransformerFactory.newInstance();
                                Transformer transformer = transFactory.newTransformer();
                                DOMSource source = new DOMSource(attachChild);
                                StringWriter strWriter = new StringWriter();
                                StreamResult result = new StreamResult(strWriter);
                                transformer.transform(source, result);

                                content.append(strWriter.toString());
                            } else {
                                content.append(attachChild.getNodeValue());
                            }
                            attachChild = attachChild.getNextSibling();
                        }
                        part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(),
                                attachment.getAttribute("mimetype"))));
                        part.setFileName(attachment.getAttribute("filename"));
                        //                            part.setHeader("Content-Transfer-Encoding", "base64");
                        attachments.add(part);
                        break;
                    }
                }

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

            }
            // Lost from
            if (!fromWasSet)
                msg.setFrom();

            // Preparing content and attachments
            if (attachments.size() > 0) {
                if (multibody == null) {
                    multibody = new MimeMultipart("mixed");
                    if (body != null) {
                        multibody.addBodyPart(body);
                    }
                } else {
                    MimeMultipart container = new MimeMultipart("mixed");
                    MimeBodyPart containerBody = new MimeBodyPart();
                    containerBody.setContent(multibody);
                    container.addBodyPart(containerBody);
                    multibody = container;
                }
                for (MimeBodyPart part : attachments) {
                    multibody.addBodyPart(part);
                }
            }

            // And now setting-up content
            if (multibody != null) {
                msg.setContent(multibody);
            } else if (body != null) {
                msg.setText(firstContent, firstCharset, firstContentType);
                if (firstEncoding != null) {
                    msg.setHeader("Content-Transfer-Encoding", firstEncoding);
                }
            }

            msg.saveChanges();
            mails.add(msg);
        }
    }

    return mails;
}

From source file:org.firesoa.common.jxpath.model.dom.W3CDomFactory.java

private void addW3CDomElement(Node parent, int index, String tag, String namespaceURI) {
    try {//w  w w  .j  a  va  2  s  .  c  o m
        Node child = parent.getFirstChild();
        int count = 0;
        while (child != null) {
            if (child.getNodeName().equals(tag)) {
                count++;
            }
            child = child.getNextSibling();
        }

        // Keep inserting new elements until we have index + 1 of them
        while (count <= index) {
            Document doc = parent.getOwnerDocument();
            Node newElement;
            if (namespaceURI == null) {
                newElement = doc.createElement(tag);
            } else {
                newElement = doc.createElementNS(namespaceURI, tag);
            }

            parent.appendChild(newElement);
            count++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.geotools.geometry.jts.spatialschema.geometry.GeometryTestParser.java

/**
 * Processes the root "run" node//from   w  w  w .  jav  a  2 s  . c  o m
 * @param node
 * @return
 * @throws ParseException
 */
public GeometryTestContainer processRootNode(Node node) throws ParseException {
    if (!node.getNodeName().equalsIgnoreCase("run")) {
        throw new ParseException("Expected run tag, found " + node.getNodeName(), 0);
    }
    GeometryTestContainer test = new GeometryTestContainer();
    Node child = node.getFirstChild();
    String precisionModel = "FLOATING";
    while (child != null) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            String name = child.getNodeName();
            if (name.equalsIgnoreCase("case")) {
                GeometryTestCase testCase = readTestCase(child);
                test.addTestCase(testCase);
            } else if (name.equalsIgnoreCase("precisionmodel")) {
                precisionModel = getPrecisionModel(child);
            } else {
                throw new ParseException("Unexpected: " + name, 0);
            }
        }
        child = child.getNextSibling();
    }
    return test;
}

From source file:org.geotools.geometry.jts.spatialschema.geometry.GeometryTestParser.java

/**
 * parse a single test case//  ww w .  j a  v a  2  s. c o m
 *
 * From looking at various JTS test cases and seeing how their
 * testbuilder program works, I think its safe to assume that
 * there will always be just one or two objects, named a and
 * b.
 *
 * @param testCaseNode
 * @return
 */
private GeometryTestCase readTestCase(Node testCaseNode) throws ParseException {
    Node child = testCaseNode.getFirstChild();
    GeometryTestOperation operation = null;

    GeometryTestCase testCase = new GeometryTestCase();

    while (child != null) {
        if (child.getNodeType() == Node.ELEMENT_NODE) {
            String name = child.getNodeName();
            if (name.equalsIgnoreCase("test")) {
                testCase.addTestOperation(loadTestOperation(child));
            } else if (name.equalsIgnoreCase("a")) {
                testCase.setGeometryA(loadTestGeometry(child));
            } else if (name.equalsIgnoreCase("b")) {
                testCase.setGeometryB(loadTestGeometry(child));
            } else if (name.equalsIgnoreCase("desc")) {
                testCase.setDescription(getNodeText(child));

            } else {
                throw new ParseException("Unexpected: " + name, 0);
            }
        }
        child = child.getNextSibling();
    }

    return testCase;
}

From source file:org.geotools.geometry.jts.spatialschema.geometry.GeometryTestParser.java

private Node getNamedChild(Node node, String name) {
    Node child = node.getFirstChild();
    while (child != null) {
        if (name.equalsIgnoreCase(child.getNodeName())) {
            return child;
        }/*from  w w  w  .j  a  v  a  2s  . c  om*/
        child = child.getNextSibling();
    }
    return null;
}

From source file:org.gvnix.web.screen.roo.addon.WebScreenOperationsImpl.java

/**
 * Updates load-scripts.tagx adding in the right position some elements:
 * <ul>/*from  w w  w .  j  a  v a2  s . co  m*/
 * <li><code>spring:url</code> elements for JS and CSS</li>
 * <li><code>link</code> element for CSS</li>
 * <li><code>script</code> element for JS</li>
 * </ul>
 */
private void modifyLoadScriptsTagx() {
    PathResolver pathResolver = projectOperations.getPathResolver();
    String loadScriptsTagx = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            "WEB-INF/tags/util/load-scripts.tagx");

    if (!fileManager.exists(loadScriptsTagx)) {
        // load-scripts.tagx doesn't exist, so nothing to do
        return;
    }

    InputStream loadScriptsIs = fileManager.getInputStream(loadScriptsTagx);

    Document loadScriptsXml;
    try {
        loadScriptsXml = XmlUtils.getDocumentBuilder().parse(loadScriptsIs);
    } catch (Exception ex) {
        throw new IllegalStateException("Could not open load-scripts.tagx file", ex);
    }

    Element lsRoot = loadScriptsXml.getDocumentElement();

    Node nextSibiling;

    // spring:url elements
    Element testElement = XmlUtils.findFirstElement("/root/url[@var='pattern_css_url']", lsRoot);
    if (testElement == null) {
        Element urlPatternCss = new XmlElementBuilder("spring:url", loadScriptsXml)
                .addAttribute(VALUE, "/resources/styles/pattern.css").addAttribute(VAR, "pattern_css_url")
                .build();
        Element urlQlJs = new XmlElementBuilder("spring:url", loadScriptsXml)
                .addAttribute(VALUE, "/resources/scripts/quicklinks.js").addAttribute(VAR, "qljs_url").build();
        // Add i18n messages for quicklinks.js
        List<Element> qlJsI18n = new ArrayList<Element>();
        qlJsI18n.add(new XmlElementBuilder("spring:message", loadScriptsXml)
                .addAttribute("code", "message_selectrowtodelete_alert")
                .addAttribute(VAR, "msg_selectrowtodelete_alert").addAttribute("htmlEscape", "false").build());
        qlJsI18n.add(new XmlElementBuilder("spring:message", loadScriptsXml)
                .addAttribute("code", "message_selectrowtoupdate_alert")
                .addAttribute(VAR, "msg_selectrowtoupdate_alert").addAttribute("htmlEscape", "false").build());
        qlJsI18n.add(new XmlElementBuilder("spring:message", loadScriptsXml)
                .addAttribute("code", "message_updateonlyonerow_alert")
                .addAttribute(VAR, "msg_updateonlyonerow_alert").addAttribute("htmlEscape", "false").build());
        StringBuilder qlJsI18nScriptText = new StringBuilder("<!--\n");
        qlJsI18nScriptText.append("var GVNIX_MSG_SELECT_ROW_TO_DELETE=\"${msg_selectrowtodelete_alert}\";\n");
        qlJsI18nScriptText.append("var GVNIX_MSG_SELECT_ROW_TO_UPDATE=\"${msg_selectrowtoupdate_alert}\";\n");
        qlJsI18nScriptText.append("var GVNIX_MSG_UPDATE_ONLY_ONE_ROW=\"${msg_updateonlyonerow_alert}\";\n");
        qlJsI18nScriptText.append("-->\n");
        Element qlJsI18nScript = new XmlElementBuilder("script", loadScriptsXml)
                .setText(qlJsI18nScriptText.toString()).build();
        List<Element> springUrlElements = XmlUtils.findElements("/root/url", lsRoot);
        // Element lastSpringUrl = null;
        if (!springUrlElements.isEmpty()) {
            Element lastSpringUrl = springUrlElements.get(springUrlElements.size() - 1);
            if (lastSpringUrl != null) {
                nextSibiling = lastSpringUrl.getNextSibling().getNextSibling();
                lsRoot.insertBefore(urlPatternCss, nextSibiling);
                lsRoot.insertBefore(urlQlJs, nextSibiling);
                lsRoot.insertBefore(qlJsI18nScript, nextSibiling);
                for (Element item : qlJsI18n) {
                    lsRoot.insertBefore(item, qlJsI18nScript);
                }
            }
        } else {
            // Add at the end of the document
            lsRoot.appendChild(urlPatternCss);
            lsRoot.appendChild(urlQlJs);
            for (Element item : qlJsI18n) {
                lsRoot.appendChild(item);
            }
            lsRoot.appendChild(qlJsI18nScript);
        }
    }

    // pattern.css stylesheet element
    testElement = XmlUtils.findFirstElement("/root/link[@href='${pattern_css_url}']", lsRoot);
    if (testElement == null) {
        Element linkPatternCss = new XmlElementBuilder("link", loadScriptsXml).addAttribute("rel", "stylesheet")
                .addAttribute("type", "text/css").addAttribute("media", "screen")
                .addAttribute("href", "${pattern_css_url}").build();
        linkPatternCss.appendChild(loadScriptsXml.createComment(" required for FF3 and Opera "));
        Node linkTrundraCssNode = XmlUtils.findFirstElement("/root/link[@href='${tundra_url}']", lsRoot);
        if (linkTrundraCssNode != null) {
            nextSibiling = linkTrundraCssNode.getNextSibling().getNextSibling();
            lsRoot.insertBefore(linkPatternCss, nextSibiling);
        } else {
            // Add ass last link element
            // Element lastLink = null;
            List<Element> linkElements = XmlUtils.findElements("/root/link", lsRoot);
            if (!linkElements.isEmpty()) {
                Element lastLink = linkElements.get(linkElements.size() - 1);
                if (lastLink != null) {
                    nextSibiling = lastLink.getNextSibling().getNextSibling();
                    lsRoot.insertBefore(linkPatternCss, nextSibiling);
                }
            } else {
                // Add at the end of document
                lsRoot.appendChild(linkPatternCss);
            }
        }
    }

    // quicklinks.js script element
    testElement = XmlUtils.findFirstElement("/root/script[@src='${qljs_url}']", lsRoot);
    if (testElement == null) {
        Element scriptQlJs = new XmlElementBuilder("script", loadScriptsXml).addAttribute("src", "${qljs_url}")
                .addAttribute("type", "text/javascript").build();
        scriptQlJs.appendChild(loadScriptsXml.createComment(" required for FF3 and Opera "));
        List<Element> scrtiptElements = XmlUtils.findElements("/root/script", lsRoot);
        // Element lastScript = null;
        if (!scrtiptElements.isEmpty()) {
            Element lastScript = scrtiptElements.get(scrtiptElements.size() - 1);
            if (lastScript != null) {
                nextSibiling = lastScript.getNextSibling().getNextSibling();
                lsRoot.insertBefore(scriptQlJs, nextSibiling);
            }
        } else {
            // Add at the end of document
            lsRoot.appendChild(scriptQlJs);
        }
    }

    writeToDiskIfNecessary(loadScriptsTagx, loadScriptsXml.getDocumentElement());

}

From source file:org.gvnix.web.theme.roo.addon.ThemeOperationsImpl.java

/**
 * Updates load-scripts.tagx adding in the right position some elements:
 * <ul>// w  w w  . j a  v  a  2s.com
 * <li><code>spring:url</code> elements for JS and CSS</li>
 * <li><code>link</code> element for CSS</li>
 * <li><code>script</code> element for JS</li>
 * </ul>
 */
private void modifyLoadScriptsTagx() {
    PathResolver pathResolver = projectOperations.getPathResolver();
    String loadScriptsTagx = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            "WEB-INF/tags/util/load-scripts.tagx");

    if (!fileManager.exists(loadScriptsTagx)) {
        // load-scripts.tagx doesn't exist, so nothing to do
        return;
    }

    InputStream loadScriptsIs = fileManager.getInputStream(loadScriptsTagx);

    Document loadScriptsXml;
    try {
        loadScriptsXml = org.springframework.roo.support.util.XmlUtils.getDocumentBuilder()
                .parse(loadScriptsIs);
    } catch (Exception ex) {
        throw new IllegalStateException("Could not open load-scripts.tagx file", ex);
    }

    Element lsRoot = loadScriptsXml.getDocumentElement();
    // Add new tag namesapces
    Element jspRoot = org.springframework.roo.support.util.XmlUtils.findFirstElement("/root", lsRoot);
    jspRoot.setAttribute("xmlns:util", "urn:jsptagdir:/WEB-INF/tags/util");

    Node nextSibiling;

    // spring:url elements
    Element testElement = org.springframework.roo.support.util.XmlUtils
            .findFirstElement("/root/url[@var='roo_css-ie_url']", lsRoot);
    if (testElement == null) {
        Element urlCitIECss = new XmlElementBuilder(SPRING_URL, loadScriptsXml)
                .addAttribute(VALUE_ATTRIBUTE, "/resources/styles/cit-IE.css")
                .addAttribute(VAR_ATTRIBUTE, "roo_css-ie_url").build();
        Element urlApplicationCss = new XmlElementBuilder(SPRING_URL, loadScriptsXml)
                .addAttribute(VALUE_ATTRIBUTE, "/resources/styles/application.css")
                .addAttribute(VAR_ATTRIBUTE, "application_css_url").build();
        Element urlYuiEventJs = new XmlElementBuilder(SPRING_URL, loadScriptsXml)
                .addAttribute(VALUE_ATTRIBUTE, "/resources/scripts/yui/yahoo-dom-event.js")
                .addAttribute(VAR_ATTRIBUTE, "yui_event").build();
        Element urlYuiCoreJs = new XmlElementBuilder(SPRING_URL, loadScriptsXml)
                .addAttribute(VALUE_ATTRIBUTE, "/resources/scripts/yui/container_core-min.js")
                .addAttribute(VAR_ATTRIBUTE, "yui_core").build();
        Element urlYoiMenuJs = new XmlElementBuilder(SPRING_URL, loadScriptsXml)
                .addAttribute(VALUE_ATTRIBUTE, "/resources/scripts/yui/menu-min.js")
                .addAttribute(VAR_ATTRIBUTE, "yui_menu").build();
        Element urlCitJs = new XmlElementBuilder(SPRING_URL, loadScriptsXml)
                .addAttribute(VALUE_ATTRIBUTE, "/resources/scripts/utils.js")
                .addAttribute(VAR_ATTRIBUTE, "cit_js_url").build();
        List<Element> springUrlElements = org.springframework.roo.support.util.XmlUtils
                .findElements("/root/url", lsRoot);
        // Element lastSpringUrl = null;
        if (!springUrlElements.isEmpty()) {
            Element lastSpringUrl = springUrlElements.get(springUrlElements.size() - 1);
            if (lastSpringUrl != null) {
                nextSibiling = lastSpringUrl.getNextSibling().getNextSibling();
                lsRoot.insertBefore(urlCitIECss, nextSibiling);
                lsRoot.insertBefore(urlApplicationCss, nextSibiling);
                lsRoot.insertBefore(urlYuiEventJs, nextSibiling);
                lsRoot.insertBefore(urlYuiCoreJs, nextSibiling);
                lsRoot.insertBefore(urlYoiMenuJs, nextSibiling);
                lsRoot.insertBefore(urlCitJs, nextSibiling);
            }
        } else {
            // Add at the end of the document
            lsRoot.appendChild(urlCitIECss);
            lsRoot.appendChild(urlApplicationCss);
            lsRoot.appendChild(urlYuiEventJs);
            lsRoot.appendChild(urlYuiCoreJs);
            lsRoot.appendChild(urlYoiMenuJs);
            lsRoot.appendChild(urlCitJs);
        }
    }

    Element setUserLocale = org.springframework.roo.support.util.XmlUtils.findFirstElement("/root/set/out",
            lsRoot);
    setUserLocale.setAttribute("default", "es");

    // cit-IE.css stylesheet element
    testElement = org.springframework.roo.support.util.XmlUtils
            .findFirstElement("/root/iecondition/link[@href='${roo_css-ie_url}']", lsRoot);
    if (testElement == null) {
        Element ifIE = new XmlElementBuilder("util:iecondition", loadScriptsXml).build();

        Element linkCitIECss = new XmlElementBuilder("link", loadScriptsXml).addAttribute("rel", "stylesheet")
                .addAttribute(TYPE_ATTRIBUTE, "text/css").addAttribute(HREF_ATTRIBUTE, "${roo_css-ie_url}")
                .build();
        ifIE.appendChild(linkCitIECss);
        Node linkFaviconNode = org.springframework.roo.support.util.XmlUtils
                .findFirstElement("/root/link[@href='${favicon}']", lsRoot);
        if (linkFaviconNode != null) {
            nextSibiling = linkFaviconNode.getNextSibling().getNextSibling();
            lsRoot.insertBefore(ifIE, linkFaviconNode);
        } else {
            // Add ass last link element
            // Element lastLink = null;
            List<Element> linkElements = org.springframework.roo.support.util.XmlUtils
                    .findElements("/root/link", lsRoot);
            if (!linkElements.isEmpty()) {
                Element lastLink = linkElements.get(linkElements.size() - 1);
                if (lastLink != null) {
                    nextSibiling = lastLink.getNextSibling().getNextSibling();
                    lsRoot.insertBefore(ifIE, nextSibiling);
                }
            } else {
                // Add at the end of document
                lsRoot.appendChild(ifIE);
            }
        }
    }

    // pattern.css stylesheet element
    testElement = org.springframework.roo.support.util.XmlUtils
            .findFirstElement("/root/link[@href='${application_css_url}']", lsRoot);
    if (testElement == null) {
        Element linkApplicationCss = new XmlElementBuilder("link", loadScriptsXml)
                .addAttribute("rel", "stylesheet").addAttribute(TYPE_ATTRIBUTE, "text/css")
                .addAttribute("media", "screen").addAttribute(HREF_ATTRIBUTE, "${application_css_url}").build();
        linkApplicationCss.appendChild(loadScriptsXml.createComment(FF3_AND_OPERA));
        Node linkFaviconNode = org.springframework.roo.support.util.XmlUtils
                .findFirstElement("/root/link[@href='${favicon}']", lsRoot);
        if (linkFaviconNode != null) {
            nextSibiling = linkFaviconNode.getNextSibling().getNextSibling();
            lsRoot.insertBefore(linkApplicationCss, linkFaviconNode);
        } else {
            // Add ass last link element
            // Element lastLink = null;
            List<Element> linkElements = org.springframework.roo.support.util.XmlUtils
                    .findElements("/root/link", lsRoot);
            if (!linkElements.isEmpty()) {
                Element lastLink = linkElements.get(linkElements.size() - 1);
                if (lastLink != null) {
                    nextSibiling = lastLink.getNextSibling().getNextSibling();
                    lsRoot.insertBefore(linkApplicationCss, nextSibiling);
                }
            } else {
                // Add at the end of document
                lsRoot.appendChild(linkApplicationCss);
            }
        }
    }

    // utils.js script element
    testElement = org.springframework.roo.support.util.XmlUtils
            .findFirstElement("/root/script[@src='${cit_js_url}']", lsRoot);
    if (testElement == null) {
        Element scriptYuiEventJs = new XmlElementBuilder(SCRIPT, loadScriptsXml)
                .addAttribute(SRC, "${yui_event}").addAttribute(TYPE_ATTRIBUTE, TEXT_JSCRPT).build();
        scriptYuiEventJs.appendChild(loadScriptsXml.createComment(FF3_AND_OPERA));
        Element scriptYuiCoreJs = new XmlElementBuilder(SCRIPT, loadScriptsXml).addAttribute(SRC, "${yui_core}")
                .addAttribute(TYPE_ATTRIBUTE, TEXT_JSCRPT).build();
        scriptYuiCoreJs.appendChild(loadScriptsXml.createComment(FF3_AND_OPERA));
        Element scriptYoiMenuJs = new XmlElementBuilder(SCRIPT, loadScriptsXml).addAttribute(SRC, "${yui_menu}")
                .addAttribute(TYPE_ATTRIBUTE, TEXT_JSCRPT).build();
        scriptYoiMenuJs.appendChild(loadScriptsXml.createComment(FF3_AND_OPERA));
        Element scriptCitJs = new XmlElementBuilder(SCRIPT, loadScriptsXml).addAttribute(SRC, "${cit_js_url}")
                .addAttribute(TYPE_ATTRIBUTE, TEXT_JSCRPT).build();
        scriptCitJs.appendChild(loadScriptsXml.createComment(FF3_AND_OPERA));
        List<Element> scrtiptElements = org.springframework.roo.support.util.XmlUtils
                .findElements("/root/script", lsRoot);
        // Element lastScript = null;
        if (!scrtiptElements.isEmpty()) {
            Element lastScript = scrtiptElements.get(scrtiptElements.size() - 1);
            if (lastScript != null) {
                nextSibiling = lastScript.getNextSibling().getNextSibling();
                lsRoot.insertBefore(scriptYuiEventJs, nextSibiling);
                lsRoot.insertBefore(scriptYuiCoreJs, nextSibiling);
                lsRoot.insertBefore(scriptYoiMenuJs, nextSibiling);
                lsRoot.insertBefore(scriptCitJs, nextSibiling);
            }
        } else {
            // Add at the end of document
            lsRoot.appendChild(scriptYuiEventJs);
            lsRoot.appendChild(scriptYuiCoreJs);
            lsRoot.appendChild(scriptYoiMenuJs);
            lsRoot.appendChild(scriptCitJs);
        }
    }

    writeToDiskIfNecessary(loadScriptsTagx, loadScriptsXml.getDocumentElement());

}

From source file:org.infoglue.cms.applications.structuretool.actions.ViewSiteNodePageComponentsAction.java

/**
 * This method moves the component up a step if possible within the same slot. 
 *//* w ww  .j  ava  2s  .c o m*/

public String doMoveComponent() throws Exception {
    initialize();

    String componentXML = getPageComponentsString(siteNodeId, this.masterLanguageVO.getId());
    //logger.info("componentXML:" + componentXML);

    Document document = XMLHelper.readDocumentFromByteArray(componentXML.getBytes("UTF-8"));
    String componentXPath = "//component[@id=" + this.componentId + "]";

    NodeList anl = org.apache.xpath.XPathAPI.selectNodeList(document.getDocumentElement(), componentXPath);
    if (anl.getLength() > 0) {
        Element component = (Element) anl.item(0);
        String name = component.getAttribute("name");
        //logger.info(XMLHelper.serializeDom(component, new StringBuffer()));
        Node parentNode = component.getParentNode();

        boolean hasChanged = false;

        if (this.direction.intValue() == 0) //Up
        {
            Node previousNode = component.getPreviousSibling();

            while (previousNode != null && previousNode.getNodeType() != Node.ELEMENT_NODE) {
                previousNode = previousNode.getPreviousSibling();
                //break;
            }

            Element element = ((Element) previousNode);
            while (element != null && !element.getAttribute("name").equalsIgnoreCase(name)) {
                previousNode = previousNode.getPreviousSibling();
                while (previousNode != null && previousNode.getNodeType() != Node.ELEMENT_NODE) {
                    previousNode = previousNode.getPreviousSibling();
                    //break;
                }
                element = ((Element) previousNode);
            }

            if (previousNode != null) {
                parentNode.removeChild(component);
                parentNode.insertBefore(component, previousNode);
                hasChanged = true;
            }
        } else if (this.direction.intValue() == 1) //Down
        {
            Node nextNode = component.getNextSibling();

            while (nextNode != null && nextNode.getNodeType() != Node.ELEMENT_NODE) {
                nextNode = nextNode.getNextSibling();
                break;
            }

            Element element = ((Element) nextNode);
            while (element != null && !element.getAttribute("name").equalsIgnoreCase(name)) {
                nextNode = nextNode.getNextSibling();
                element = ((Element) nextNode);
            }

            if (nextNode != null)
                nextNode = nextNode.getNextSibling();

            if (nextNode != null) {
                parentNode.removeChild(component);
                parentNode.insertBefore(component, nextNode);
                hasChanged = true;
            } else {
                parentNode.removeChild(component);
                parentNode.appendChild(component);
                hasChanged = true;
            }
        }

        if (hasChanged) {
            String modifiedXML = XMLHelper.serializeDom(document, new StringBuffer()).toString();
            //logger.info("modifiedXML:" + modifiedXML);

            ContentVO contentVO = NodeDeliveryController
                    .getNodeDeliveryController(siteNodeId, languageId, contentId)
                    .getBoundContent(this.getInfoGluePrincipal(), siteNodeId, this.masterLanguageVO.getId(),
                            true, "Meta information", DeliveryContext.getDeliveryContext());
            ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController()
                    .getLatestActiveContentVersionVO(contentVO.getId(), this.masterLanguageVO.getId());
            ContentVersionController.getContentVersionController().updateAttributeValue(
                    contentVersionVO.getContentVersionId(), "ComponentStructure", modifiedXML,
                    this.getInfoGluePrincipal());
        }
    }

    this.url = getComponentRendererUrl() + getComponentRendererAction() + "?siteNodeId=" + this.siteNodeId
            + "&languageId=" + this.languageId + "&contentId=" + this.contentId + "&focusElementId="
            + this.componentId + "&showSimple=" + this.showSimple;
    //this.getResponse().sendRedirect(url);      

    this.url = this.getResponse().encodeURL(url);
    this.getResponse().sendRedirect(url);
    return NONE;
}

From source file:org.jasig.portal.layout.dlm.PositionManager.java

/**
   This method trims down the position set to the position directives on
   the node info elements still having a position directive. Any directives
   that violated restrictions were removed from the node info objects so
   the position set should be made to match the order of those still
   having one.//from   w  ww .ja v  a2  s  . c o m
 */
static void adjustPositionSet(List<NodeInfo> order, Element positionSet, IntegrationResult result) {
    Node nodeToMatch = positionSet.getFirstChild();
    Element nodeToInsertBefore = positionSet.getOwnerDocument().createElement("INSERT_POINT");
    positionSet.insertBefore(nodeToInsertBefore, nodeToMatch);

    for (Iterator iter = order.iterator(); iter.hasNext();) {
        NodeInfo ni = (NodeInfo) iter.next();

        if (ni.positionDirective != null) {
            // found one check it against the current one in the position
            // set to see if it is different. If so then indicate that
            // something (the position set) has changed in the plf
            if (ni.positionDirective != nodeToMatch)
                result.changedPLF = true;

            // now bump the insertion point forward prior to
            // moving on to the next position node to be evaluated
            if (nodeToMatch != null)
                nodeToMatch = nodeToMatch.getNextSibling();

            // now insert it prior to insertion point
            positionSet.insertBefore(ni.positionDirective, nodeToInsertBefore);
        }
    }

    // now for any left over after the insert point remove them.

    while (nodeToInsertBefore.getNextSibling() != null)
        positionSet.removeChild(nodeToInsertBefore.getNextSibling());

    // now remove the insertion point
    positionSet.removeChild(nodeToInsertBefore);
}

From source file:org.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java

@Override
protected int saveStructure(Node node, PreparedStatement structStmt, PreparedStatement parmStmt)
        throws SQLException {
    if (node == null) { // No more
        return 0;
    }/*from  w ww  .  j a  v  a  2s.  c  o m*/
    if (node.getNodeName().equals("parameter")) {
        //parameter, skip it and go on to the next node
        return this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    }
    if (!(node instanceof Element)) {
        return 0;
    }

    final Element structure = (Element) node;

    if (LOG.isDebugEnabled()) {
        LOG.debug("saveStructure XML content: " + XmlUtilitiesImpl.toString(node));
    }

    // determine the struct_id for storing in the db. For incorporated nodes in
    // the plf their ID is a system-wide unique ID while their struct_id for
    // storing in the db is cached in a dlm:plfID attribute.
    int saveStructId = -1;
    final String plfID = structure.getAttribute(Constants.ATT_PLF_ID);

    if (!plfID.equals("")) {
        saveStructId = Integer.parseInt(plfID.substring(1));
    } else {
        final String id = structure.getAttribute("ID");
        saveStructId = Integer.parseInt(id.substring(1));
    }

    int nextStructId = 0;
    int childStructId = 0;
    int chanId = -1;
    IPortletDefinition portletDef = null;
    final boolean isChannel = node.getNodeName().equals("channel");

    if (isChannel) {
        chanId = Integer.parseInt(node.getAttributes().getNamedItem("chanID").getNodeValue());
        portletDef = this.portletDefinitionRegistry.getPortletDefinition(String.valueOf(chanId));
        if (portletDef == null) {
            //Portlet doesn't exist any more, drop the layout node
            return 0;
        }
    }

    if (node.hasChildNodes()) {
        childStructId = this.saveStructure(node.getFirstChild(), structStmt, parmStmt);
    }
    nextStructId = this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    structStmt.clearParameters();
    structStmt.setInt(1, saveStructId);
    structStmt.setInt(2, nextStructId);
    structStmt.setInt(3, childStructId);

    final String externalId = structure.getAttribute("external_id");
    if (externalId != null && externalId.trim().length() > 0) {
        final Integer eID = new Integer(externalId);
        structStmt.setInt(4, eID.intValue());
    } else {
        structStmt.setNull(4, java.sql.Types.NUMERIC);

    }
    if (isChannel) {
        structStmt.setInt(5, chanId);
        structStmt.setNull(6, java.sql.Types.VARCHAR);
    } else {
        structStmt.setNull(5, java.sql.Types.NUMERIC);
        structStmt.setString(6, structure.getAttribute("name"));
    }
    final String structType = structure.getAttribute("type");
    structStmt.setString(7, structType);
    structStmt.setString(8, RDBMServices.dbFlag(xmlBool(structure.getAttribute("hidden"))));
    structStmt.setString(9, RDBMServices.dbFlag(xmlBool(structure.getAttribute("immutable"))));
    structStmt.setString(10, RDBMServices.dbFlag(xmlBool(structure.getAttribute("unremovable"))));
    if (LOG.isDebugEnabled()) {
        LOG.debug(structStmt.toString());
    }
    structStmt.executeUpdate();

    // code to persist extension attributes for dlm
    final NamedNodeMap attribs = node.getAttributes();
    for (int i = 0; i < attribs.getLength(); i++) {
        final Node attrib = attribs.item(i);
        final String name = attrib.getNodeName();

        if (name.startsWith(Constants.NS) && !name.equals(Constants.ATT_PLF_ID)
                && !name.equals(Constants.ATT_FRAGMENT) && !name.equals(Constants.ATT_PRECEDENCE)) {
            // a cp extension attribute. Push into param table.
            parmStmt.clearParameters();
            parmStmt.setInt(1, saveStructId);
            parmStmt.setString(2, name);
            parmStmt.setString(3, attrib.getNodeValue());
            if (LOG.isDebugEnabled()) {
                LOG.debug(parmStmt.toString());
            }
            parmStmt.executeUpdate();
        }
    }
    final NodeList parameters = node.getChildNodes();
    if (parameters != null && isChannel) {
        for (int i = 0; i < parameters.getLength(); i++) {
            if (parameters.item(i).getNodeName().equals("parameter")) {
                final Element parmElement = (Element) parameters.item(i);
                final NamedNodeMap nm = parmElement.getAttributes();
                final String parmName = nm.getNamedItem("name").getNodeValue();
                final String parmValue = nm.getNamedItem("value").getNodeValue();
                final Node override = nm.getNamedItem("override");

                // if no override specified then default to allowed
                if (override != null && !override.getNodeValue().equals("yes")) {
                    // can't override
                } else {
                    // override only for adhoc or if diff from chan def
                    final IPortletDefinitionParameter cp = portletDef.getParameter(parmName);
                    if (cp == null || !cp.getValue().equals(parmValue)) {
                        parmStmt.clearParameters();
                        parmStmt.setInt(1, saveStructId);
                        parmStmt.setString(2, parmName);
                        parmStmt.setString(3, parmValue);
                        if (LOG.isDebugEnabled()) {
                            LOG.debug(parmStmt);
                        }
                        parmStmt.executeUpdate();
                    }
                }
            }
        }
    }
    return saveStructId;
}