Example usage for org.w3c.dom Document importNode

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

Introduction

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

Prototype

public Node importNode(Node importedNode, boolean deep) throws DOMException;

Source Link

Document

Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.

Usage

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

public Document getMenuItemsByPageTemplates(User user, int[] pageTemplateKeys) {

    Connection con = null;//from  w ww .j av  a2 s  . c o  m
    PreparedStatement preparedStmt = null;
    ResultSet resultSet = null;

    Document doc = XMLTool.createDocument("menuitems");

    if (pageTemplateKeys != null && pageTemplateKeys.length > 0) {
        try {
            StringBuffer sql = new StringBuffer(MENU_ITEMS_BY_PAGETEMPLATES);
            for (int i = 0; i < pageTemplateKeys.length; i++) {
                if (i > 0) {
                    sql.append(',');
                }
                sql.append(pageTemplateKeys[i]);
            }
            sql.append("))");

            con = getConnection();
            preparedStmt = con.prepareStatement(sql.toString());
            resultSet = preparedStmt.executeQuery();

            Element rootElem = doc.getDocumentElement();
            while (resultSet.next()) {
                int meiKey = resultSet.getInt("mei_lKey");

                Document menuItemDoc = getMenuItem(user, meiKey, -1, false, false, false, false, true, false,
                        false, 1);

                Element tmpElem = (Element) menuItemDoc.getDocumentElement().getFirstChild();
                if (tmpElem != null) {
                    rootElem.appendChild(doc.importNode(tmpElem, true));
                }
            }
        } catch (SQLException e) {
            VerticalEngineLogger.warn(this.getClass(), 10, "A database error occurred. XML may be incomplete.",
                    e);
        } finally {
            close(resultSet);
            close(preparedStmt);
            close(con);
        }
    }

    return doc;
}

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

private void menuItemForm(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems) throws VerticalAdminException {

    int menuKey = formItems.getInt("menukey");

    User user = securityService.getLoggedInAdminConsoleUser();
    String menuXML = admin.getAdminMenu(user, menuKey);

    boolean forwardData = formItems.getBoolean("forward_data", false);
    boolean create;

    String menuItemXML = null;//from w  w w . ja  va 2s  .  com
    String categoryXML = null;
    String pageTemplatesXML;
    String pageTemplateParamsXML = null;
    String defaultAccessRightXML = null;

    // menuitem key:
    String key = formItems.getString("key", null);

    try {
        if (key != null && !key.startsWith("f") && !key.equals("none")) {
            create = false;
            menuItemXML = admin.getMenuItem(user, Integer.parseInt(key), false, true);
        } else {
            create = true;
            String insertBelow = formItems.getString("insertbelow", null);
            if (insertBelow != null && !"-1".equals(insertBelow)) {
                defaultAccessRightXML = admin.getAccessRights(user, AccessRight.MENUITEM,
                        Integer.parseInt(insertBelow), true);
            } else {
                defaultAccessRightXML = admin.getAccessRights(user, AccessRight.MENUITEM_DEFAULT, menuKey,
                        true);
            }
        }

        int[] excludeTypeKeys = null; // before we excluded page-tempales of type newsletter, but not anymore.
        pageTemplatesXML = admin.getPageTemplatesByMenu(menuKey, excludeTypeKeys);

        Document doc1 = XMLTool.domparse(menuXML);
        Element menuElem = XMLTool.selectElement(doc1.getDocumentElement(), "//menu[@key = '" + menuKey + "']");

        int pageTemplateKey = formItems.getInt("selpagetemplatekey", -1);
        if (pageTemplateKey < 0 && create) {
            // selpagetemplatekey has not been set... set it to parent or default
            // pagetemplatekey (if appliccable)
            int insertBelow = -1;
            if (formItems.containsKey("insertbelow")
            /* && formItems.get("insertbelow") instanceof Integer */ ) {
                insertBelow = formItems.getInt("insertbelow");
            }

            pageTemplateKey = findParentPagetemplateKey(doc1, insertBelow);
            formItems.putInt("selpagetemplatekey", pageTemplateKey);
        }

        if (pageTemplateKey >= 0) {
            pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey);
        } else if (menuItemXML != null
                && XMLTool.getElementText(menuItemXML, "//page/@pagetemplatekey") != null) {
            pageTemplateKey = Integer.parseInt(XMLTool.getElementText(menuItemXML, "//page/@pagetemplatekey"));
            pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey);
        } else {
            String tmp = menuElem.getAttribute("defaultpagetemplate");
            if (tmp != null && tmp.length() > 0) {
                pageTemplateKey = Integer.parseInt(tmp);
                pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey);
            }
        }

        // insert correct menuitem XML:
        Element menuitemElem = null;
        if (menuItemXML != null) {
            Document miDoc = XMLTool.domparse(menuItemXML);
            Element tmpElem = miDoc.getDocumentElement();
            tmpElem = XMLTool.getFirstElement(tmpElem);

            if (tmpElem != null) {
                // add read count
                // int readCount = admin.getReadCount(LogHandler.TABLE_TMENUITEM, Integer.parseInt(key));
                // Element elem = XMLTool.createElement(miDoc, tmpElem, "logentries");
                // elem.setAttribute("totalread", String.valueOf(readCount));

                if (tmpElem != null) {
                    String xpath = "//menuitem[@key = '" + key + "']";
                    Element oldElem = (Element) XMLTool.selectNode(doc1.getDocumentElement(), xpath);
                    if (oldElem != null) {
                        Element menuitemsElem = (Element) oldElem.getParentNode();
                        menuitemElem = (Element) doc1.importNode(tmpElem, true);
                        menuitemsElem.replaceChild(menuitemElem, oldElem);
                    }
                }
            }
        }

        Document pageTemplateDoc = XMLTool.domparse(pageTemplatesXML);

        XMLTool.mergeDocuments(doc1, pageTemplateDoc, true);

        if (defaultAccessRightXML != null) {
            XMLTool.mergeDocuments(doc1, XMLTool.domparse(defaultAccessRightXML), true);
        }

        ExtendedMap parameters = new ExtendedMap();

        if (forwardData) {
            // get accessrights element
            Node nodeAccessRights;
            if (create) {
                nodeAccessRights = XMLTool.selectNode(doc1.getDocumentElement(), "/menus/accessrights");
            } else {
                nodeAccessRights = XMLTool.selectNode(doc1.getDocumentElement(),
                        "//menuitem[@key=" + key + "]/accessrights");
            }

            // get new accessrights xml from parameters
            String xmlAccessRights = buildAccessRightsXML(formItems);
            if (xmlAccessRights != null) {
                Document docAccessRights = XMLTool.domparse(xmlAccessRights);

                if (docAccessRights.getDocumentElement().hasChildNodes())
                // replace accessrights element with the generated accessrights
                {
                    nodeAccessRights.getParentNode().replaceChild(
                            doc1.importNode(docAccessRights.getDocumentElement(), true), nodeAccessRights);
                }
            }

            // get custom parameters
            // get parameters element
            Node nodeParameters;
            if (create) {
                Node nodeMenu = XMLTool.selectNode(doc1.getDocumentElement(), "/menus");
                nodeParameters = XMLTool.createElement(doc1, (Element) nodeMenu, "parameters");
                nodeMenu.appendChild(nodeParameters);
            } else {
                nodeParameters = XMLTool.selectNode(doc1.getDocumentElement(),
                        "//menuitem[@key=" + key + "]/parameters");
            }

            XMLTool.removeChildNodes((Element) nodeParameters, false);

            if (isArrayFormItem(formItems, "paramname")) {
                String[] paramName = (String[]) formItems.get("paramname");
                String[] paramValue = (String[]) formItems.get("paramval");
                for (int i = 0; i < paramName.length; i++) {
                    final String currParamName = paramName[i];
                    if (currParamName == null || !currParamName.trim().equals("")) {
                        Element newElem = XMLTool.createElement(doc1, (Element) nodeParameters, "parameter",
                                paramValue[i]);
                        newElem.setAttribute("name", currParamName);
                        nodeParameters.appendChild(newElem);
                    }
                }
            } else {
                // ingen sideparametre finnes, vi lager en
                String paramName = formItems.getString("paramname", "");
                String paramValue = formItems.getString("paramval", "");
                if (paramName.length() > 0) {
                    Element newElem = XMLTool.createElement(doc1, (Element) nodeParameters, "parameter",
                            paramValue);
                    newElem.setAttribute("name", paramName);
                    nodeParameters.appendChild(newElem);
                }
            }
            parameters.put("referer", formItems.getString("referer"));

        }

        if (pageTemplateParamsXML == null) {
            Element nameElem = (Element) XMLTool.selectNode(doc1, "//menuitem[@key = '" + key + "']/page");

            if (nameElem != null) {
                pageTemplateKey = Integer.parseInt(nameElem.getAttribute("pagetemplatekey"));
                pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey);
            }
        }

        Document doc8;
        if (pageTemplateParamsXML != null) {
            doc8 = XMLTool.domparse(pageTemplateParamsXML);
            XMLTool.mergeDocuments(doc1, doc8, true);
        }

        String xpath = "/pagetemplates/pagetemplate[@key=" + pageTemplateKey + "]";
        Element pagetemplateElem = (Element) XMLTool.selectNode(pageTemplateDoc, xpath);
        if (pagetemplateElem != null) {
            String pageTemplateType = pagetemplateElem.getAttribute("type");
            if ("form".equals(pageTemplateType)) {
                Element dataElem = XMLTool.getElement(menuitemElem, "data");
                Element formElem = XMLTool.getElement(dataElem, "form");
                if (formElem != null) {
                    String keyStr = formElem.getAttribute("categorykey");
                    if (keyStr.length() > 0) {
                        int categoryKey = Integer.parseInt(keyStr);
                        categoryXML = admin.getCategoryNameXML(categoryKey);
                    }
                }
            }
        }

        if (categoryXML != null) {
            Document doc5 = XMLTool.domparse(categoryXML);
            XMLTool.mergeDocuments(doc1, doc5, true);
        }

        // Get content types for this site
        XMLTool.mergeDocuments(doc1, admin.getContentTypes(false).getAsDOMDocument(), true);

        // Append languages
        Document langs = XMLTool.domparse(admin.getLanguages());
        XMLTool.mergeDocuments(doc1, langs, true);

        DOMSource xmlSource = new DOMSource(doc1);

        // Stylesheet
        Source xslSource = AdminStore.getStylesheet(session, "menu_item_form.xsl");

        // Parameters
        addCommonParameters(admin, user, request, parameters, -1, menuKey);
        parameters.put("page", String.valueOf(request.getParameter("page")));
        if ((key == null || key.length() == 0 || key.equals("none"))) {
            parameters.put("key", "none");
        } else {
            parameters.put("key", key);
        }

        String type = formItems.getString("type", null);
        if ((type == null || "page".equals(type)) && pageTemplateKey >= 0) {
            if (pagetemplateElem != null) {
                type = pagetemplateElem.getAttribute("type");
            }
        }

        if ("document".equals(type) || "form".equals(type)) {
            type = "content";
        }

        parameters.put("type", type);
        parameters.put("insertbelow", formItems.getString("insertbelow", null));
        parameters.put("selpagetemplatekey", String.valueOf(pageTemplateKey));
        parameters.put("name", formItems.getString("name", null));

        if ("on".equals(formItems.getString("visibility", null))) {
            parameters.put("visibility", "on");
        }

        parameters.put("forward_data", formItems.get("forward_data", Boolean.FALSE));
        parameters.put("menu-name", formItems.getString("menu-name", null));
        parameters.put("displayname", formItems.getString("displayname", null));
        parameters.put("description", formItems.getString("description", null));
        parameters.put("keywords", formItems.getString("keywords", null));
        parameters.put("alias", formItems.getString("alias", null));
        parameters.put("document", formItems.getString("contentdata_body", null));
        if (formItems.getString("noauth", null) != null) {
            if ("on".equals(formItems.getString("noauth", null))) {
                parameters.put("noauth", "false");
            } else {
                parameters.put("noauth", "true");
            }
        }
        parameters.put("catselkey", formItems.getString("catsel", null));
        parameters.put("catkey", formItems.getString("category_key", null));
        parameters.put("catname", formItems.getString("viewcategory_key", null));
        parameters.put("menukey", String.valueOf(menuKey));

        // find content title if contentkey is specified
        if (menuitemElem != null) {
            String contentKeyStr = menuitemElem.getAttribute("contentkey");
            if (contentKeyStr.length() > 0) {
                int contentKey = Integer.parseInt(contentKeyStr);
                int versionKey = admin.getCurrentVersionKey(contentKey);
                String contentTitle = admin.getContentTitle(versionKey);
                parameters.put("contenttitle", contentTitle);
            }
        }

        // Adds accessrights values, so that these can be remembered until next page
        for (Object formItemKey : formItems.keySet()) {
            String paramName = (String) formItemKey;
            if (paramName.startsWith("accessright[key=")) {
                parameters.put(paramName, formItems.getString(paramName));
            }
        }
        parameters.put("selectedtabpageid", formItems.getString("selectedtabpageid", null));

        // Get form categories
        int[] contentTypeKeys = admin.getContentTypesByHandlerClass(
                "com.enonic.vertical.adminweb.handlers.ContentFormHandlerServlet");
        if (contentTypeKeys != null && contentTypeKeys.length > 0) {
            StringBuffer contentTypeString = new StringBuffer();
            for (int i = 0; i < contentTypeKeys.length; i++) {
                if (i > 0) {
                    contentTypeString.append(',');
                }
                contentTypeString.append(contentTypeKeys[i]);
            }
            parameters.put("contenttypestring", contentTypeString.toString());
        } else {
            parameters.put("contenttypestring", "99999");
        }

        addAccessLevelParameters(user, parameters);

        UserEntity defaultRunAsUser = siteDao.findByKey(formItems.getInt("menukey")).resolveDefaultRunAsUser();
        String defaultRunAsUserName = "NA";
        if (defaultRunAsUser != null) {
            defaultRunAsUserName = defaultRunAsUser.getDisplayName();
        }
        parameters.put("defaultRunAsUser", defaultRunAsUserName);

        transformXML(session, response.getWriter(), xmlSource, xslSource, parameters);

    } catch (IOException ioe) {
        String msg = "I/O error: %t";
        VerticalAdminLogger.errorAdmin(this.getClass(), 0, msg, ioe);
    } catch (TransformerException te) {
        String msg = "XSL transformer error: %t";
        VerticalAdminLogger.errorAdmin(this.getClass(), 0, msg, te);
    }
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

private Document replaceIfExistingByXPaths(final Document originalDom, final Document modifiedDom,
        Map<String, String> xPathPairs) throws XPathExpressionException {

    Document finalDom = originalDom;
    Element finalDomRoot = (Element) finalDom.getFirstChild();

    //Element modifiedDomRoot = (Element) modifiedDom.getFirstChild();

    Element lastChild = null;/*from w  ww  . j  ava  2  s  .c  o  m*/

    for (Entry<String, String> xPathPair : xPathPairs.entrySet()) {

        /**
         * basically, this is to copy the element specified in srcXPath, and
         * replace/add it to the position pointed by destXPath...
         */
        String srcXPath = xPathPair.getKey();

        logger.debug("srcXPath: " + srcXPath);

        String destXPath = xPathPair.getValue();

        logger.debug("destXPath: " + destXPath);

        XPath xPath = getXPathInstance();
        // find all the nodes specified by destXPath in the originalDom, and
        // delete them all
        NodeList existingNodeList = (NodeList) (xPath.evaluate(destXPath, finalDom, XPathConstants.NODESET));

        xPath.reset();
        // find all the nodes specified by srcXPath in the modifiedDom
        NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET));

        int el = existingNodeList.getLength();

        logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath);

        int l = nodeList.getLength();

        logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath);

        for (int i = 0; i < el; i++) {
            Node c = existingNodeList.item(i);

            //xPathExpression = xPath.compile(srcXPath);
            //NodeList srcNodeLst = (NodeList) (xPathExpression.evaluate(
            //modifiedDom, XPathConstants.NODESET));
            //NodeList srcNodeLst = modifiedDomRoot.getElementsByTagName(c.getNodeName());

            if (l > 0) {
                // remove this node from its parent...

                c.getParentNode().removeChild(c);
                logger.debug("Node:" + c.getNodeName() + " is removed!");
            }

        }

        // create the node structure first. and return the last child of the
        // path... the right most node...
        lastChild = createElementStructureByPath(finalDomRoot, destXPath);

        List<String> nodeNameList = getNodeList(destXPath);

        String lastNodeName = nodeNameList.get(nodeNameList.size() - 1);

        Node currentNode = null;
        for (int i = 0; i < l; i++) {
            currentNode = nodeList.item(i);

            // the name of the last node in srcXPath might not be the same
            // as the name of the last node in destXPath
            Element lastElement = finalDom.createElement(lastNodeName);

            // NodeList currentNodeChildNodes = currentNode.getChildNodes();
            // int s = currentNodeChildNodes.getLength();
            // for(int j = 0; j < s; j++){
            // lastElement.appendChild(finalDom.importNode(currentNodeChildNodes.item(j),
            // true));
            // }
            if (currentNode.hasAttributes()) {
                NamedNodeMap attributes = currentNode.getAttributes();

                for (int j = 0; j < attributes.getLength(); j++) {
                    String attribute_name = attributes.item(j).getNodeName();
                    String attribute_value = attributes.item(j).getNodeValue();

                    lastElement.setAttribute(attribute_name, attribute_value);
                }
            }

            while (currentNode.hasChildNodes()) {
                Node kid = currentNode.getFirstChild();
                currentNode.removeChild(kid);
                lastElement.appendChild(finalDom.importNode(kid, true));
            }

            lastChild.appendChild(lastElement);

        }

    }

    return finalDom;

}

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

protected Document getMenuItem(User user, int key, int tagItem, boolean withParents, boolean complete,
        boolean includePageConfig, boolean withChildren, boolean includeHidden, boolean includeTypeSpecificXML,
        boolean tagItems, int levels) {

    Document doc = XMLTool.createDocument("menuitems");
    Element rootElement = doc.getDocumentElement();

    Connection con = null;//from  ww  w .  j av  a  2 s. c o  m
    PreparedStatement preparedStmt = null;
    ResultSet resultSet = null;
    try {
        con = getConnection();

        String sql = getSecurityHandler().appendMenuItemSQL(user, MENU_ITEM_SELECT_BY_KEY, null);
        preparedStmt = con.prepareStatement(sql);

        preparedStmt.setInt(1, key);
        resultSet = preparedStmt.executeQuery();

        if (!withChildren) {
            if (resultSet.next()) {
                buildMenuItemXML(doc, rootElement, resultSet, tagItem, complete, includePageConfig,
                        includeHidden, includeTypeSpecificXML, tagItems, levels);
            }

            // include parents?
            if (withParents) {
                // yep. call getMenuItemDOM recursivly.
                Element menuItemElement = (Element) doc.getDocumentElement().getFirstChild();
                String tmp = menuItemElement.getAttribute("parent");

                while (tmp != null && tmp.length() > 0) {
                    // get the parent:
                    doc = getMenuItem(user, Integer.parseInt(tmp), false, false, false);

                    // move the child inside the parent:
                    rootElement = doc.getDocumentElement();
                    Element parentElement = (Element) rootElement.getFirstChild();
                    Element menuItemsElement = XMLTool.createElement(doc, parentElement, "menuitems");
                    menuItemsElement.appendChild(doc.importNode(menuItemElement, true));
                    menuItemElement = parentElement;

                    tmp = menuItemElement.getAttribute("parent");
                }
            }
        } else {
            buildMenuItemsXML(user, resultSet, doc, rootElement, levels, tagItem, complete, includePageConfig,
                    includeHidden, includeTypeSpecificXML, tagItems);
        }
    } catch (SQLException sqle) {
        VerticalEngineLogger.error(this.getClass(), 30, "SQL error.", sqle);
    } finally {
        close(resultSet);
        close(preparedStmt);
        close(con);
    }

    return doc;

}

From source file:ddf.catalog.services.xsltlistener.XsltResponseQueueTransformer.java

@Override
public ddf.catalog.data.BinaryContent transform(SourceResponse upstreamResponse,
        Map<String, Serializable> arguments) throws CatalogTransformerException {

    LOGGER.debug("Transforming ResponseQueue with XSLT tranformer");

    long grandTotal = -1;

    try {/*from  w  w w . j  a  v a  2 s.  c o m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.newDocument();

        Node resultsElement = doc.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "results", null));

        // TODO use streaming XSLT, not DOM
        List<Result> results = upstreamResponse.getResults();
        grandTotal = upstreamResponse.getHits();

        for (Result result : results) {
            Metacard metacard = result.getMetacard();
            String thisMetacard = metacard.getMetadata();
            if (metacard != null && thisMetacard != null) {
                Element metacardElement = createElement(doc, XML_RESULTS_NAMESPACE, "metacard", null);
                if (metacard.getId() != null) {
                    metacardElement
                            .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "id", metacard.getId()));
                }
                if (metacard.getMetacardType().toString() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "type",
                            metacard.getMetacardType().getName()));
                }
                if (metacard.getTitle() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "title", metacard.getTitle()));
                }
                if (result.getRelevanceScore() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "score",
                            result.getRelevanceScore().toString()));
                }
                if (result.getDistanceInMeters() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "distance",
                            result.getDistanceInMeters().toString()));
                }
                if (metacard.getSourceId() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "site", metacard.getSourceId()));
                }
                if (metacard.getContentTypeName() != null) {
                    String contentType = metacard.getContentTypeName();
                    Element typeElement = createElement(doc, XML_RESULTS_NAMESPACE, "content-type",
                            contentType);
                    // TODO revisit what to put in the qualifier
                    typeElement.setAttribute("qualifier", "content-type");
                    metacardElement.appendChild(typeElement);
                }
                if (metacard.getResourceURI() != null) {
                    try {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "product",
                                metacard.getResourceURI().toString()));
                    } catch (DOMException e) {
                        LOGGER.warn(" Unable to create resource uri element", e);
                    }
                }
                if (metacard.getThumbnail() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail",
                            Base64.encodeBase64String(metacard.getThumbnail())));
                    try {
                        String mimeType = URLConnection
                                .guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail()));
                        metacardElement
                                .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType));
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        metacardElement.appendChild(
                                createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", "image/png"));
                    }
                }
                DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                if (metacard.getCreatedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "created",
                            fmt.print(metacard.getCreatedDate().getTime())));
                }
                // looking at the date last modified
                if (metacard.getModifiedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "updated",
                            fmt.print(metacard.getModifiedDate().getTime())));
                }
                if (metacard.getEffectiveDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "effective",
                            fmt.print(metacard.getEffectiveDate().getTime())));
                }
                if (metacard.getLocation() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "location", metacard.getLocation()));
                }
                Element documentElement = doc.createElementNS(XML_RESULTS_NAMESPACE, "document");
                metacardElement.appendChild(documentElement);
                resultsElement.appendChild(metacardElement);

                Node importedNode = doc.importNode(new XPathHelper(thisMetacard).getDocument().getFirstChild(),
                        true);
                documentElement.appendChild(importedNode);
            } else {
                LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer");
                continue;
            }
        }

        if (LOGGER.isDebugEnabled()) {
            DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
            LSSerializer lsSerializer = domImplementation.createLSSerializer();
            LOGGER.debug("Generated XML input for transform: " + lsSerializer.writeToString(doc));
        }

        LOGGER.debug("Starting responsequeue xslt transform.");

        Transformer transformer;

        Map<String, Object> mergedMap = new HashMap<String, Object>();
        mergedMap.put(GRAND_TOTAL, grandTotal);
        if (arguments != null) {
            mergedMap.putAll(arguments);
        }

        BinaryContent resultContent;
        StreamResult resultOutput = null;
        Source source = new DOMSource(doc);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        resultOutput = new StreamResult(baos);

        try {
            transformer = templates.newTransformer();
        } catch (TransformerConfigurationException tce) {
            throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(),
                    tce.getCause());
        }

        if (mergedMap != null && !mergedMap.isEmpty()) {
            for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            "Adding parameter to transform {" + entry.getKey() + ":" + entry.getValue() + "}");
                }
                transformer.setParameter(entry.getKey(), entry.getValue());
            }
        }

        try {
            transformer.transform(source, resultOutput);
            byte[] bytes = baos.toByteArray();
            LOGGER.debug("Transform complete.");
            resultContent = new XsltTransformedContent(bytes, mimeType);
        } catch (TransformerException te) {
            LOGGER.error("Could not perform Xslt transform: " + te.getException(), te.getCause());
            throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getException(),
                    te.getCause());
        } finally {
            // transformer.reset();
            // don't need to do that unless we are putting it back into a
            // pool -- which we should do, but that can wait until later.
        }

        return resultContent;
    } catch (ParserConfigurationException e) {
        LOGGER.warn("Error creating new document: " + e.getMessage(), e.getCause());
        throw new CatalogTransformerException("Error merging entries to xml feed.", e);
    }
}

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

protected Document getMenuItem(User user, int key, boolean withParents, boolean complete,
        boolean includePageConfig, boolean withChildren) {

    Document doc;
    Element rootElement;/*from  www  .jav  a  2  s  .co m*/
    doc = XMLTool.createDocument("menuitems");
    rootElement = doc.getDocumentElement();

    Connection con = null;
    PreparedStatement preparedStmt = null;
    ResultSet resultSet = null;
    try {
        con = getConnection();

        preparedStmt = con
                .prepareStatement(getSecurityHandler().appendMenuItemSQL(user, MENU_ITEM_SELECT_BY_KEY));
        preparedStmt.setInt(1, key);
        resultSet = preparedStmt.executeQuery();

        if (!withChildren) {
            if (resultSet.next()) {
                buildMenuItemXML(doc, rootElement, resultSet, -1, complete, includePageConfig, true, true, true,
                        -1);
            }

            // include parents?
            if (withParents) {
                // yep. call getMenuItemDOM recursivly.
                Element menuItemElement = (Element) doc.getDocumentElement().getFirstChild();
                if (menuItemElement.hasAttribute("parent")) {
                    int parentKey = Integer.valueOf(menuItemElement.getAttribute("parent"));
                    while (parentKey >= 0) {
                        // get the parent:
                        doc = getMenuItem(user, parentKey, false, false, false);

                        // move the child inside the parent:
                        rootElement = doc.getDocumentElement();
                        Element parentElement = (Element) rootElement.getFirstChild();
                        if (parentElement != null) {
                            Element menuItemsElement = XMLTool.createElement(doc, parentElement, "menuitems");
                            menuItemsElement.appendChild(doc.importNode(menuItemElement, true));
                            menuItemElement = parentElement;

                            if (menuItemElement.hasAttribute("parent")) {
                                parentKey = Integer.valueOf(menuItemElement.getAttribute("parent"));
                            } else {
                                parentKey = -1;
                            }
                        } else {
                            parentKey = -1;
                        }
                    }
                }
            }
        } else {
            buildMenuItemsXML(user, resultSet, doc, rootElement, -1, -1, complete, includePageConfig, true,
                    true, true);
        }
    } catch (SQLException sqle) {
        VerticalEngineLogger.error(this.getClass(), 30, "SQL error.", sqle);
    } finally {
        close(resultSet);
        close(preparedStmt);
        close(con);
    }

    return doc;

}

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;//w  w  w.  j av a 2 s  . co m
    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;
}

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

private Element getMenuData(Element rootElement, int menuId) {
    Document doc = rootElement.getOwnerDocument();
    Element menuElement = XMLTool.createElement(doc, rootElement, "menu");

    Connection con = null;/*from  ww w  .  j a v a 2 s .  com*/
    PreparedStatement preparedStmt = null;
    ResultSet result = null;
    try {
        con = getConnection();

        preparedStmt = con.prepareStatement(MENU_SELECT_BY_KEY);
        preparedStmt.setInt(1, menuId);
        result = preparedStmt.executeQuery();
        if (result.next()) {
            int languageKey = result.getInt("men_lan_lKey");

            menuElement.setAttribute("key", String.valueOf(menuId));
            menuElement.setAttribute("languagekey", String.valueOf(languageKey));
            menuElement.setAttribute("languagecode", result.getString("lan_sCode"));
            menuElement.setAttribute("language", result.getString("lan_sDescription"));
            menuElement.setAttribute("runas", result.getString("men_usr_hRunAs"));

            String name = result.getString("men_sName");
            if (!result.wasNull()) {
                XMLTool.createElement(doc, menuElement, "name", name);
            } else {
                XMLTool.createElement(doc, menuElement, "name");
            }

            // firstpage:
            int frontpageKey = result.getInt("men_mei_firstPage");
            if (!result.wasNull()) {
                XMLTool.createElement(doc, menuElement, "firstpage").setAttribute("key",
                        String.valueOf(frontpageKey));
            } else {
                XMLTool.createElement(doc, menuElement, "firstpage");
            }

            // loginpage:
            int loginpageKey = result.getInt("men_mei_loginPage");
            if (!result.wasNull()) {
                XMLTool.createElement(doc, menuElement, "loginpage").setAttribute("key",
                        String.valueOf(loginpageKey));
            } else {
                XMLTool.createElement(doc, menuElement, "loginpage");
            }

            // errorpage:
            int errorpageKey = result.getInt("men_mei_errorPage");
            if (!result.wasNull()) {
                XMLTool.createElement(doc, menuElement, "errorpage").setAttribute("key",
                        String.valueOf(errorpageKey));
            } else {
                XMLTool.createElement(doc, menuElement, "errorpage");
            }

            // Page template:
            int defaultPagetemplate = result.getInt("men_pat_lKey");
            if (!result.wasNull()) {
                XMLTool.createElement(doc, menuElement, "defaultpagetemplate").setAttribute("pagetemplatekey",
                        String.valueOf(defaultPagetemplate));
            }

            // XML data:
            InputStream is = result.getBinaryStream("men_xmlData");
            if (!result.wasNull()) {
                Document tmpDoc = XMLTool.domparse(is);
                menuElement.appendChild(doc.importNode(tmpDoc.getDocumentElement(), true));
            }

            // Menu details.
            Element detailsElement = XMLTool.createElement(doc, menuElement, "details");

            //Statistics URL:
            String statisticsURL = result.getString(db.tMenu.men_sStatisticsURL.getName());
            if (!result.wasNull()) {
                XMLTool.createElement(doc, detailsElement, db.tMenu.men_sStatisticsURL.getXPath())
                        .setTextContent(statisticsURL);
            } else {
                XMLTool.createElement(doc, detailsElement, db.tMenu.men_sStatisticsURL.getXPath());
            }

            /* Missing fields. New fields are only implemented in SiteXmlCreator. */
        } else {
            String message = "No menu found for menu ID: %0";
            VerticalEngineLogger.error(this.getClass(), 10, message, menuId, null);
        }
    } catch (SQLException sqle) {
        VerticalEngineLogger.error(this.getClass(), 20, "A database error occurred: %t", sqle);
    } finally {
        close(result);
        close(preparedStmt);
        close(con);
    }

    return menuElement;
}

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

private Element buildMenuItemXML(Document doc, Element menuItemsElement, ResultSet result, int tagItem,
        boolean complete, boolean includePageConfig, boolean includeHidden, boolean includeTypeSpecificXML,
        boolean tagItems, int levels) throws SQLException {

    int key = result.getInt("mei_lKey");

    // check if menuitem is hidden:
    int hiddenInt = result.getInt("mei_bHidden");
    boolean hidden = result.wasNull() || hiddenInt == 1;

    // propagate upwards in the XML and tag parents:
    if (key == tagItem) {
        tagParents(menuItemsElement);/*from  w  w w.j  ava  2 s .c  o m*/
    }

    // simply return null if we don't want to include
    // hidden menuitems:
    if ((!includeHidden && hidden) || levels == 0) {
        // special case: if includeHidden is false, we must
        // check to see if the menuitem that is to be tagged
        // is a child of this menuitem
        if (tagItems) {
            if (tagItem != -1 && tagItem != key) {
                if (hasChild(key, tagItem, true)) {
                    tagParents(menuItemsElement);

                    if (hidden) {
                        Node n = menuItemsElement.getParentNode();
                        if (n.getNodeType() == Node.ELEMENT_NODE) {
                            ((Element) n).setAttribute("active", "true");
                        }
                    }
                }
            } else if (tagItem == key) {
                Node n = menuItemsElement.getParentNode();
                if (n.getNodeType() == Node.ELEMENT_NODE) {
                    ((Element) n).setAttribute("active", "true");
                }
            }
        }
        return null;
    }

    ////// + build xml for menu item
    Element menuItemElement = XMLTool.createElement(doc, menuItemsElement, "menuitem");
    menuItemElement.setAttribute("key", String.valueOf(key));

    // tag the menuitem?
    if (tagItem == key && !hidden) {
        menuItemElement.setAttribute("path", "true");
        menuItemElement.setAttribute("active", "true");
    }

    // attribute: owner
    menuItemElement.setAttribute("owner", result.getString("mei_usr_hOwner"));

    // attribute: modifier
    menuItemElement.setAttribute("modifier", result.getString("mei_usr_hModifier"));

    // attribute: order
    menuItemElement.setAttribute("order", result.getString("mei_lOrder"));

    // Add timestamp attribute
    menuItemElement.setAttribute("timestamp",
            CalendarUtil.formatTimestamp(result.getTimestamp("mei_dteTimestamp")));

    // attribute: language
    int lanKey = result.getInt("lan_lKey");
    String lanCode = result.getString("lan_sCode");
    String lanDesc = result.getString("lan_sDescription");
    if (lanDesc != null) {
        menuItemElement.setAttribute("languagekey", String.valueOf(lanKey));
        menuItemElement.setAttribute("languagecode", lanCode);
        menuItemElement.setAttribute("language", lanDesc);
    }

    // attribute menykey:
    int menuKey = result.getInt("mei_men_lkey");
    if (!result.wasNull()) {
        menuItemElement.setAttribute("menukey", String.valueOf(menuKey));
    }

    // attribute parent:
    int parentKey = result.getInt("mei_lParent");
    if (!result.wasNull()) {
        menuItemElement.setAttribute("parent", String.valueOf(parentKey));
    }

    // element: name
    XMLTool.createElement(doc, menuItemElement, "name", result.getString("mei_sName"));

    // display-name
    XMLTool.createElement(doc, menuItemElement, ELEMENT_NAME_DISPLAY_NAME,
            result.getString(COLUMN_NAME_DISPLAY_NAME));

    // short-name:
    String tmp = result.getString(COLUMN_NAME_ALTERNATIVE_NAME);
    if (!result.wasNull() && tmp.length() > 0) {
        XMLTool.createElement(doc, menuItemElement, ELEMENT_NAME_MENU_NAME, tmp);
    }

    menuItemElement.setAttribute("runAs", RunAsType.get(result.getInt("mei_lRunAs")).toString());

    // description:
    String desc = result.getString("mei_sDescription");
    if (!result.wasNull()) {
        XMLTool.createElement(doc, menuItemElement, "description", desc);
    } else {
        XMLTool.createElement(doc, menuItemElement, "description");
    }

    // keywords:
    String keywords = result.getString("mei_sKeywords");
    if (!result.wasNull()) {
        XMLTool.createElement(doc, menuItemElement, "keywords", keywords);
    } else {
        XMLTool.createElement(doc, menuItemElement, "keywords");
    }

    // visibility:
    if (!hidden) {
        menuItemElement.setAttribute("visible", "yes");
    } else {
        menuItemElement.setAttribute("visible", "no");
    }

    // contentkey
    int contentKey = getMenuItemContentKey(key);
    if (contentKey != -1) {
        menuItemElement.setAttribute("contentkey", String.valueOf(contentKey));
    }

    // element menuitemdata:
    InputStream is = result.getBinaryStream("mei_xmlData");
    Element documentElem;
    if (result.wasNull()) {
        XMLTool.createElement(doc, menuItemElement, "parameters");
        documentElem = XMLTool.createElement(doc, "document");
        if (complete) {
            XMLTool.createElement(doc, menuItemElement, "data");
        }
    } else {
        Document dataDoc = XMLTool.domparse(is);
        Element dataElem = (Element) doc.importNode(dataDoc.getDocumentElement(), true);
        Element parametersElem = XMLTool.getElement(dataElem, "parameters");
        dataElem.removeChild(parametersElem);
        menuItemElement.appendChild(parametersElem);
        if (complete) {
            documentElem = XMLTool.getElement(dataElem, "document");
            if (documentElem != null) {
                dataElem.removeChild(documentElem);
                menuItemElement.appendChild(documentElem);
            }
            menuItemElement.appendChild(dataElem);
        } else {
            documentElem = XMLTool.createElement(doc, "document");
        }
    }

    // attribute: menu item type
    MenuItemType menuItemType = MenuItemType.get(result.getInt("mei_mid_lKey"));
    menuItemElement.setAttribute("type", menuItemType.getName());

    if (includeTypeSpecificXML) {
        // build type-specific XML:
        switch (menuItemType) {
        case PAGE:
            buildPageTypeXML(result, doc, menuItemElement, complete && includePageConfig);
            break;

        case URL:
            buildURLTypeXML(result, doc, menuItemElement);
            break;

        case CONTENT:
            MenuItemKey sectionKey = getSectionHandler().getSectionKeyByMenuItem(new MenuItemKey(key));
            if (sectionKey != null) {
                buildSectionTypeXML(key, menuItemElement);
            }
            buildDocumentTypeXML(menuItemElement, documentElem);
            buildPageTypeXML(result, doc, menuItemElement, complete && includePageConfig);
            break;

        case LABEL:
            break;
        case SECTION:
            buildSectionTypeXML(key, menuItemElement);
            break;
        case SHORTCUT:
            buildShortcutTypeXML(key, menuItemElement);
            break;
        }
    }

    return menuItemElement;
}

From source file:com.enonic.vertical.adminweb.handlers.xmlbuilders.SimpleContentXMLBuilder.java

private void createNormalBlock(ExtendedMap formItems, Document doc, Element contentdata, NodeList inputElements)
        throws ParseException {

    ArrayList<Integer> keepBinaries;
    if (formItems.containsKey("__keepbinaries")) {
        keepBinaries = (ArrayList<Integer>) formItems.get("__keepbinaries");
    } else {/* w  w  w .j  a  va 2  s . c  o  m*/
        keepBinaries = new ArrayList<Integer>();
    }

    for (int i = 0; i < inputElements.getLength(); ++i) {
        Element inputElem = (Element) inputElements.item(i);
        String name = inputElem.getAttribute("name");

        String xpath = XMLTool.getElementText(inputElem, "xpath");
        String type = inputElem.getAttribute("type");

        if (xpath != null) {
            // First, create the elements in the xpath:

            Element tmpElem = createXPathElements(contentdata, xpath, 1);

            if (tmpElem == null) {
                VerticalAdminLogger.errorAdmin(SimpleContentXMLBuilder.class, 3,
                        "Incorrect xpath specification : " + xpath, null);
            }

            // Then store the data.
            // Some types may need to be treated separatly.

            // date
            if (type.equals("date")) {
                String date = formItems.getString("date" + name, null);
                if (date != null) {
                    Date tempDate = DateUtil.parseDate(date);
                    XMLTool.createTextNode(doc, tmpElem, DateUtil.formatISODate(tempDate));
                }
            }

            // images
            else if (type.equals("images")) {
                if (AdminHandlerBaseServlet.isArrayFormItem(formItems, name)) {
                    String[] images = (String[]) formItems.get(name);
                    String[] text = (String[]) formItems.get(name + "text");
                    for (int k = 1; k < images.length; k++) {
                        if (images[k] == null || images[k].length() == 0) {
                            continue;
                        }
                        Element image = XMLTool.createElement(doc, tmpElem, "image");
                        image.setAttribute("key", images[k]);
                        XMLTool.createElement(doc, image, "text", text[k]);
                    }
                }
            }

            // image
            else if (type.equals("image") && formItems.containsKey(name)) {
                String image = formItems.getString(name);
                tmpElem.setAttribute("key", image);
                if ("true".equals(inputElem.getAttribute("imagetext"))) {
                    String text = formItems.getString(name + "text");
                    XMLTool.createElement(doc, tmpElem, "text", text);
                }
            }

            // related content
            else if (type.equals("relatedcontent")) {
                if (AdminHandlerBaseServlet.isArrayFormItem(formItems, name)) {
                    String[] content = (String[]) formItems.get(name);
                    for (String aContent : content) {
                        if (aContent == null || aContent.length() == 0) {
                            continue;
                        }
                        Element contentElem = XMLTool.createElement(doc, tmpElem, "content");
                        contentElem.setAttribute("key", aContent);
                    }
                } else if (formItems.containsKey(name)) {
                    if (!"false".equals(inputElem.getAttribute("multiple"))) {
                        String content = formItems.getString(name);
                        Element contentElem = XMLTool.createElement(doc, tmpElem, "content");
                        contentElem.setAttribute("key", content);
                    } else {
                        String content = formItems.getString(name);
                        tmpElem.setAttribute("key", content);
                    }
                }

            }

            // files
            else if (type.equals("files")) {
                if (AdminHandlerBaseServlet.isArrayFormItem(formItems, name)) {
                    //logCategory.debug("multiple files");
                    String[] files = (String[]) formItems.get(name);
                    for (String file1 : files) {
                        if (file1 != null && file1.length() > 0) {
                            Element file = XMLTool.createElement(doc, tmpElem, "file");
                            file.setAttribute("key", file1);
                        }
                    }
                } else {
                    //logCategory.debug("single file");
                    String filekey = formItems.getString(name, null);
                    if (filekey != null && filekey.length() > 0) {
                        Element file = XMLTool.createElement(doc, tmpElem, "file");
                        file.setAttribute("key", filekey);
                    }
                }
            }

            // file
            else if (type.equals("file")) {
                //logCategory.debug("single file");
                String filekey = formItems.getString(name, null);
                if (filekey != null && filekey.length() > 0) {
                    Element file = XMLTool.createElement(doc, tmpElem, "file");
                    file.setAttribute("key", filekey);
                }
            }

            // uploaded binary file
            else if (type.equals("uploadfile")) {
                String fileName = formItems.getString("filename_" + name, "");
                int oldKey = -1;

                // If file was already present (has binary key)
                if (formItems.containsKey(name)) {
                    oldKey = formItems.getInt(name);
                }

                boolean isReplaced = false;

                BinaryData[] binaries = (BinaryData[]) formItems.get("__binaries", null);
                if (binaries != null && binaries.length > 0) {
                    int index = -1;
                    for (int counter = 0; counter < binaries.length; counter++) {
                        if (fileName.equals(binaries[counter].fileName)) {
                            index = counter;
                            break;
                        }
                    }
                    if (index != -1) {
                        Element binaryElement = XMLTool.createElement(doc, tmpElem, "binarydata");
                        binaryElement.setAttribute("key", "%" + index);

                        if (oldKey != -1) {
                            isReplaced = true;
                        }
                    }
                }

                if (oldKey != -1 && !isReplaced) {
                    Element binaryElement = XMLTool.createElement(doc, tmpElem, "binarydata");
                    binaryElement.setAttribute("key", String.valueOf(oldKey));
                    keepBinaries.add(oldKey);
                    formItems.put("__keepbinaries", keepBinaries);
                }
            }

            // checkbox
            else if (type.equals("checkbox")) {
                if ("true".equals(formItems.getString(name, null))) {
                    XMLTool.createTextNode(doc, tmpElem, "true");
                } else {
                    XMLTool.createTextNode(doc, tmpElem, "false");
                }
            }

            // multiple choice
            else if (type.equals("multiplechoice")) {
                // <text>
                if (formItems.containsKey(name)) {
                    XMLTool.createElement(doc, tmpElem, "text", formItems.getString(name));

                    // <alternative>'s
                    String[] alternatives = formItems.getStringArray(name + "_alternative");
                    String[] corrects = formItems.getStringArray(name + "_checkbox_values");
                    for (int j = 0; j < alternatives.length; j++) {
                        Element alternativeElem = XMLTool.createElement(doc, tmpElem, "alternative",
                                alternatives[j]);
                        boolean correct = ("true".equals(corrects[j]));
                        alternativeElem.setAttribute("correct", String.valueOf(correct));
                    }
                }
            }

            else if (type.equals("xml")) {
                // xml
                if (formItems.containsKey(name)) {
                    String value = formItems.getString(name, null);
                    if (value != null) {
                        Document xmlDoc = XMLTool.domparse(value);
                        tmpElem.appendChild(doc.importNode(xmlDoc.getDocumentElement(), true));
                    }
                }
            }

            //JIRA VS-2461 Hack to make radiobuttons work in groups
            // radiobutton
            else if (type.equals("radiobutton")) {
                String[] radiobuttonName = getFormItemsByRegexp("rb:[0-9].*:" + name, formItems);
                if (radiobuttonName.length == 1) {
                    if (formItems.getString(radiobuttonName[0]) != null
                            && !formItems.getString(radiobuttonName[0]).equalsIgnoreCase(radiobuttonName[0])) {
                        XMLTool.createTextNode(doc, tmpElem, formItems.getString(radiobuttonName[0]));
                    }

                } else {
                    throw new IllegalArgumentException("Ambigous input for radiobutton " + name);
                }

            }

            // normal text
            else {
                if (formItems.containsKey(name)) {
                    String value = formItems.getString(name, null);
                    if (type.equals("htmlarea") || type.equals("simplehtmlarea")) {
                        XMLTool.createXHTMLNodes(doc, tmpElem, value, true);
                    } else {
                        XMLTool.createTextNode(doc, tmpElem, value);
                    }
                }
            }
        }
    }
}