Example usage for org.w3c.dom Document createCDATASection

List of usage examples for org.w3c.dom Document createCDATASection

Introduction

In this page you can find the example usage for org.w3c.dom Document createCDATASection.

Prototype

public CDATASection createCDATASection(String data) throws DOMException;

Source Link

Document

Creates a CDATASection node whose value is the specified string.

Usage

From source file:org.mrgeo.resources.wms.WmsGenerator.java

private Response writeError(Response.Status httpStatus, final String code, final String msg) {
    try {//from w ww . ja  va  2 s  .  c  o m
        Document doc;
        final DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance();
        final DocumentBuilder builder = dBF.newDocumentBuilder();
        doc = builder.newDocument();

        final Element ser = doc.createElement("ServiceExceptionReport");
        doc.appendChild(ser);
        ser.setAttribute("version", WMS_VERSION);
        final Element se = XmlUtils.createElement(ser, "ServiceException");
        se.setAttribute("code", code);
        CDATASection msgNode = doc.createCDATASection(msg);
        se.appendChild(msgNode);
        final ByteArrayOutputStream xmlStream = new ByteArrayOutputStream();
        final PrintWriter out = new PrintWriter(xmlStream);
        DocumentUtils.writeDocument(doc, version, WMS_SERVICE, out);
        out.close();
        return Response.status(httpStatus).header("Content-Type", MediaType.TEXT_XML)
                .entity(xmlStream.toString()).build();
    } catch (ParserConfigurationException e1) {
    } catch (TransformerException e1) {
    }
    // Fallback in case there is an XML exception above
    return Response.status(httpStatus).entity(msg).build();
}

From source file:org.opencastproject.comments.CommentParser.java

/**
 * Serializes the comment to a {@link org.w3c.dom.Document}.
 * //from  w w w  . j  a  va  2 s . c o  m
 * @param comment
 *          the comment
 * @return the serialized comment
 */
private static Element getAsXmlDocument(Comment comment, Document doc) {
    // Root element "comment"
    Element commentXml = doc.createElementNS(NAMESPACE, "comment");
    commentXml.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", NAMESPACE);

    // Identifier
    if (comment.getId().isSome())
        commentXml.setAttribute("id", comment.getId().get().toString());

    // Resolved status
    commentXml.setAttribute("resolved", Boolean.toString(comment.isResolvedStatus()));

    // Author
    Element authorNode = getAuthorNode(comment.getAuthor(), doc);
    commentXml.appendChild(authorNode);

    // Creation date
    Element creationDate = doc.createElement("creationDate");
    creationDate.setTextContent(DateTimeSupport.toUTC(comment.getCreationDate().getTime()));
    commentXml.appendChild(creationDate);

    // Modification date
    Element modificationDate = doc.createElement("modificationDate");
    modificationDate.setTextContent(DateTimeSupport.toUTC(comment.getModificationDate().getTime()));
    commentXml.appendChild(modificationDate);

    // Text
    Element text = doc.createElement("text");
    if (StringUtils.isNotBlank(comment.getText()))
        text.appendChild(doc.createCDATASection(comment.getText()));
    commentXml.appendChild(text);

    // Reason
    Element reason = doc.createElement("reason");
    if (StringUtils.isNotBlank(comment.getReason()))
        reason.setTextContent(comment.getReason());
    commentXml.appendChild(reason);

    // Replies
    Element repliesNode = doc.createElement("replies");
    for (CommentReply r : comment.getReplies()) {
        repliesNode.appendChild(getAsXml(r, doc));
    }
    commentXml.appendChild(repliesNode);

    return commentXml;
}

From source file:org.opencastproject.comments.CommentParser.java

private static Element getAsXml(CommentReply reply, Document doc) {
    // Root element "comment"
    Element replyXml = doc.createElementNS(NAMESPACE, "reply");
    replyXml.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", NAMESPACE);

    // Identifier
    if (reply.getId().isSome())
        replyXml.setAttribute("id", reply.getId().get().toString());

    // Author/*from ww w.j a  v  a  2 s  . c  o  m*/
    Element authorNode = getAuthorNode(reply.getAuthor(), doc);
    replyXml.appendChild(authorNode);

    // Creation date
    Element creationDate = doc.createElement("creationDate");
    creationDate.setTextContent(DateTimeSupport.toUTC(reply.getCreationDate().getTime()));
    replyXml.appendChild(creationDate);

    // Modification date
    Element modificationDate = doc.createElement("modificationDate");
    modificationDate.setTextContent(DateTimeSupport.toUTC(reply.getModificationDate().getTime()));
    replyXml.appendChild(modificationDate);

    // Text
    Element text = doc.createElement("text");
    if (StringUtils.isNotBlank(reply.getText()))
        text.appendChild(doc.createCDATASection(reply.getText()));

    replyXml.appendChild(text);

    return replyXml;
}

From source file:org.opencastproject.comments.CommentParser.java

private static Element getAuthorNode(User author, Document doc) {
    Element authorNode = doc.createElement("author");
    Element username = doc.createElement("username");
    username.setTextContent(author.getUsername());
    authorNode.appendChild(username);/*from   ww w .j  a va2 s  .c  o m*/
    Element email = doc.createElement("email");
    email.setTextContent(author.getEmail());
    authorNode.appendChild(email);
    Element name = doc.createElement("name");
    if (StringUtils.isNotBlank(author.getName()))
        name.appendChild(doc.createCDATASection(author.getName()));
    authorNode.appendChild(name);
    return authorNode;
}

From source file:org.openestate.io.core.XmlUtils.java

/**
 * Replace all text values of a {@link Node} with CDATA values.
 *
 * @param doc/*w ww.  j  a v  a 2s .c o  m*/
 * the document to update
 *
 * @param node
 * the node to update
 */
public static void replaceTextWithCData(Document doc, Node node) {
    if (node instanceof Text) {
        Text text = (Text) node;
        CDATASection cdata = doc.createCDATASection(text.getTextContent());
        Element parent = (Element) text.getParentNode();
        parent.replaceChild(cdata, text);
    } else if (node instanceof Element) {
        //LOGGER.debug( "ELEMENT " + element.getTagName() );
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            //LOGGER.debug( "> " + children.item( i ).getClass().getName() );
            XmlUtils.replaceTextWithCData(doc, children.item(i));
        }
    }
}

From source file:org.ow2.proactive.scheduler.common.job.factories.Job2XMLTransformer.java

/**
 * Corresponds to <element name="script">
 *
 * The schema allows the specification of a script either by writing the
 * script code either by providing a file with arguments. Both will result
 * in the same {@link org.ow2.proactive.scripting.Script} object. In the
 * current translation we will always translate a Script object by inlining
 * the script code using a "codeScript"element (first option).
 *
 * The xml specification does not allow addding arguments to a script
 * defined by its code. Therefore, when we translate the script object to
 * xml, if we encounter arguments, we will insert their value directly in
 * the script's code by inserting a line like:
 * <p/>/*from   w  ww. j  av a2s .  c  o m*/
 * var args = ["argument_1",...,"argument_n"];
 *
 */
private Element createScriptElement(Document doc, Script script) {
    Element scriptElement = doc.createElementNS(Schemas.SCHEMA_LATEST.getNamespace(),
            XMLTags.SCRIPT_SCRIPT.getXMLName());
    Element codeE = doc.createElementNS(Schemas.SCHEMA_LATEST.getNamespace(), XMLTags.SCRIPT_CODE.getXMLName());
    setAttribute(codeE, XMLAttributes.LANGUAGE, script.getEngineName(), true);
    String scriptText = script.getScript();
    Serializable[] params = script.getParameters();
    if (params != null) {

        scriptText = inlineScriptParametersInText(scriptText, params);
    }

    CDATASection scriptTextCDATA = doc.createCDATASection(scriptText);
    codeE.appendChild(scriptTextCDATA);

    scriptElement.appendChild(codeE);
    return scriptElement;
}

From source file:org.rdv.DockingDataPanelManager.java

@Override
public Document getConfigurationXML() throws Exception {
    Document ret = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element stateEl = ret.createElement("serialState");
    ret.appendChild(stateEl);/*from w w w.  ja  v a2 s.c o m*/

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bos);
    rootWindow_.write(out, false);
    out.close();
    String data = new sun.misc.BASE64Encoder().encode(bos.toByteArray());
    stateEl.appendChild(ret.createCDATASection(data));

    return ret;
}

From source file:org.sakaiproject.portal.xsltcharon.impl.XsltRenderContext.java

protected void safeAppendTextNode(Document doc, Element element, String text, boolean cdata) {
    if (text != null) {
        element.appendChild(cdata ? doc.createCDATASection(text) : doc.createTextNode(text));
    }/*w  w w.j ava 2s.  com*/
}

From source file:org.wso2.carbon.registry.samples.reporting.ServiceReportGenerator.java

public ByteArrayOutputStream execute(String template, String type) throws IOException {
    try {//from  ww  w . jav a  2s. com
        Registry registry = getRegistry();
        Registry gov = GovernanceUtils.getGovernanceUserRegistry(registry, "admin");
        if (registry == null) {
            throw new RuntimeException("Registry is null");
        }
        if (!registry.resourceExists(template)) {
            throw new FileNotFoundException("Template is not found");
        }
        // Read Template
        String templateContent = RegistryUtils.decodeBytes((byte[]) registry.get(template).getContent());
        //Read html file
        if (HTML.equalsIgnoreCase(type)) {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(templateContent)));
            //Find images and embed them
            NodeList nodes = doc.getElementsByTagName(IMAGE);
            for (int i = 0; i < nodes.getLength(); i++) {
                Node image = nodes.item(i);
                NodeList list = image.getChildNodes();
                for (int j = 0; j != list.getLength(); ++j) {
                    Node child = list.item(j);
                    if (IMAGE_EXPRESSION.equals(child.getNodeName()) && child.getTextContent() != null) {
                        String imgUrlStr = child.getTextContent().trim().replaceAll("^\"|\"$", "");
                        //Get image extension
                        String imageExtension = imgUrlStr.substring(imgUrlStr.lastIndexOf(".") + 1);

                        byte[] imageBytes = convertInputStream(imgUrlStr);
                        Element imgExp = doc.createElement(IMAGE_EXPRESSION);
                        String strBuilder = "\"data:image/" + imageExtension + ";base64,"
                                + new String(Base64.encodeBase64(imageBytes)) + "\"";
                        imgExp.appendChild(doc.createCDATASection(strBuilder));
                        imgExp.setAttribute(CLASS, String.class.getName());
                        image.replaceChild(imgExp, child);
                    }
                }
            }
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            DOMSource source = new DOMSource(doc);

            StringWriter outWriter = new StringWriter();
            StreamResult result = new StreamResult(outWriter);

            transformer.transform(source, result);
            StringBuffer stringBuffer = outWriter.getBuffer();
            templateContent = stringBuffer.toString();
            stringBuffer.delete(0, stringBuffer.length());
        }
        GovernanceUtils.loadGovernanceArtifacts((UserRegistry) gov);
        // Create Report Bean Collection
        GenericArtifactManager genericArtifactManager = new GenericArtifactManager(gov, "restservice");
        List<ReportBean> beanList = new LinkedList<ReportBean>();
        for (GenericArtifact genericArtifact : genericArtifactManager.getAllGenericArtifacts()) {
            beanList.add(new ReportBean(genericArtifact.getAttribute("overview_name"),
                    genericArtifact.getAttribute("overview_version"),
                    genericArtifact.getAttribute("overview_description")));
        }
        // Return Report Stream as a ByteArrayOutputStream
        return new ReportStream().getReportStream(new JasperPrintProvider().createJasperPrint(
                new JRBeanCollectionDataSource(beanList), templateContent, new ReportParamMap[0]), type);

    } catch (RuntimeException e) {
        throw new IOException("Failed to get input stream", e);
    } catch (RegistryException e) {
        throw new IOException("Failed to find report template", e);
    } catch (TransformerException e) {
        throw new IOException("Failed to transform file", e);
    } catch (JRException e) {
        throw new IOException("Failed to create jasperprint", e);
    } catch (ReportingException e) {
        throw new IOException("Failed to create jasperprint", e);
    } catch (ParserConfigurationException e) {
        throw new IOException("Failed to create DocumentBuilder", e);
    } catch (SAXException e) {
        throw new IOException("Failed to parse inputSource", e);
    }
}

From source file:se.unlogic.hierarchy.core.servlets.CoreServlet.java

protected void processRequest(HttpServletRequest req, HttpServletResponse res, User user, URIParser uriParser)
        throws TransformerException, IOException {

    ForegroundModuleResponse moduleResponse = null;
    RequestException exception = null;/*from  w w w.  j a v  a2 s.  c o m*/

    try {
        try {
            moduleResponse = this.rootSection.processRequest(req, res, user, uriParser,
                    rootSection.getSectionDescriptor().getRequiredProtocol());

        } catch (AccessDeniedException e) {

            if (user == null) {

                loginHandler.processLoginRequest(req, res, uriParser, true);
            }

            if (!res.isCommitted()) {
                throw e;
            }
        }

    } catch (RequestException e) {

        log.log(e.getPriority(),
                e.toString() + " Requested by user " + user + " accessing from " + req.getRemoteAddr(),
                e.getThrowable());
        exception = e;
    }

    // Check if the response has been committed
    if (!res.isCommitted()) {

        // Set request attribute to tell the URLFilter to ignore this response
        req.setAttribute("processed", true);

        // Response has not been committed create xml document
        Document doc = XMLUtils.createDomDocument();

        // Create root element
        Element document = doc.createElement("document");
        doc.appendChild(document);

        if (exception != null) {

            // Append exception
            Element errors = doc.createElement("errors");
            doc.getDocumentElement().appendChild(errors);
            errors.appendChild(exception.toXML(doc));

            if (exception.getStatusCode() != null) {
                res.setStatus(exception.getStatusCode());
            }

            this.appendLinks(doc, exception.getBackgroundModuleResponses());
            this.appendScripts(doc, exception.getBackgroundModuleResponses());

            this.addBackgroundModuleResponses(exception.getBackgroundModuleResponses(), doc, user, req);

        } else {

            // Check if the user has changed
            if (moduleResponse.isUserChanged()) {

                try {
                    HttpSession session = req.getSession(false);

                    if (session != null) {
                        user = (User) session.getAttribute("user");
                    }

                } catch (IllegalStateException e) {

                    user = null;
                }
            }

            if (moduleResponse.isExcludeSystemTransformation()) {
                doc = moduleResponse.getDocument();
                document = doc.getDocumentElement();
            }

            this.appendLinks(doc, moduleResponse);
            this.appendScripts(doc, moduleResponse);

            if (isValidResponse(moduleResponse)) {

                if (moduleResponse.getResponseType() == ResponseType.HTML) {

                    // Append module html response
                    Element moduleres = doc.createElement("moduleHTMLResponse");
                    document.appendChild(moduleres);
                    moduleres.appendChild(doc.createCDATASection(moduleResponse.getHtml()));

                } else if (moduleResponse.getResponseType() == ResponseType.XML_FOR_CORE_TRANSFORMATION) {

                    // Append module response
                    Element moduleres = doc.createElement("moduleXMLResponse");
                    document.appendChild(moduleres);
                    moduleres.appendChild(doc.adoptNode(moduleResponse.getElement()));

                } else if (moduleResponse.getResponseType() == ResponseType.XML_FOR_SEPARATE_TRANSFORMATION) {

                    if (moduleResponse.getTransformer() != null) {

                        // Write xml to debug file if xml debug output is enabled
                        if (moduleXMLDebug && !StringUtils.isEmpty(moduleXMLDebugFile)) {
                            this.log.debug("XML debug mode enabled, writing module XML to " + moduleXMLDebugFile
                                    + " for module " + moduleResponse.getModuleDescriptor());

                            try {
                                XMLUtils.writeXMLFile(moduleResponse.getDocument(),
                                        this.applicationFileSystemPath + "WEB-INF/" + moduleXMLDebugFile, true,
                                        encoding);

                                this.log.debug("Finished writing module XML to "
                                        + this.applicationFileSystemPath + "WEB-INF/" + moduleXMLDebugFile);

                            } catch (Exception e) {

                                this.log.error("Error writing module XML to " + this.applicationFileSystemPath
                                        + "WEB-INF/" + moduleXMLDebugFile, e);
                            }
                        }

                        // Transform output
                        try {

                            this.log.debug("Module XML transformation starting");

                            if (moduleResponse.isExcludeSystemTransformation()) {

                                // Set response parameters
                                res.setContentType("text/html");

                                // Set standard HTTP/1.1 no-cache headers.
                                res.setHeader("Cache-Control",
                                        "no-store, no-cache, must-revalidate, proxy-revalidate");

                                XMLTransformer.transformToWriter(moduleResponse.getTransformer(), doc,
                                        res.getWriter(), encoding);

                                return;

                            } else {

                                StringWriter stringWriter = new StringWriter();

                                XMLTransformer.transformToWriter(moduleResponse.getTransformer(),
                                        moduleResponse.getDocument(), stringWriter, encoding);

                                // Append module response
                                Element moduleres = doc.createElement("moduleTransformedResponse");
                                document.appendChild(moduleres);

                                this.log.debug("Module XML transformation finished, appending result...");

                                moduleres.appendChild(doc.createCDATASection(stringWriter.toString()));

                                this.log.debug("Result appended");

                            }

                        } catch (Exception e) {

                            this.log.error("Tranformation of module response from module"
                                    + moduleResponse.getModuleDescriptor() + " failed, requested by user "
                                    + user + " accesing from " + req.getRemoteAddr(), e);

                            Element errors = doc.createElement("errors");
                            document.appendChild(errors);

                            Element separateTransformationFailedElement = doc
                                    .createElement("separateTransformationFailed");
                            errors.appendChild(separateTransformationFailedElement);
                            separateTransformationFailedElement
                                    .appendChild(XMLUtils.createCDATAElement("exception", e.toString(), doc));
                            separateTransformationFailedElement
                                    .appendChild(moduleResponse.getModuleDescriptor().toXML(doc));
                        }
                    } else {
                        this.log.error(
                                "Module response for separate transformation without attached stylesheet returned by module "
                                        + moduleResponse.getModuleDescriptor() + " requested by user " + user
                                        + " accesing from " + req.getRemoteAddr());
                        Element errors = doc.createElement("errors");
                        document.appendChild(errors);
                        Element separateTransformationWithoutStylesheetElement = doc
                                .createElement("separateTransformationWithoutStylesheet");
                        errors.appendChild(separateTransformationWithoutStylesheetElement);
                        separateTransformationWithoutStylesheetElement
                                .appendChild(moduleResponse.getModuleDescriptor().toXML(doc));
                    }
                }
            } else {
                // No response, append error
                this.log.error("Invalid module response from module" + moduleResponse.getModuleDescriptor()
                        + ", requested by user " + user + " accesing from " + req.getRemoteAddr());
                Element errors = doc.createElement("errors");
                document.appendChild(errors);
                Element invalidModuleResonseElement = doc.createElement("invalidModuleResonse");
                errors.appendChild(invalidModuleResonseElement);
                invalidModuleResonseElement.appendChild(moduleResponse.getModuleDescriptor().toXML(doc));
            }

            this.addBackgroundModuleResponses(moduleResponse.getBackgroundModuleResponses(), doc, user, req);
        }

        XMLUtils.appendNewCDATAElement(doc, document, "version", VERSION);

        document.appendChild(RequestUtils.getRequestInfoAsXML(doc, req, uriParser, false, true));

        // Append root section
        document.appendChild(this.rootSection.getSectionDescriptor().toXML(doc));

        // Append userinfo and menuitems
        if (user != null) {
            document.appendChild(user.toXML(doc));
        }

        //Get style sheet so that the correct menu type can be added
        CachedXSLTDescriptor xslDescriptor;

        if (this.xsltCacheHandler.getXslDescriptorCount() == 1) {

            //Only default stylesheet loaded, skip i18n support.

            xslDescriptor = this.xsltCacheHandler.getDefaultXsltDescriptor();

        } else {

            Language language = this.getLanguage(req, user);

            String preferedDesign = this.getPreferedDesign(req, user);

            xslDescriptor = this.xsltCacheHandler.getBestMatchingXSLTDescriptor(language, preferedDesign);
        }

        Element menus = doc.createElement("menus");
        document.appendChild(menus);

        if (moduleResponse != null) {

            if (moduleResponse.getTitle() != null) {
                document.appendChild(XMLUtils.createCDATAElement("title", moduleResponse.getTitle(), doc));
            }

            if (xslDescriptor.usesFullMenu()) {

                menus.appendChild(rootSection.getFullMenu(user, uriParser).toXML(doc));

            } else {

                if (moduleResponse.getMenu() != null) {

                    menus.appendChild(moduleResponse.getMenu().toXML(doc));
                }
            }

            if (!moduleResponse.getBreadcrumbs().isEmpty()) {

                Element breadcrumbsElement = doc.createElement("breadcrumbs");
                document.appendChild(breadcrumbsElement);

                for (Breadcrumb breadcrumb : moduleResponse.getBreadcrumbs()) {

                    if (breadcrumb != null) {

                        breadcrumbsElement.appendChild(breadcrumb.toXML(doc));
                    }
                }
            }

        } else if (exception != null) {

            if (xslDescriptor.usesFullMenu()) {

                menus.appendChild(rootSection.getFullMenu(user, uriParser).toXML(doc));

            } else {

                if (exception.getMenu() != null) {

                    menus.appendChild(exception.getMenu().toXML(doc));
                }
            }

            //TODO add breadcrumbs to exceptions
        }

        // Write xml to debug file if xml debug output is enabled
        if (systemXMLDebug && !StringUtils.isEmpty(systemXMLDebugFile)) {
            this.log.debug("XML debug mode enabled, writing system XML to " + systemXMLDebugFile);

            try {
                FileWriter xmldebugstream = new FileWriter(
                        new File(this.applicationFileSystemPath + "WEB-INF/" + systemXMLDebugFile));
                XMLUtils.toString(doc, encoding, xmldebugstream, false);
                xmldebugstream.close();

                this.log.debug("Finished writing system XML to " + this.applicationFileSystemPath + "WEB-INF/"
                        + systemXMLDebugFile);

            } catch (Exception e) {

                this.log.error("Error writing system XML to " + this.applicationFileSystemPath + "WEB-INF/"
                        + systemXMLDebugFile, e);
            }
        }

        // Set encoding
        res.setCharacterEncoding(encoding);

        // Set response parameters
        res.setContentType("text/html");

        // Set standard HTTP/1.1 no-cache headers.
        res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");

        // Transform output
        try {
            this.log.debug("System XML transformation starting");

            XMLTransformer.transformToWriter(xslDescriptor.getTransformer(), doc, res.getWriter(), encoding);

            this.log.debug("System XML transformation finished, response transformed and committed");

        } catch (TransformerException e) {

            this.log.error("System XML transformation failed, " + e);
            throw e;

        } catch (IOException e) {

            if (!res.isCommitted()) {

                log.error("Error writing response", e);
                throw e;

            } else {

                this.log.debug("Response already committed");
            }
        } catch (IllegalStateException e) {

            this.log.debug("Response already committed");
        }

    } else {
        if (exception != null) {
            this.log.warn("Error " + exception + " after response has been committed");
        } else {
            this.log.debug("Response already committed");
        }
    }
}