Example usage for org.w3c.dom Document replaceChild

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

Introduction

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

Prototype

public Node replaceChild(Node newChild, Node oldChild) throws DOMException;

Source Link

Document

Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.

Usage

From source file:de.bund.bfr.knime.pmm.common.chart.ChartUtilities.java

public static SvgImageContent convertToSVGImageContent(JFreeChart chart, int width, int height) {
    SVGDOMImplementation domImpl = new SVGDOMImplementation();
    Document document = domImpl.createDocument(null, "svg", null);
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

    svgGenerator.setSVGCanvasSize(new Dimension(width, height));

    if (chart != null) {
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, width, height));
    }//from ww w . j  a  v a2  s .  c o  m

    svgGenerator.finalize();
    document.replaceChild(svgGenerator.getRoot(), document.getDocumentElement());

    return new SvgImageContent((SVGDocument) document, true);
}

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

public void handlerReport(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems, String subOp) throws VerticalAdminException {

    User user = securityService.getLoggedInAdminConsoleUser();
    ExtendedMap parameters = formItems;/* w  ww . ja  v a2s . c  o m*/

    if ("form".equals(subOp)) {
        int unitKey = formItems.getInt("selectedunitkey", -1);
        int categoryKey = formItems.getInt("cat");

        String superCategoryXML = admin.getSuperCategoryNames(categoryKey, false, true);
        Document doc = XMLTool.domparse(superCategoryXML);

        addCommonParameters(admin, user, request, parameters, unitKey, -1);

        transformXML(request, response, doc, "report_form.xsl", parameters);
    } else if ("create".equals(subOp)) {
        ResourceKey stylesheetKey = new ResourceKey(formItems.getString("stylesheetkey"));
        ResourceFile res = resourceService.getResourceFile(stylesheetKey);
        if (res == null) {
            throw new StylesheetNotFoundException(stylesheetKey);
        }
        Document xslDoc;
        try {
            xslDoc = res.getDataAsXml().getAsDOMDocument();
        } catch (XMLException e) {
            throw new InvalidStylesheetException(stylesheetKey, e);
        }
        DOMSource xslSource = new DOMSource(xslDoc);

        int cat = formItems.getInt("cat");
        String reportXML;
        String searchType = formItems.getString("searchtype");
        if ("simple".equals(searchType)) {
            reportXML = new SearchUtility(userDao, groupDao, securityService, contentService).simpleReport(user,
                    formItems, cat);
        } else {
            String[] contentTypeStringArray = formItems.getStringArray("contenttypestring");
            int[] contentTypes = resolveContentTypes(contentTypeStringArray);
            StringBuffer contentTypesString = createContentTypesString(contentTypes);
            reportXML = new SearchUtility(userDao, groupDao, securityService, contentService)
                    .advancedReport(user, formItems, contentTypes);
        }
        Document reportDoc = XMLTool.domparse(reportXML);
        Element contentsElem = reportDoc.getDocumentElement();
        String datasourcesDefaultResultElementName = verticalProperties.getDatasourceDefaultResultRootElement();
        Element verticaldataElem = XMLTool.createElement(reportDoc, datasourcesDefaultResultElementName);
        reportDoc.replaceChild(verticaldataElem, contentsElem);
        verticaldataElem.appendChild(contentsElem);
        DOMSource reportSource = new DOMSource(reportDoc);

        new XsltProcessorHelper().stylesheet(xslSource, getStylesheetURIResolver(admin)).params(parameters)
                .input(reportSource).process(response);
    } else {
        String message = "Unknown sub-operation for operation report: %0";
        VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, subOp, null);
    }
}

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

public void handlerCopy(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems, User user, int key)
        throws VerticalAdminException, VerticalEngineException {

    String xmlCO = admin.getContentObject(Integer.parseInt(request.getParameter("key")));
    Document doc = XMLTool.domparse(xmlCO);

    Element nameElem = (Element) XMLTool.selectNode(doc, "/contentobjects/contentobject/name");
    Node[] nameArray = XMLTool.filterNodes(nameElem.getChildNodes(), Node.TEXT_NODE);

    Text name = (Text) nameArray[0];
    AdminConsoleTranslationService languageMap = AdminConsoleTranslationService.getInstance();
    Map translationMap = languageMap.getTranslationMap(user.getSelectedLanguageCode());
    name.setData(name.getData() + " (" + translationMap.get("%txtCopy%") + ")");

    Element coElem = (Element) XMLTool.selectNode(doc, "/contentobjects/contentobject");
    coElem.removeAttribute("key");

    Element docRoot = doc.getDocumentElement();
    doc.replaceChild(coElem, docRoot);

    key = admin.createContentObject(user, XMLTool.documentToString(doc));

    redirectClientToReferer(request, response);
}

From source file:org.pegadi.server.article.ArticleServerImpl.java

/**
 * Change the main tag name of an article. Used when the article type changes.
 *
 * @param art The article.//from w w w  .ja v  a2 s .co m
 * @param ID  The ID of the new article type.
 */
protected void changeArticleType(Article art, int ID) {
    Map<String, Object> map = template.queryForMap("SELECT tagname FROM ArticleType WHERE ID=:id",
            Collections.singletonMap("id", ID));
    String tag = (String) map.get("tagname");

    Document doc = art.getDocument();
    if (doc == null) {
        art.parseText();
        doc = art.getDocument();
    }

    if (doc == null) {
        log.error("changeArticleType: Can't get document for article, article is NOT changed.");
        return;
    }

    Element root = doc.getDocumentElement();
    log.info("Root before: " + doc.getDocumentElement().toString());

    Element replace = doc.createElement(tag);

    NamedNodeMap att = root.getAttributes();

    for (int i = 0; i < att.getLength(); i++) {
        Node n = att.item(i);
        if (n instanceof Attr) {
            replace.setAttribute(((Attr) n).getName(), ((Attr) n).getValue());
        }
    }

    NodeList nl = root.getChildNodes();
    log.info("changeArticleType: Root node has {} children.", nl.getLength());
    for (int i = 0; i < nl.getLength(); i++) {
        Node clone = nl.item(i).cloneNode(true);
        log.info("Adding node {} to replace", (i + 1));
        replace.appendChild(clone);
    }

    log.info("Replacement node: {}", replace.toString());

    doc.replaceChild(replace, root);

    log.info("Root after: {}", doc.getDocumentElement().toString());

    if (!art.serialize()) {
        log.error("changeArticleType: Can't serialize the changed XML.");
    }
}

From source file:com.enonic.cms.web.portal.services.ContentServicesBase.java

protected String buildXML(UserServicesService userServices, User user, ExtendedMap formItems, SiteKey siteKey,
        int contentTypeKey, String contentTitle, boolean skipEmptyElements) {

    Document doc;
    Element contentElem;//w ww. j  ava 2  s .c o m
    Element contentdataElem;
    int contentKey = formItems.getInt("key", -1);

    if (contentKey == -1) {
        contentKey = formItems.getInt("contentkey", -1);
    }

    if (contentKey == -1) {
        doc = XMLTool.createDocument("content");
        contentElem = doc.getDocumentElement();

        int categoryKey = formItems.getInt("categorykey");
        CategoryEntity categoryEntity = categoryDao.findByKey(new CategoryKey(categoryKey));

        if (categoryEntity.getAutoMakeAvailableAsBoolean()) {
            contentElem.setAttribute("publishfrom", CalendarUtil.formatCurrentDate());
            contentElem.setAttribute("status", "2");
        } else {
            // new content is created as draft
            contentElem.setAttribute("status", "0");
            contentElem.removeAttribute("publishfrom");
            contentElem.removeAttribute("publishto");
        }

        contentElem.setAttribute("contenttypekey", String.valueOf(contentTypeKey));
        contentElem.setAttribute("priority", "0");

        // category:
        Element category = XMLTool.createElement(doc, contentElem, "categoryname");
        category.setAttribute("key", String.valueOf(categoryKey));

        // content title
        XMLTool.createElement(doc, contentElem, "title", contentTitle);

        // content data
        contentdataElem = XMLTool.createElement(doc, contentElem, "contentdata");
    } else {
        doc = userServices.getContent(user, contentKey, false, 0, 0, 0).getAsDOMDocument();
        Element rootElem = doc.getDocumentElement();
        contentElem = XMLTool.getFirstElement(rootElem);
        rootElem.removeChild(contentElem);
        doc.replaceChild(contentElem, rootElem);

        // modifier/@key
        Element modifierElem = XMLTool.getElement(contentElem, "modifier");
        XMLTool.removeChildFromParent(contentElem, modifierElem);
        modifierElem = XMLTool.createElement(contentElem, "modifier");
        modifierElem.setAttribute("key", String.valueOf(user.getKey()));

        // version/@key
        int versionKey = userServices.getCurrentVersionKey(contentKey);
        contentElem.setAttribute("versionkey", String.valueOf(versionKey));

        // content title
        Element title = XMLTool.getElement(contentElem, "title");
        XMLTool.removeChildNodes(title);
        XMLTool.createTextNode(doc, title, contentTitle);

        // content data
        contentdataElem = XMLTool.getElement(contentElem, "contentdata");
        XMLTool.removeChildNodes(contentdataElem, true);
    }

    buildContentTypeXML(userServices, contentdataElem, formItems, skipEmptyElements);

    return XMLTool.documentToString(doc);
}

From source file:com.enonic.vertical.userservices.ContentHandlerBaseController.java

protected String buildXML(UserServicesService userServices, User user, ExtendedMap formItems, SiteKey siteKey,
        int contentTypeKey, String contentTitle, boolean skipEmptyElements)
        throws VerticalUserServicesException, RemoteException {

    Document doc;
    Element contentElem;/*from  w  ww  .ja  v  a 2s  .  c  o m*/
    Element contentdataElem;
    int contentKey = formItems.getInt("key", -1);

    if (contentKey == -1) {
        contentKey = formItems.getInt("contentkey", -1);
    }

    if (contentKey == -1) {
        doc = XMLTool.createDocument("content");
        contentElem = doc.getDocumentElement();

        int categoryKey = formItems.getInt("categorykey");
        CategoryEntity categoryEntity = categoryDao.findByKey(new CategoryKey(categoryKey));

        if (categoryEntity.getAutoMakeAvailableAsBoolean()) {
            contentElem.setAttribute("publishfrom", CalendarUtil.formatCurrentDate());
            contentElem.setAttribute("status", "2");
        } else {
            // new content is created as draft
            contentElem.setAttribute("status", "0");
            contentElem.removeAttribute("publishfrom");
            contentElem.removeAttribute("publishto");
        }

        contentElem.setAttribute("contenttypekey", String.valueOf(contentTypeKey));
        contentElem.setAttribute("priority", "0");

        // category:
        Element category = XMLTool.createElement(doc, contentElem, "categoryname");
        category.setAttribute("key", String.valueOf(categoryKey));

        // content title
        XMLTool.createElement(doc, contentElem, "title", contentTitle);

        // content data
        contentdataElem = XMLTool.createElement(doc, contentElem, "contentdata");
    } else {
        doc = XMLTool.domparse(userServices.getContent(user, contentKey, false, 0, 0, 0));
        Element rootElem = doc.getDocumentElement();
        contentElem = XMLTool.getFirstElement(rootElem);
        rootElem.removeChild(contentElem);
        doc.replaceChild(contentElem, rootElem);

        // modifier/@key
        Element modifierElem = XMLTool.getElement(contentElem, "modifier");
        XMLTool.removeChildFromParent(contentElem, modifierElem);
        modifierElem = XMLTool.createElement(contentElem, "modifier");
        modifierElem.setAttribute("key", String.valueOf(user.getKey()));

        // version/@key
        int versionKey = userServices.getCurrentVersionKey(contentKey);
        contentElem.setAttribute("versionkey", String.valueOf(versionKey));

        // content title
        Element title = XMLTool.getElement(contentElem, "title");
        XMLTool.removeChildNodes(title);
        XMLTool.createTextNode(doc, title, contentTitle);

        // content data
        contentdataElem = XMLTool.getElement(contentElem, "contentdata");
        XMLTool.removeChildNodes(contentdataElem, true);
    }

    buildContentTypeXML(userServices, contentdataElem, formItems, skipEmptyElements);

    return XMLTool.documentToString(doc);
}

From source file:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java

protected final void addUserRightToDocument(AdminService admin, User user, Document doc, int categoryKey) {
    String xmlAccessRights = admin.getAccessRights(user, AccessRight.CATEGORY, categoryKey, true);
    Document docAccessRights = XMLTool.domparse(xmlAccessRights);
    Element userrightElem = XMLTool.getElement(docAccessRights.getDocumentElement(), "userright");
    if (userrightElem != null) {
        docAccessRights.replaceChild(userrightElem, docAccessRights.getDocumentElement());
        XMLTool.mergeDocuments(doc, docAccessRights, true);
    }/*from w  ww  .  j a v  a 2 s  .  co  m*/
}

From source file:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java

public void handlerReport(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems, String subOp) throws VerticalAdminException {

    try {/*from www.  ja  va  2s.  co m*/
        User user = securityService.getLoggedInAdminConsoleUser();
        ExtendedMap parameters = formItems;

        if ("form".equals(subOp)) {
            int unitKey = formItems.getInt("selectedunitkey", -1);
            int categoryKey = formItems.getInt("cat");
            int contentTypeKey = getContentTypeKey(formItems);

            String assignmentDueDate = formItems.getString("date_assignmentDueDate", "");
            String assignmentDueDateOp = formItems.getString("_assignmentDueDate.op", "");
            String assigneeUserKey = formItems.getString("_assignee", "");
            String assignerUserKey = formItems.getString("_assigner", "");

            String superCategoryXML = admin.getSuperCategoryNames(categoryKey, false, true);
            Document doc = XMLTool.domparse(superCategoryXML);

            addCommonParameters(admin, user, request, parameters, unitKey, -1);
            parameters.put("contenttypekey", String.valueOf(contentTypeKey));

            parameters.put("assignment.dueDate", assignmentDueDate);
            parameters.put("assignment.dueDate.op", assignmentDueDateOp);
            parameters.put("assignment.assigneeUserKey", assigneeUserKey);
            parameters.put("assignment.assignerUserKey", assignerUserKey);

            transformXML(request, response, doc, "report_form.xsl", parameters);
        } else if ("create".equals(subOp)) {
            ResourceKey stylesheetKey = new ResourceKey(formItems.getString("stylesheetkey"));
            ResourceFile res = resourceService.getResourceFile(stylesheetKey);
            if (res == null) {
                throw new StylesheetNotFoundException(stylesheetKey);
            }

            int cat = formItems.getInt("cat");
            String reportXML;
            String searchType = formItems.getString("searchtype");
            if ("simple".equals(searchType)) {
                reportXML = new SearchUtility(userDao, groupDao, securityService, contentService)
                        .simpleReport(user, formItems, cat);
            } else {
                // reportXML = SearchUtility.advancedReport( user, admin, formItems );
                String[] contentTypeStringArray = formItems.getStringArray("contenttypestring");
                int[] contentTypes = resolveContentTypes(contentTypeStringArray);

                String ownerGroupKey = formItems.getString("owner", "");
                if (!"".equals(ownerGroupKey)) {
                    User ownerUser = getUserFromUserGroupKey(ownerGroupKey);

                    addUserKeyToFormItems(formItems, "owner.key", ownerUser);
                }

                String modifierGroupKey = formItems.getString("modifier", "");
                if (!"".equals(modifierGroupKey)) {
                    User modifierUser = getUserFromUserGroupKey(modifierGroupKey);

                    addUserKeyToFormItems(formItems, "modifier.key", modifierUser);
                }
                reportXML = new SearchUtility(userDao, groupDao, securityService, contentService)
                        .advancedReport(user, formItems, contentTypes);
            }
            Document reportDoc = XMLTool.domparse(reportXML);
            Element contentsElem = reportDoc.getDocumentElement();
            String datasourcesDefaultResultElementName = verticalProperties
                    .getDatasourceDefaultResultRootElement();
            Element verticaldataElem = XMLTool.createElement(reportDoc, datasourcesDefaultResultElementName);
            reportDoc.replaceChild(verticaldataElem, contentsElem);
            verticaldataElem.appendChild(contentsElem);
            DOMSource reportSource = new DOMSource(reportDoc);

            XsltResource xslResource = new XsltResource(res.getDataAsXml().getAsString());
            XsltProcessorManager procManager = XsltProcessorManagerAccessor.getProcessorManager();
            XsltProcessor proc = procManager.createProcessor(xslResource, getStylesheetURIResolver(admin));
            proc.setParameter("datetoday", DateUtil.formatISODateTime(new Date()));

            response.setContentType(proc.getOutputMediaType() + "; charset=UTF-8");
            response.getWriter().write(proc.process(reportSource));
        } else {
            String message = "Unknown sub-operation for operation report: %t";
            VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, subOp, null);
        }
    } catch (XsltProcessorException e) {
        String message = "Failed to transmform XML document: %t";
        VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, e);
    } catch (IOException e) {
        String message = "Failed to transmform XML document: %t";
        VerticalAdminLogger.errorAdmin(this.getClass(), 0, message, e);
    }

}

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

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

    try {//from  w  w w.  j a  v a  2 s . c  om
        User user = securityService.getLoggedInAdminConsoleUser();
        boolean createPageTemplate;
        boolean updateStyleSheet = formItems.getBoolean("updatestylesheet", true);
        boolean updateCSS = formItems.getBoolean("updatecss", false);
        String xmlData;
        Document doc;
        String cssStylesheetKey = null;

        String datasourcesXML;

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

        ResourceKey stylesheetKey = null;
        ResourceFile stylesheet = null;
        ResourceKey cssKey = null;
        boolean stylesheetValid = false;
        String cssKeyParam = request.getParameter("selectedcsskey");
        if (cssKeyParam != null && !"".equals(cssKeyParam)) {
            cssKey = new ResourceKey(cssKeyParam);
        }
        if (request.getParameter("selstylesheetkey") != null
                && request.getParameter("selstylesheetkey").length() > 0) {
            stylesheetKey = new ResourceKey(request.getParameter("selstylesheetkey"));
            formItems.putString("stylesheetkey", stylesheetKey.toString());
        }

        int key = formItems.getInt("key", -1);

        // If we have not selected a stylesheet yet
        if (stylesheetKey == null && cssKey == null && key == -1) {

            createPageTemplate = true;

            doc = XMLTool.createDocument("pagetemplates");
            Document dsDoc = XMLTool.createDocument("datasources");
            datasourcesXML = XMLTool.documentToString(dsDoc);
        } else {
            createPageTemplate = (key == -1);
            int pageTemplateKey;

            if (stylesheetKey == null && cssKey == null) // createPageTemplate = false
            {
                //   If we are editing an existing template
                pageTemplateKey = Integer.parseInt(request.getParameter("key"));
                xmlData = admin.getPageTemplate(pageTemplateKey);
                doc = XMLTool.domparse(xmlData);
                Element pagetemplateElem = XMLTool.getElement(doc.getDocumentElement(), "pagetemplate");
                Element stylesheetElem = XMLTool.getElement(pagetemplateElem, "stylesheet");
                stylesheetKey = new ResourceKey(stylesheetElem.getAttribute("stylesheetkey"));
            } else {
                // If we are making a new template
                doc = buildPageTemplateXML(formItems, key == -1);
                Element oldRoot = doc.getDocumentElement();
                String keyStr = oldRoot.getAttribute("key");
                if (keyStr != null && keyStr.length() > 0) {
                    pageTemplateKey = Integer.parseInt(keyStr);
                } else {
                    pageTemplateKey = -1;
                }
                Element newRoot = XMLTool.createElement(doc, "pagetemplates");
                doc.replaceChild(newRoot, oldRoot);
                newRoot.appendChild(oldRoot);
                updateStyleSheet = stylesheetKey != null;
                if (!updateStyleSheet) {
                    Element elem = XMLTool.getElement(oldRoot, "stylesheet");
                    String styleSheetKeyStr = elem.getAttribute("stylesheetkey");
                    if (styleSheetKeyStr.length() > 0) {
                        stylesheetKey = new ResourceKey(styleSheetKeyStr);
                    }
                }
            }

            Element cssElem = (Element) XMLTool.selectNode(doc, "/pagetemplates/pagetemplate/css");
            if (cssElem != null) {
                if (updateCSS && cssKey == null) {
                    cssElem.getParentNode().removeChild(cssElem);
                } else {
                    cssStylesheetKey = cssElem.getAttribute("stylesheetkey");
                }
            }

            Element ptdElem = (Element) XMLTool.selectNode(doc, "/pagetemplates/pagetemplate/pagetemplatedata");
            Element dselem = XMLTool.getElement(ptdElem, "datasources");
            if (dselem != null) {
                Document dsDoc = XMLTool.createDocument();
                dsDoc.appendChild(dsDoc.importNode(dselem, true));
                datasourcesXML = XMLTool.documentToString(dsDoc);
            } else {
                Document dsDoc = XMLTool.createDocument("datasources");
                datasourcesXML = XMLTool.documentToString(dsDoc);
            }

            if (!updateStyleSheet) {
                // Insert valuename attributes all parameters
                Element[] pagetemplateparamElems = XMLTool.getElements(ptdElem, "pagetemplateparameter");
                for (Element pagetemplateparamElem : pagetemplateparamElems) {
                    String keyStr = pagetemplateparamElem.getAttribute("value");
                    if (keyStr != null && keyStr.length() > 0) {
                        String type = pagetemplateparamElem.getAttribute("type");
                        if ("category".equals(type)) {
                            int categoryKey = Integer.parseInt(keyStr);
                            String name = admin.getCategoryName(categoryKey);
                            pagetemplateparamElem.setAttribute("valuename", name);
                        } else if ("page".equals(type)) {
                            int menuItemKey = Integer.parseInt(keyStr);
                            String name = admin.getMenuItemName(menuItemKey);
                            pagetemplateparamElem.setAttribute("valuename", name);
                        } else if ("resource".equals(type)) {
                            pagetemplateparamElem.setAttribute("valuename", keyStr);
                        }
                    }
                }
            }

            String menuItemsXML = admin.getMenuItemsByPageTemplates(user, new int[] { pageTemplateKey });
            Document menuItemsDoc = XMLTool.domparse(menuItemsXML);
            XMLTool.mergeDocuments(doc, menuItemsDoc, true);
        }

        if (stylesheetKey != null && ((createPageTemplate && cssKey == null) || updateStyleSheet)) {

            Map<String, Element> elemMap = new HashMap<String, Element>();
            Element root = doc.getDocumentElement();
            if (updateStyleSheet) {
                // Remove all parameters from xml
                root = XMLTool.getElement(root, "pagetemplate");
                Element pageTemplateParamterRootElement = XMLTool.getElement(root, "pagetemplateparameters");
                Element[] pageTemplateParameterElems = XMLTool.getElements(pageTemplateParamterRootElement,
                        "pagetemplateparameter");
                for (Element elem : pageTemplateParameterElems) {
                    String name = XMLTool.getElementText(XMLTool.getElement(elem, "name"));
                    elemMap.put(name, elem);
                }
                root.removeChild(pageTemplateParamterRootElement);
                pageTemplateParamterRootElement = XMLTool.getElement(root, "pagetemplatedata");
                pageTemplateParameterElems = XMLTool.getElements(pageTemplateParamterRootElement,
                        "pagetemplateparameter");
                for (Element elem1 : pageTemplateParameterElems) {
                    String name = elem1.getAttribute("name");
                    elemMap.put(name, elem1);
                    pageTemplateParamterRootElement.removeChild(elem1);
                }
            }
            Element stylesheetParams = XMLTool.createElement(doc, root, "pagetemplateparameters");

            Element pagetemplatedataElem = XMLTool.getElement(root, "pagetemplatedata");
            if (pagetemplatedataElem == null) {
                pagetemplatedataElem = XMLTool.createElement(doc, root, "pagetemplatedata");
            }

            stylesheet = resourceService.getResourceFile(stylesheetKey);
            if (stylesheet != null) {
                Document stylesheetDoc = null;
                try {
                    stylesheetDoc = stylesheet.getDataAsXml().getAsDOMDocument();
                    stylesheetValid = true;
                } catch (XMLException e) {
                }
                if (stylesheetDoc != null) {
                    Element[] paramElems = XMLTool.getElements(stylesheetDoc.getDocumentElement(), "xsl:param");
                    for (Element paramElem : paramElems) {
                        Element typeElem = XMLTool.getElement(paramElem, "type");
                        Element tempElem;
                        String name = paramElem.getAttribute("name");
                        if (typeElem != null) {
                            String type = XMLTool.getElementText(typeElem);
                            if ("object".equals(type) || "region".equals(type)) {
                                Element elem = elemMap.get(name);
                                if (elem != null && elem.getAttribute("type").length() == 0) {
                                    stylesheetParams.appendChild(elem);
                                } else {
                                    tempElem = XMLTool.createElement(doc, stylesheetParams,
                                            "pagetemplateparameter");
                                    XMLTool.createElement(doc, tempElem, "name", name);
                                }
                            } else {
                                if (elemMap.containsKey(name)) {
                                    Element elem = elemMap.get(name);
                                    String elemType = elem.getAttribute("type");
                                    if (elemType.length() == 0) {
                                        elem.setAttribute("name", name);
                                        XMLTool.removeChildNodes(elem, true);
                                    }
                                    elem.setAttribute("type", type);
                                    pagetemplatedataElem.appendChild(elem);
                                } else {
                                    tempElem = XMLTool.createElement(doc, pagetemplatedataElem,
                                            "pagetemplateparameter");
                                    tempElem.setAttribute("name", name);
                                    tempElem.setAttribute("type", type);
                                }
                            }
                        } else {
                            // Alle vanlige parametere, spesifisert som as="xs:string", e.l. i XSL'en.
                            if (elemMap.containsKey(name)) {
                                Element elem = elemMap.get(name);
                                String type = elem.getAttribute("type");
                                if (type.length() == 0) {
                                    elem.setAttribute("name", name);
                                    XMLTool.removeChildNodes(elem, true);
                                } else {
                                    elem.removeAttribute("type");
                                    elem.removeAttribute("valuename");
                                }
                                pagetemplatedataElem.appendChild(elem);
                            } else {
                                tempElem = XMLTool.createElement(doc, pagetemplatedataElem,
                                        "pagetemplateparameter");
                                tempElem.setAttribute("name", name);
                            }
                        }
                    }
                }
            }
        }

        if (stylesheet == null && stylesheetKey != null) {
            stylesheet = resourceService.getResourceFile(stylesheetKey);
        }

        if (stylesheet != null) {
            Document stylesheetDoc = null;
            try {
                stylesheetDoc = stylesheet.getDataAsXml().getAsDOMDocument();
                stylesheetValid = true;
            } catch (XMLException e) {
            }
            if (stylesheetDoc != null) {
                Element tmpElem = XMLTool.createElement(doc.getDocumentElement(), "resource");
                tmpElem.appendChild(doc.importNode(stylesheetDoc.getDocumentElement(), true));
            }
        }

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

        DOMSource xmlSource = new DOMSource(doc);

        Source xslSource = AdminStore.getStylesheet(session, "pagetemplate_form.xsl");

        HashMap<String, Object> parameters = new HashMap<String, Object>();
        addCommonParameters(admin, user, request, parameters, -1, menuKey);

        if (cssStylesheetKey != null) {
            parameters.put("cssStylesheetKey", cssStylesheetKey);
            parameters.put("cssStylesheetExist",
                    resourceService.getResourceFile(new ResourceKey(cssStylesheetKey)) == null ? "false"
                            : "true");
        }

        ResourceKey defaultCSSKey = admin.getDefaultCSSByMenu(menuKey);
        if (defaultCSSKey != null) {
            parameters.put("defaultcsskey", defaultCSSKey.toString());
            parameters.put("defaultcssExist",
                    resourceService.getResourceFile(defaultCSSKey) == null ? "false" : "true");
        }

        if (createPageTemplate) {
            parameters.put("create", "1");
        } else {
            parameters.put("create", "0");
        }

        parameters.put("page", String.valueOf(request.getParameter("page")));
        datasourcesXML = StringUtil.formatXML(datasourcesXML, 2);
        parameters.put("datasources", datasourcesXML);

        parameters.put("menukey", formItems.getString("menukey"));
        parameters.put("selectedtabpageid", formItems.getString("selectedtabpageid", "none"));

        if (stylesheetKey != null) {
            parameters.put("selstylesheetkey", stylesheetKey.toString());
            parameters.put("selstylesheetExist", stylesheet == null ? "false" : "true");
            parameters.put("selstylesheetValid", stylesheetValid ? "true" : "false");

        }

        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 (TransformerException e) {
        VerticalAdminLogger.errorAdmin(this.getClass(), 10, "XSLT error: %t", e);
    } catch (IOException e) {
        VerticalAdminLogger.errorAdmin(this.getClass(), 20, "I/O error: %t", e);
    }
}

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

private void copyMenu(CopyContext copyContext, Element menuElem) throws VerticalCopyException,
        VerticalCreateException, VerticalUpdateException, VerticalSecurityException {

    if (menuElem != null) {
        User user = copyContext.getUser();
        int oldMenuKey = Integer.parseInt(menuElem.getAttribute("key"));

        //if (copyContext.getOldSiteKey() != copyContext.getNewSiteKey())
        //  menuElem.setAttribute("sitekey", String.valueOf(copyContext.getNewSiteKey()));
        //else {/*from w  w  w.j  a  v  a  2 s . com*/
        Element nameElem = XMLTool.getElement(menuElem, "name");
        Text text = (Text) nameElem.getFirstChild();
        Map translationMap = languageMap.getTranslationMap(user.getSelectedLanguageCode());
        text.setData(text.getData() + " (" + translationMap.get("%txtCopy%") + ")");
        //}

        Element elem = XMLTool.getElement(menuElem, "firstpage");
        String oldFirstPageKey = elem.getAttribute("key");
        elem.removeAttribute("key");

        elem = XMLTool.getElement(menuElem, "loginpage");
        String oldLoginPageKey = elem.getAttribute("key");
        elem.removeAttribute("key");

        elem = XMLTool.getElement(menuElem, "errorpage");
        String oldErrorPageKey = elem.getAttribute("key");
        elem.removeAttribute("key");

        String oldDefaultPageTemplateKey = null;
        elem = XMLTool.getElement(menuElem, "defaultpagetemplate");
        if (elem != null) {
            oldDefaultPageTemplateKey = elem.getAttribute("pagetemplatekey");
            elem.removeAttribute("pagetemplatekey");
        }

        Document newDoc = XMLTool.createDocument();
        Element newMenuElem = (Element) newDoc.importNode(menuElem, true);
        newDoc.appendChild(newMenuElem);
        Element menuitemsElem = XMLTool.getElement(newMenuElem, "menuitems");
        newMenuElem.removeChild(menuitemsElem);
        SiteKey menuKey = createMenu(user, copyContext, newDoc, false);

        // copy content objects and page templates
        ContentObjectHandler contentObjectHandler = getContentObjectHandler();
        contentObjectHandler.copyContentObjects(oldMenuKey, copyContext);
        PageTemplateHandler pageTemplateHandler = getPageTemplateHandler();
        pageTemplateHandler.copyPageTemplates(oldMenuKey, copyContext);

        Document doc = getMenu(user, menuKey.toInt(), true, true);
        Element docElem = doc.getDocumentElement();
        newMenuElem = (Element) docElem.getFirstChild();
        doc.replaceChild(newMenuElem, docElem);
        Element newMenuitemsElem = (Element) doc.importNode(menuitemsElem, true);
        menuitemsElem = XMLTool.getElement(newMenuElem, "menuitems");
        newMenuElem.replaceChild(newMenuitemsElem, menuitemsElem);

        // prepare copy of menu items
        prepareCopy(newMenuitemsElem, copyContext);
        updateMenu(user, copyContext, doc, false);

        if (oldFirstPageKey != null && oldFirstPageKey.length() > 0) {
            elem = XMLTool.createElementIfNotPresent(doc, newMenuElem, "firstpage");
            elem.setAttribute("key",
                    String.valueOf(copyContext.getMenuItemKey(Integer.parseInt(oldFirstPageKey))));
        }

        if (oldLoginPageKey != null && oldLoginPageKey.length() > 0) {
            elem = XMLTool.createElementIfNotPresent(doc, newMenuElem, "loginpage");
            elem.setAttribute("key",
                    String.valueOf(copyContext.getMenuItemKey(Integer.parseInt(oldLoginPageKey))));
        }

        if (oldErrorPageKey != null && oldErrorPageKey.length() > 0) {
            elem = XMLTool.createElementIfNotPresent(doc, newMenuElem, "errorpage");
            elem.setAttribute("key",
                    String.valueOf(copyContext.getMenuItemKey(Integer.parseInt(oldErrorPageKey))));
        }

        if (oldDefaultPageTemplateKey != null && oldDefaultPageTemplateKey.length() > 0) {
            elem = XMLTool.createElement(doc, newMenuElem, "defaultpagetemplate");
            elem.setAttribute("pagetemplatekey", String
                    .valueOf(copyContext.getPageTemplateKey(Integer.parseInt(oldDefaultPageTemplateKey))));
        }

        if (copyContext.isIncludeContents()) {
            menuitemsElem = XMLTool.getElement(newMenuElem, "menuitems");
            prepareUpdate(menuitemsElem);
        }

        // update default css
        Element menudataElem = XMLTool.getElement(newMenuElem, "menudata");
        Element defaultcssElem = XMLTool.getElement(menudataElem, "defaultcss");
        if (defaultcssElem != null) {
            String cssKey = defaultcssElem.getAttribute("key");
            if (cssKey != null && cssKey.length() > 0) {
                defaultcssElem.setAttribute("key", cssKey);
            }
        }

        updateMenu(user, copyContext, doc, true);

        // post-process content objects and page templates
        contentObjectHandler.copyContentObjectsPostOp(oldMenuKey, copyContext);
        pageTemplateHandler.copyPageTemplatesPostOp(oldMenuKey, copyContext);
    }
}