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:com.seajas.search.attender.model.searchresult.SearchResult.java

/**
 * Marshal the document content to a W3C Element node.
 * // www.  j ava  2  s  .  c o  m
 * @param document
 * @return Element
 */
public Element toElement(final Document document) {
    Element result = document.createElement("search-result");

    result.setAttribute("url", url);
    result.setAttribute("title", StringEscapeUtils.unescapeHtml(title));
    result.setAttribute("author", StringEscapeUtils.unescapeHtml(author != null ? author : ""));
    result.setAttribute("source", StringEscapeUtils.unescapeHtml(source != null ? source : ""));
    result.setAttribute("publicationDate", new SimpleDateFormat("yyyy-MM-dd HH:mm").format(publicationDate));

    if (!StringUtils.isEmpty(imageThumbnail))
        result.setAttribute("image-thumbnail", imageThumbnail);

    result.appendChild(document.createCDATASection(StringEscapeUtils.unescapeHtml(summary)));

    return result;
}

From source file:com.aurel.track.exchange.track.exporter.TrackExportBL.java

/**
 * Create a dom element with text content and attributes
 * @param elementName/*from   www  .  j  a va2s.  c  o  m*/
 * @param textContent
 * @param attributeValues
 * @param dom
 * @return
 */
private static Element createElementWithAttributes(String elementName, String textContent, boolean needCDATA,
        Map<String, String> attributeValues, Document dom) {
    //create the main element
    Element element = null;
    try {
        element = dom.createElement(elementName);
    } catch (DOMException e) {
        LOGGER.warn("Creating an XML node with the element name " + elementName + " failed with " + e);
    }
    if (element == null) {
        return null;
    }

    //create the text element
    if (textContent != null) {
        if (needCDATA) {
            CDATASection cdataText = dom.createCDATASection(Html2Text.stripNonValidXMLCharacters(textContent));
            element.appendChild(cdataText);
        } else {
            Text textElement;
            try {
                textElement = dom.createTextNode(textContent);
            } catch (DOMException e) {
                LOGGER.info("Creating the text node for the element " + elementName + " and text " + textContent
                        + " failed with " + e);
                textElement = dom.createTextNode("");
            }
            //append the text to the element
            element.appendChild(textElement);
        }
    }

    //set the attributes
    if (attributeValues != null) {
        Iterator<String> iterator = attributeValues.keySet().iterator();
        while (iterator.hasNext()) {
            String attributeName = iterator.next();
            String attributeValue = attributeValues.get(attributeName);
            if (attributeValue != null) {
                try {
                    element.setAttribute(attributeName, attributeValue);
                } catch (DOMException e) {
                    LOGGER.warn("Setting the attribute name " + attributeName + " to attribute value "
                            + attributeValue + " faield with " + e.getMessage());
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
    }
    return element;
}

From source file:Main.java

/**
 * Clone given Node into target Document. If targe is null, same Document will be used.
 * If deep is specified, all children below will also be cloned.
 *//* w  ww.j ava  2s .  c om*/
public static Node cloneNode(Node node, Document target, boolean deep) throws DOMException {
    if (target == null || node.getOwnerDocument() == target)
        // same Document
        return node.cloneNode(deep);
    else {
        //DOM level 2 provides this in Document, so once xalan switches to that,
        //we can take out all the below and just call target.importNode(node, deep);
        //For now, we implement based on the javadocs for importNode
        Node newNode;
        int nodeType = node.getNodeType();

        switch (nodeType) {
        case Node.ATTRIBUTE_NODE:
            newNode = target.createAttribute(node.getNodeName());

            break;

        case Node.DOCUMENT_FRAGMENT_NODE:
            newNode = target.createDocumentFragment();

            break;

        case Node.ELEMENT_NODE:

            Element newElement = target.createElement(node.getNodeName());
            NamedNodeMap nodeAttr = node.getAttributes();

            if (nodeAttr != null)
                for (int i = 0; i < nodeAttr.getLength(); i++) {
                    Attr attr = (Attr) nodeAttr.item(i);

                    if (attr.getSpecified()) {
                        Attr newAttr = (Attr) cloneNode(attr, target, true);
                        newElement.setAttributeNode(newAttr);
                    }
                }

            newNode = newElement;

            break;

        case Node.ENTITY_REFERENCE_NODE:
            newNode = target.createEntityReference(node.getNodeName());

            break;

        case Node.PROCESSING_INSTRUCTION_NODE:
            newNode = target.createProcessingInstruction(node.getNodeName(), node.getNodeValue());

            break;

        case Node.TEXT_NODE:
            newNode = target.createTextNode(node.getNodeValue());

            break;

        case Node.CDATA_SECTION_NODE:
            newNode = target.createCDATASection(node.getNodeValue());

            break;

        case Node.COMMENT_NODE:
            newNode = target.createComment(node.getNodeValue());

            break;

        case Node.NOTATION_NODE:
        case Node.ENTITY_NODE:
        case Node.DOCUMENT_TYPE_NODE:
        case Node.DOCUMENT_NODE:
        default:
            throw new IllegalArgumentException("Importing of " + node + " not supported yet");
        }

        if (deep)
            for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling())
                newNode.appendChild(cloneNode(child, target, true));

        return newNode;
    }
}

From source file:Main.java

/**
 * Clone given Node into target Document. If targe is null, same Document will be used.
 * If deep is specified, all children below will also be cloned.
 *///from  w ww  .j av  a 2s .  c  o  m
public final static Node cloneNode(Node node, Document target, boolean deep) throws DOMException {
    if ((target == null) || (node.getOwnerDocument() == target)) {
        // same Document
        return node.cloneNode(deep);
    } else {
        //DOM level 2 provides this in Document, so once xalan switches to that,
        //we can take out all the below and just call target.importNode(node, deep);
        //For now, we implement based on the javadocs for importNode
        Node newNode;
        int nodeType = node.getNodeType();

        switch (nodeType) {
        case Node.ATTRIBUTE_NODE:
            newNode = target.createAttribute(node.getNodeName());

            break;

        case Node.DOCUMENT_FRAGMENT_NODE:
            newNode = target.createDocumentFragment();

            break;

        case Node.ELEMENT_NODE:

            Element newElement = target.createElement(node.getNodeName());
            NamedNodeMap nodeAttr = node.getAttributes();

            if (nodeAttr != null) {
                for (int i = 0; i < nodeAttr.getLength(); i++) {
                    Attr attr = (Attr) nodeAttr.item(i);

                    if (attr.getSpecified()) {
                        Attr newAttr = (Attr) cloneNode(attr, target, true);
                        newElement.setAttributeNode(newAttr);
                    }
                }
            }

            newNode = newElement;

            break;

        case Node.ENTITY_REFERENCE_NODE:
            newNode = target.createEntityReference(node.getNodeName());

            break;

        case Node.PROCESSING_INSTRUCTION_NODE:
            newNode = target.createProcessingInstruction(node.getNodeName(), node.getNodeValue());

            break;

        case Node.TEXT_NODE:
            newNode = target.createTextNode(node.getNodeValue());

            break;

        case Node.CDATA_SECTION_NODE:
            newNode = target.createCDATASection(node.getNodeValue());

            break;

        case Node.COMMENT_NODE:
            newNode = target.createComment(node.getNodeValue());

            break;

        case Node.NOTATION_NODE:
        case Node.ENTITY_NODE:
        case Node.DOCUMENT_TYPE_NODE:
        case Node.DOCUMENT_NODE:
        default:
            throw new IllegalArgumentException("Importing of " + node + " not supported yet");
        }

        if (deep) {
            for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
                newNode.appendChild(cloneNode(child, target, true));
            }
        }

        return newNode;
    }
}

From source file:jef.tools.XMLUtils.java

/**
 * CDATA/*from   w ww .  j ava2 s. c  o  m*/
 * 
 * @param node
 *            
 * @param data
 *            CDATA
 * @return ?CDATA
 */
public static CDATASection addCDataText(Node node, String data) {
    Document doc = null;
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        doc = (Document) node;
    } else {
        doc = node.getOwnerDocument();
    }
    CDATASection e = doc.createCDATASection(data);
    node.appendChild(e);
    return e;
}

From source file:com.fiorano.openesb.application.aps.OutPortInst.java

/**
 *  Returns the xml string equivalent of this object.
 *
 * @param document the input Document object
 * @return element node//  w w  w.  j  ava2s .c  om
 * @exception FioranoException if an error occurs while creating the element
 *      node.
 */
public Node toJXMLString(Document document) throws FioranoException {
    Node root0 = document.createElement("OutPortInst");

    ((Element) root0).setAttribute("isSyncRequestType", "" + isSyncRequestType());

    Node child = null;

    child = XMLDmiUtil.getNodeObject("Name", m_strPortName, document);
    if (child != null) {
        root0.appendChild(child);
    }

    if (!StringUtils.isEmpty(m_strDscription)) {
        child = XMLDmiUtil.getNodeObject("Description", m_strDscription, document);
        if (child != null) {
            root0.appendChild(child);
        }
    }

    boolean standardXSD = false;

    if ("ON_EXCEPTION".equals(m_strPortName))
        standardXSD = CommonSchemas.ERROR_XSD == null ? m_strXSD == null
                : m_strXSD != null && CommonSchemas.ERROR_XSD.equals(m_strXSD);

    if (standardXSD) {
        Element elem = document.createElement("StandardXSD");

        root0.appendChild(elem);
    } else if (m_strXSDRef != null) {
        child = XMLDmiUtil.getNodeObject(PortInstConstants.PORT_XSDREF, m_strXSDRef, document);
        root0.appendChild(child);
    }

    if (m_strContextXSL != null) {
        Element elem = document.createElement("SetContextXSL");
        CDATASection cdata = document.createCDATASection(m_strContextXSL);

        elem.appendChild(cdata);
        root0.appendChild(elem);
    }

    if (m_strContextInfo != null) {
        Element elem = document.createElement("SetContextInfo");
        CDATASection cdata = document.createCDATASection(m_strContextInfo);

        elem.appendChild(cdata);
        root0.appendChild(elem);
    }

    if (m_transformerType != null) {
        Element elem = document.createElement("SetTransformationType");
        CDATASection cdata = document.createCDATASection(m_transformerType);

        elem.appendChild(cdata);
        root0.appendChild(elem);
    }

    if (!StringUtils.isEmpty(m_strJavaClass)) {
        child = XMLDmiUtil.getNodeObject("JavaClass", m_strJavaClass, document);
        if (child != null) {
            root0.appendChild(child);
        }
    }

    if (m_params != null && m_params.size() > 0) {
        Enumeration _enum = m_params.elements();

        while (_enum.hasMoreElements()) {
            Param param = (Param) _enum.nextElement();
            if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue())) {
                if (!checkIfDefaultValue(param.getParamName(), param.getParamValue())) {
                    Node paramNode = param.toJXMLString(document);
                    root0.appendChild(paramNode);
                }
            }
        }
    }

    return root0;
}

From source file:org.gvnix.web.report.roo.addon.addon.ReportMetadata.java

/**
 * Creates a sample jrxml report file based in the template
 * report/JasperReport-template.jrxml with:
 * <ul>/*from   w w w  .ja v a  2 s .  co m*/
 * <li>3 field elements or less if the entity in fromBackingObject doesn't
 * has more than 3 member fields</li>
 * <li>As many staticText/textField element pairs as fields have been
 * created</li>
 * </ul>
 * The jrxml is copied to the WEB-INF/reports foder with the name
 * entity_report_name.jrxml
 * 
 * @param installedReport
 * @param fromBackingObject
 */
private void installJasperReportTemplate(String installedReport, JavaType fromBackingObject) {
    // Check if a jrxml file exists
    PathResolver pathResolver = projectOperations.getPathResolver();
    String reportJrXml = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            "WEB-INF/reports/".concat(fromBackingObject.getSimpleTypeName().toLowerCase()).concat("_")
                    .concat(installedReport.toLowerCase()).concat(".jrxml"));

    if (fileManager.exists(reportJrXml)) {
        // We can't modify the existing jrxml file just in case the user has
        // modified it
        return;
    }

    // Get member details of fromBackingObject type
    MemberDetails memberDetails = getMemberDetails(fromBackingObject);
    List<FieldMetadata> elegibleFields = webMetadataService.getScaffoldEligibleFieldMetadata(fromBackingObject,
            memberDetails, governorPhysicalTypeMetadata.getId());
    /*
     * We only use 3 fields in the sample report. By now we only use field
     * types accepted by JasperReports XMLSchema
     */
    List<FieldMetadata> usableFields = new ArrayList<FieldMetadata>();
    Iterator<FieldMetadata> it = elegibleFields.iterator();
    FieldMetadata field = null;
    while (it.hasNext() && usableFields.size() < 3) {
        field = it.next();
        if (ReportValidTypes.VALID_TYPES.contains(field.getFieldType().getFullyQualifiedTypeName())) {
            usableFields.add(field);
        }
    }

    InputStream templateInputStream = FileUtils.getInputStream(getClass(),
            "report/JasperReport-template.jrxml");

    Document jrxml;
    try {
        jrxml = XmlUtils.getDocumentBuilder().parse(templateInputStream);
    } catch (Exception ex) {
        throw new IllegalStateException("Could not open JasperReport-template.jrxml file", ex);
    }

    Element jasperReport = jrxml.getDocumentElement();

    // Add a field definition and its use in the detail band per
    // usableFields
    String textHeight = "20";
    String sTextW = "64";
    String fTextW = "119";
    String yPos = "0";
    int xPos = 0; // we need xPos as int in order to modify its value.
    Element staticText;
    Element textField;
    Element detailBand = XmlUtils.findFirstElement("/jasperReport/detail/band", jasperReport);
    Node backgroundNode = XmlUtils.findNode("/jasperReport/background", jasperReport);
    for (FieldMetadata fieldMetadata : usableFields) {
        jasperReport.insertBefore(new XmlElementBuilder("field", jrxml)
                .addAttribute("name", fieldMetadata.getFieldName().getSymbolName())
                .addAttribute("class", fieldMetadata.getFieldType().getFullyQualifiedTypeName()).build(),
                backgroundNode);
        staticText = (Element) new XmlElementBuilder("staticText", jrxml).build();
        staticText.appendChild(new XmlElementBuilder("reportElement", jrxml)
                .addAttribute("x", String.valueOf(xPos)).addAttribute("y", yPos).addAttribute("width", sTextW)
                .addAttribute("height", textHeight).build());
        staticText.appendChild(new XmlElementBuilder("textElement", jrxml).build());
        staticText.appendChild(new XmlElementBuilder("text", jrxml)
                .addChild(jrxml.createCDATASection(fieldMetadata.getFieldName().getReadableSymbolName()))
                .build());
        detailBand.appendChild(staticText);
        // Increment xPos for the next text box
        xPos += (Integer.parseInt(sTextW) + 1);
        textField = (Element) new XmlElementBuilder("textField", jrxml).build();
        textField.appendChild(new XmlElementBuilder("reportElement", jrxml)
                .addAttribute("x", String.valueOf(xPos)).addAttribute("y", yPos).addAttribute("width", fTextW)
                .addAttribute("height", textHeight).build());
        textField.appendChild(new XmlElementBuilder("textElement", jrxml).build());
        textField
                .appendChild(new XmlElementBuilder("textFieldExpression", jrxml)
                        .addAttribute("class", fieldMetadata.getFieldType().getFullyQualifiedTypeName())
                        .addChild(jrxml.createCDATASection(
                                "$F{".concat(fieldMetadata.getFieldName().getSymbolName()).concat("}")))
                        .build());
        detailBand.appendChild(textField);
        // Increment xPos for the next text box
        xPos += (Integer.parseInt(fTextW) + 1);
    }

    // We are sure that reportJrXml file doesn't exist so we can write it
    // with the jrxml document content
    MutableFile mutableFile = fileManager.createFile(reportJrXml);
    Validate.notNull(mutableFile, "Could not create jrxml file '".concat(reportJrXml).concat("'"));

    try {
        // Build a string representation of the jrxml
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        XmlUtils.writeXml(XmlUtils.createIndentingTransformer(), byteArrayOutputStream, jrxml);
        String jrxmlContent = byteArrayOutputStream.toString();

        // We need to write the file out (it's a new file, or the existing
        // file has different contents)
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = IOUtils.toInputStream(jrxmlContent);
            outputStream = mutableFile.getOutputStream();
            IOUtils.copy(inputStream, outputStream);
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
    } catch (IOException ioe) {
        throw new IllegalStateException("Could not output '".concat(mutableFile.getCanonicalPath()).concat("'"),
                ioe);
    }

}

From source file:com.fiorano.openesb.application.aps.Route.java

/**
 *  Returns the xml string equivalent of this object
 *
 * @param document the input Document object
 * @return element node/*from ww  w. j a va2s  .c  om*/
 * @exception FioranoException if an error occurs while creating the element
 *      node.
 */
Node toJXMLString(Document document) throws FioranoException {
    Node root0 = document.createElement("Route");

    ((Element) root0).setAttribute("isP2PRoute", "" + m_isP2PRoute);
    ((Element) root0).setAttribute("isPersistant", "" + m_isPersitant);
    ((Element) root0).setAttribute("isDurable", "" + m_isDurable);
    ((Element) root0).setAttribute("applyTransformationAtSrc", "" + m_applyTransformationAtSrc);

    Node node = null;

    node = XMLDmiUtil.getNodeObject("Name", m_routeName, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("RouteGUID", m_routeGUID, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("TimeToLive", "" + m_iTimeToLive, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("SrcServiceInstance", m_srcServInst, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("SrcPort", m_srcPortName, document);
    if (node != null)
        root0.appendChild(node);

    Element child = null;

    if (m_transformationXSL != null) {
        child = document.createElement("TransformationXSL");

        Node pcData = document.createCDATASection(m_transformationXSL);

        child.appendChild(pcData);
        root0.appendChild(child);
    }
    if (m_selectors != null) {
        Iterator itr = m_selectors.keySet().iterator();

        while (itr.hasNext()) {
            child = document.createElement("Selector");

            String type = (String) itr.next();

            child.setAttribute("type", type);

            Object val = m_selectors.get(type);
            String value = null;

            if (val instanceof String) {
                value = (String) m_selectors.get(type);
            } else if (val instanceof XPathDmi) {
                value = ((XPathDmi) val).getXPath();
                HashMap map = ((XPathDmi) val).getNameSpace();

                if (map != null) {
                    Set keys = map.keySet();
                    Iterator iter = keys.iterator();

                    while (iter.hasNext()) {
                        String key = (String) iter.next();
                        String keyval = (String) map.get(key);

                        child.setAttribute("esb_" + key, keyval);
                    }
                }
            }

            Node pcData = document.createTextNode(value);

            child.appendChild(pcData);
            root0.appendChild(child);
        }
    }

    node = XMLDmiUtil.getNodeObject("TgtServiceInstance", m_trgtServInst, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("TgtPort", m_trgtPortName, document);
    if (node != null)
        root0.appendChild(node);

    if (!StringUtils.isEmpty(m_longDescription)) {
        node = XMLDmiUtil.getNodeObject("LongDescription", m_longDescription, document);
        if (node != null)
            root0.appendChild(node);
    }
    if (!StringUtils.isEmpty(m_shortDescription)) {
        node = XMLDmiUtil.getNodeObject("ShortDescription", m_shortDescription, document);
        if (node != null)
            root0.appendChild(node);
    }
    if (m_altDestination != null) {
        root0.appendChild(m_altDestination.toJXMLString(document));
    }

    if (m_params != null && m_params.size() > 0) {
        Enumeration enums = m_params.elements();

        while (enums.hasMoreElements()) {
            Param param = (Param) enums.nextElement();
            if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue()))
                root0.appendChild(param.toJXMLString(document));
        }
    }

    return root0;
}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

public static Node writeObjectToXml(Document document, Object object, Object compiledValue) throws Exception {
    if (object == null)
        return null;

    if (object instanceof Enum) {
        object = ((Enum<?>) object).name();
    }/*from   ww w.jav  a 2s  . c  o  m*/

    // Simple objects
    if ((object instanceof Boolean) || (object instanceof Integer) || (object instanceof Double)
            || (object instanceof Float) || (object instanceof Character) || (object instanceof Long)
            || (object instanceof Short) || (object instanceof Byte)) {
        Element element = document.createElement(object.getClass().getName());
        element.setAttribute("value", object.toString());
        if (compiledValue != null)
            element.setAttribute("compiledValue", compiledValue.toString());
        return element;
    }
    // Strings
    else if (object instanceof String) {
        Element element = document.createElement(object.getClass().getName());
        element.setAttribute("value", object.toString());
        if (compiledValue != null) {
            element.setAttribute("compiledValueClass", compiledValue.getClass().getCanonicalName());
            element.setAttribute("compiledValue", compiledValue.toString());
        }
        return element;
    }
    // Arrays
    else if (object.getClass().getName().startsWith("[")) {
        String arrayClassName = object.getClass().getName();
        int i = arrayClassName.lastIndexOf('[');

        String itemClassName = arrayClassName.substring(i + 1);
        char c = itemClassName.charAt(itemClassName.length() - 1);
        switch (c) {
        case ';':
            itemClassName = itemClassName.substring(1, itemClassName.length() - 1);
            break;
        case 'B':
            itemClassName = "byte";
            break;
        case 'C':
            itemClassName = "char";
            break;
        case 'D':
            itemClassName = "double";
            break;
        case 'F':
            itemClassName = "float";
            break;
        case 'I':
            itemClassName = "int";
            break;
        case 'J':
            itemClassName = "long";
            break;
        case 'S':
            itemClassName = "short";
            break;
        case 'Z':
            itemClassName = "boolean";
            break;
        }

        Element element = document.createElement("array");
        element.setAttribute("classname", itemClassName);

        int len = Array.getLength(object);
        element.setAttribute("length", Integer.toString(len));

        Node subNode;
        for (int k = 0; k < len; k++) {
            subNode = writeObjectToXml(document, Array.get(object, k));
            if (subNode != null) {
                element.appendChild(subNode);
            }
        }

        return element;
    }
    // XMLization
    else if (object instanceof XMLizable) {
        Element element = document.createElement("xmlizable");
        element.setAttribute("classname", object.getClass().getName());
        element.appendChild(((XMLizable) object).writeXml(document));
        return element;
    }
    // Default serialization
    else {
        Element element = document.createElement("serializable");
        element.setAttribute("classname", object.getClass().getName());

        String objectBytesEncoded = null;
        byte[] objectBytes = null;

        // We write the object to a bytes array
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.flush();
        outputStream.close();

        // Now, we retrieve the object bytes
        objectBytes = outputStream.toByteArray();
        objectBytesEncoded = org.apache.commons.codec.binary.Base64.encodeBase64String(objectBytes);

        CDATASection cDATASection = document.createCDATASection(new String(objectBytesEncoded));
        element.appendChild(cDATASection);

        return element;
    }
}

From source file:com.enonic.vertical.adminweb.ContentObjectHandlerServlet.java

private Document buildContentObjectXML(AdminService admin, ExtendedMap formItems, boolean createContentObject,
        boolean updateStyleSheets) throws VerticalAdminException {
    Document doc;
    Element contentObject;//  www.  j a  v  a2s.c om
    if (updateStyleSheets) {
        doc = XMLTool.createDocument("contentobjects");
        Element root = doc.getDocumentElement();
        contentObject = XMLTool.createElement(doc, root, "contentobject");
    } else {
        doc = XMLTool.createDocument("contentobject");
        contentObject = doc.getDocumentElement();
    }

    contentObject.setAttribute("menukey", formItems.getString("menukey"));

    if (!createContentObject) {
        contentObject.setAttribute("key", formItems.getString("key"));

        String docContentKeyStr = formItems.getString("contentkey", null);
        if (docContentKeyStr != null) {
            contentObject.setAttribute("contentkey", docContentKeyStr);
        }
    }

    String runAsKey = formItems.getString("runAs", null);
    if (runAsKey != null) {
        contentObject.setAttribute("runAs", runAsKey);
    }

    Element tempElement;
    if (updateStyleSheets) {
        String name = formItems.getString("name", null);
        if (name != null) {
            tempElement = XMLTool.createElement(doc, contentObject, "name", name);
        } else {
            tempElement = XMLTool.createElement(doc, contentObject, "name");
        }
    } else {
        String name = formItems.getString("name");
        tempElement = XMLTool.createElement(doc, contentObject, "name", name);
    }

    /*
    if (formItems.containsKey("viewborderstylesheet")) {
    tempElement = XMLTool.createElement(doc, contentObject, "borderstylesheet");
    tempElement.setAttribute("key", formItems.getString("viewborderstylesheet"));
    }
            
            
    if (formItems.containsKey("viewstylesheet")) {
    tempElement = XMLTool.createElement(doc, contentObject, "objectstylesheet");
    tempElement.setAttribute("key", formItems.getString("viewstylesheet"));
    }
    */

    ResourceKey stylesheetKey = ResourceKey.parse(formItems.getString("stylesheet", null));
    if (stylesheetKey != null) {
        tempElement = XMLTool.createElement(doc, contentObject, "objectstylesheet");
        tempElement.setAttribute("key", String.valueOf(stylesheetKey));
    }

    ResourceKey borderStylesheetKey = ResourceKey.parse(formItems.getString("borderstylesheet", null));
    if (borderStylesheetKey != null) {
        tempElement = XMLTool.createElement(doc, contentObject, "borderstylesheet");
        tempElement.setAttribute("key", String.valueOf(borderStylesheetKey));
    }

    /*
    String ssName = formItems.getString("viewborderstylesheet", null);
    if (ssName != null) {
    tempElement = XMLTool.createElement(doc, contentObject, "borderstylesheet", ssName);
    ResourceKey stylesheetKey = new ResourceKey(formItems.getInt("borderstylesheet"));
    tempElement.setAttribute("key", String.valueOf(stylesheetKey));
    boolean shared = admin.isResourceShared(stylesheetKey);
    if (shared)
        tempElement.setAttribute("shared", "true");
    }
            
    ssName = formItems.getString("viewstylesheet", null);
    if (ssName != null) {
    tempElement = XMLTool.createElement(doc, contentObject, "objectstylesheet", ssName);
    tempElement.setAttribute("key", formItems.getString("stylesheet"));
    ResourceKey stylesheetKey = new ResourceKey(formItems.getInt("stylesheet"));
    tempElement.setAttribute("key", String.valueOf(stylesheetKey));
    boolean shared = admin.isResourceShared(stylesheetKey);
    if (shared)
        tempElement.setAttribute("shared", "true");
    }
    */

    Element contentObjectData = XMLTool.createElement(doc, contentObject, "contentobjectdata");

    // caching
    String cacheType = formItems.getString("cachetype");
    if (!"off".equals(cacheType)) {
        contentObjectData.setAttribute("cachedisabled", "false");

        // cache type
        contentObjectData.setAttribute("cachetype", cacheType);

        if (cacheType.equals("specified")) {
            contentObjectData.setAttribute("mincachetime", formItems.getString("mincachetime"));
        }
    } else {
        contentObjectData.setAttribute("cachedisabled", "true");
    }

    // document
    Element document = XMLTool.createElement(doc, contentObjectData, "document");

    if (verticalProperties.isStoreXHTMLOn()) {
        XMLTool.createXHTMLNodes(doc, document, formItems.getString("contentdata_body", ""), true);
    } else {
        XMLTool.createCDATASection(doc, document, formItems.getString("contentdata_body", ""));
    }

    Document datasourcesDoc = null;
    try {
        String datasources = formItems.getString("datasources", null);
        // Do NOT replace this with formItems.getString("datasources", "</datasources">) since
        // the editor could send blankspaces
        if (StringUtils.isBlank(datasources)) {
            datasources = "<datasources/>";
        }

        datasourcesDoc = XMLTool.domparse(datasources, "datasources");
    } catch (Exception e) {
        String message = "Failed to parse datasource document: %t";
        VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, e);
    }
    contentObjectData.appendChild(doc.importNode(datasourcesDoc.getDocumentElement(), true));

    // Add script
    Element scriptElem = doc.createElement("script");
    scriptElem.appendChild(doc.createCDATASection(formItems.getString("script", "")));
    contentObjectData.appendChild(scriptElem);

    // Stylesheet params
    Element styleSheetParams = XMLTool.createElement(doc, contentObjectData, "stylesheetparams");
    if (isArrayFormItem(formItems, "xslparam_name")) {
        String[] xslParameters = (String[]) formItems.get("xslparam_name");
        String[] xslParameterValues = (String[]) formItems.get("xslparam_value");
        String[] xslParameterTypes = (String[]) formItems.get("xslparam_type");

        for (int i = 0; i < xslParameters.length; i++) {
            String valueStr = xslParameterValues[i];
            if (valueStr != null && valueStr.length() > 0) {
                tempElement = XMLTool.createElement(doc, styleSheetParams, "stylesheetparam", valueStr);
                tempElement.setAttribute("name", xslParameters[i]);
                if (xslParameterTypes[i] != null && xslParameterTypes[i].length() > 0) {
                    String type = xslParameterTypes[i];
                    tempElement.setAttribute("type", type);

                    if ("page".equals(type)) {
                        int menuItemKey = -1;
                        try {
                            menuItemKey = Integer.parseInt(valueStr);
                        } catch (NumberFormatException nfe) {
                            String message = "Failed to parse menu item key: %t";
                            VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, nfe);
                        }
                        String menuItemName = admin.getMenuItemName(menuItemKey);
                        tempElement.setAttribute("valuename", menuItemName);
                    } else if ("category".equals(type)) {
                        int categoryKey = -1;
                        try {
                            categoryKey = Integer.parseInt(valueStr);
                        } catch (NumberFormatException nfe) {
                            String message = "Failed to parse category key: %t";
                            VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, nfe);
                        }
                        String categoryName = admin.getCategoryName(categoryKey);
                        tempElement.setAttribute("valuename", categoryName);
                    }
                }
            }
        }
    } else if (formItems.containsKey("xslparam_name")) {
        //String valueStr = (String) formItems.get("xslparam_value", null);
        if (formItems.containsKey("xslparam_value")) {
            String valueStr = formItems.getString("xslparam_value");
            tempElement = XMLTool.createElement(doc, styleSheetParams, "stylesheetparam", valueStr);
            tempElement.setAttribute("name", formItems.getString("xslparam_name"));
            String xslParameterType = formItems.getString("xslparam_type", null);
            if (xslParameterType != null) {
                String type = xslParameterType;
                tempElement.setAttribute("type", type);

                if ("page".equals(type)) {
                    int menuItemKey = -1;
                    try {
                        menuItemKey = formItems.getInt("xslparam_value");
                    } catch (NumberFormatException nfe) {
                        String message = "Failed to parse menu item key: %t";
                        VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, nfe);
                    }
                    String menuItemName = admin.getMenuItemName(menuItemKey);
                    tempElement.setAttribute("valuename", menuItemName);
                } else if ("category".equals(type)) {
                    int categoryKey = -1;
                    try {
                        categoryKey = formItems.getInt("xslparam_value");
                    } catch (NumberFormatException nfe) {
                        String message = "Failed to parse menu item key: %t";
                        VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, nfe);
                    }
                    String categoryName = admin.getCategoryName(categoryKey);
                    tempElement.setAttribute("valuename", categoryName);
                }
            }
        }
    }

    // border params
    Element borderParams = XMLTool.createElement(doc, contentObjectData, "borderparams");
    if (isArrayFormItem(formItems, "borderparam_name")) {
        String[] borderParameters = (String[]) formItems.get("borderparam_name");
        String[] borderParameterValues = (String[]) formItems.get("borderparam_value");
        String[] borderParameterTypes = (String[]) formItems.get("borderparam_type");

        for (int i = 0; i < borderParameters.length; i++) {
            String valueStr = borderParameterValues[i];
            if (valueStr != null && valueStr.length() > 0) {
                tempElement = XMLTool.createElement(doc, borderParams, "borderparam", valueStr);
                tempElement.setAttribute("name", borderParameters[i]);
                if (borderParameterTypes[i] != null && borderParameterTypes[i].length() > 0) {
                    String type = borderParameterTypes[i];
                    tempElement.setAttribute("type", type);

                    if ("page".equals(type)) {
                        int menuItemKey = -1;
                        try {
                            menuItemKey = Integer.parseInt(valueStr);
                        } catch (NumberFormatException nfe) {
                            String message = "Failed to parse menu item key: %t";
                            VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, nfe);
                        }
                        String menuItemName = admin.getMenuItemName(menuItemKey);
                        tempElement.setAttribute("valuename", menuItemName);
                    } else if ("category".equals(type)) {
                        int categoryKey = -1;
                        try {
                            categoryKey = Integer.parseInt(valueStr);
                        } catch (NumberFormatException nfe) {
                            String message = "Failed to parse menu item key: %t";
                            VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, nfe);
                        }
                        String categoryName = admin.getCategoryName(categoryKey);
                        tempElement.setAttribute("valuename", categoryName);
                    }
                }
            }
        }
    } else if (formItems.containsKey("borderparam_name")) {
        String valueStr = formItems.getString("borderparam_value", null);
        if (valueStr != null && valueStr.length() > 0) {
            tempElement = XMLTool.createElement(doc, borderParams, "borderparam", valueStr);
            tempElement.setAttribute("name", formItems.getString("borderparam_name"));
            String borderParameterType = formItems.getString("borderparam_type", null);
            if (borderParameterType != null) {
                String type = borderParameterType;
                tempElement.setAttribute("type", type);

                if ("page".equals(type)) {
                    int menuItemKey = -1;
                    try {
                        menuItemKey = Integer.parseInt(valueStr);
                    } catch (NumberFormatException nfe) {
                        String message = "Failed to parse menu item key: %t";
                        VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, nfe);
                    }
                    String menuItemName = "null";
                    menuItemName = admin.getMenuItemName(menuItemKey);
                    tempElement.setAttribute("valuename", menuItemName);
                } else if ("category".equals(type)) {
                    int categoryKey = -1;
                    try {
                        categoryKey = Integer.parseInt(valueStr);
                    } catch (NumberFormatException nfe) {
                        String message = "Failed to parse menu item key: %t";
                        VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, nfe);
                    }
                    String categoryName = admin.getCategoryName(categoryKey);
                    tempElement.setAttribute("valuename", categoryName);
                }
            }
        }
    }

    return doc;
}