Search in sources :

Example 11 with VisualTheme

use of org.apache.ofbiz.widget.renderer.VisualTheme in project ofbiz-framework by apache.

the class OutputServices method createFileFromScreen.

public static Map<String, Object> createFileFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
    Locale locale = (Locale) serviceContext.get("locale");
    Delegator delegator = dctx.getDelegator();
    VisualTheme visualTheme = (VisualTheme) serviceContext.get("visualTheme");
    String screenLocation = (String) serviceContext.remove("screenLocation");
    Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
    String contentType = (String) serviceContext.remove("contentType");
    String filePath = (String) serviceContext.remove("filePath");
    String fileName = (String) serviceContext.remove("fileName");
    if (UtilValidate.isEmpty(screenContext)) {
        screenContext = new HashMap<>();
    }
    screenContext.put("locale", locale);
    if (UtilValidate.isEmpty(contentType)) {
        contentType = "application/pdf";
    }
    try {
        MapStack<String> screenContextTmp = MapStack.create();
        screenContextTmp.put("locale", locale);
        Writer writer = new StringWriter();
        // substitute the freemarker variables...
        ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme().getType("screenfop"), visualTheme.getModelTheme().getScreenRendererLocation("screenfop"));
        ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenStringRenderer);
        screensAtt.populateContextForService(dctx, screenContext);
        screenContextTmp.putAll(screenContext);
        screensAtt.getContext().put("formStringRenderer", foFormRenderer);
        screensAtt.render(screenLocation);
        // create the input stream for the generation
        StreamSource src = new StreamSource(new StringReader(writer.toString()));
        // create the output stream for the generation
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
        ApacheFopWorker.transform(src, null, fop);
        baos.flush();
        baos.close();
        fileName += UtilDateTime.nowAsString();
        if ("application/pdf".equals(contentType)) {
            fileName += ".pdf";
        } else if ("application/postscript".equals(contentType)) {
            fileName += ".ps";
        } else if ("text/plain".equals(contentType)) {
            fileName += ".txt";
        }
        if (UtilValidate.isEmpty(filePath)) {
            filePath = EntityUtilProperties.getPropertyValue("content", "content.output.path", "/output", delegator);
        }
        File file = new File(filePath, fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baos.toByteArray());
        fos.close();
    } catch (IOException | TemplateException | GeneralException | SAXException | ParserConfigurationException e) {
        Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) ScreenRenderer(org.apache.ofbiz.widget.renderer.ScreenRenderer) SAXException(org.xml.sax.SAXException) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) Fop(org.apache.fop.apps.Fop) StreamSource(javax.xml.transform.stream.StreamSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) Delegator(org.apache.ofbiz.entity.Delegator) FileOutputStream(java.io.FileOutputStream) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) File(java.io.File) Writer(java.io.Writer) StringWriter(java.io.StringWriter)

Example 12 with VisualTheme

use of org.apache.ofbiz.widget.renderer.VisualTheme in project ofbiz-framework by apache.

the class OutputServices method sendPrintFromScreen.

public static Map<String, Object> sendPrintFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
    Locale locale = (Locale) serviceContext.get("locale");
    VisualTheme visualTheme = (VisualTheme) serviceContext.get("visualTheme");
    String screenLocation = (String) serviceContext.remove("screenLocation");
    Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
    String contentType = (String) serviceContext.remove("contentType");
    String printerContentType = (String) serviceContext.remove("printerContentType");
    if (UtilValidate.isEmpty(screenContext)) {
        screenContext = new HashMap<>();
    }
    screenContext.put("locale", locale);
    if (UtilValidate.isEmpty(contentType)) {
        contentType = "application/postscript";
    }
    if (UtilValidate.isEmpty(printerContentType)) {
        printerContentType = contentType;
    }
    try {
        MapStack<String> screenContextTmp = MapStack.create();
        screenContextTmp.put("locale", locale);
        Writer writer = new StringWriter();
        // substitute the freemarker variables...
        ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme().getType("screenfop"), visualTheme.getModelTheme().getScreenRendererLocation("screenfop"));
        ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenStringRenderer);
        screensAtt.populateContextForService(dctx, screenContext);
        screenContextTmp.putAll(screenContext);
        screensAtt.getContext().put("formStringRenderer", foFormRenderer);
        screensAtt.render(screenLocation);
        // create the input stream for the generation
        StreamSource src = new StreamSource(new StringReader(writer.toString()));
        // create the output stream for the generation
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
        ApacheFopWorker.transform(src, null, fop);
        baos.flush();
        baos.close();
        // Print is sent
        DocFlavor psInFormat = new DocFlavor.INPUT_STREAM(printerContentType);
        InputStream bais = new ByteArrayInputStream(baos.toByteArray());
        DocAttributeSet docAttributeSet = new HashDocAttributeSet();
        List<Object> docAttributes = UtilGenerics.checkList(serviceContext.remove("docAttributes"));
        if (UtilValidate.isNotEmpty(docAttributes)) {
            for (Object da : docAttributes) {
                Debug.logInfo("Adding DocAttribute: " + da, module);
                docAttributeSet.add((DocAttribute) da);
            }
        }
        Doc myDoc = new SimpleDoc(bais, psInFormat, docAttributeSet);
        PrintService printer = null;
        // lookup the print service for the supplied printer name
        String printerName = (String) serviceContext.remove("printerName");
        if (UtilValidate.isNotEmpty(printerName)) {
            PrintServiceAttributeSet printServiceAttributes = new HashPrintServiceAttributeSet();
            printServiceAttributes.add(new PrinterName(printerName, locale));
            PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributes);
            if (printServices.length > 0) {
                printer = printServices[0];
                Debug.logInfo("Using printer: " + printer.getName(), module);
                if (!printer.isDocFlavorSupported(psInFormat)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotSupportDocFlavorFormat", UtilMisc.toMap("psInFormat", psInFormat, "printerName", printer.getName()), locale));
                }
            }
            if (printer == null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotFound", UtilMisc.toMap("printerName", printerName), locale));
            }
        } else {
            // if no printer name was supplied, try to get the default printer
            printer = PrintServiceLookup.lookupDefaultPrintService();
            if (printer != null) {
                Debug.logInfo("No printer name supplied, using default printer: " + printer.getName(), module);
            }
        }
        if (printer == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotAvailable", locale));
        }
        PrintRequestAttributeSet praset = new HashPrintRequestAttributeSet();
        List<Object> printRequestAttributes = UtilGenerics.checkList(serviceContext.remove("printRequestAttributes"));
        if (UtilValidate.isNotEmpty(printRequestAttributes)) {
            for (Object pra : printRequestAttributes) {
                Debug.logInfo("Adding PrintRequestAttribute: " + pra, module);
                praset.add((PrintRequestAttribute) pra);
            }
        }
        DocPrintJob job = printer.createPrintJob();
        job.print(myDoc, praset);
    } catch (PrintException | IOException | TemplateException | GeneralException | SAXException | ParserConfigurationException e) {
        Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) ScreenRenderer(org.apache.ofbiz.widget.renderer.ScreenRenderer) HashPrintServiceAttributeSet(javax.print.attribute.HashPrintServiceAttributeSet) HashDocAttributeSet(javax.print.attribute.HashDocAttributeSet) DocAttributeSet(javax.print.attribute.DocAttributeSet) PrintService(javax.print.PrintService) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet) PrintRequestAttributeSet(javax.print.attribute.PrintRequestAttributeSet) SAXException(org.xml.sax.SAXException) PrintException(javax.print.PrintException) StringWriter(java.io.StringWriter) SimpleDoc(javax.print.SimpleDoc) StringReader(java.io.StringReader) Doc(javax.print.Doc) SimpleDoc(javax.print.SimpleDoc) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) GeneralException(org.apache.ofbiz.base.util.GeneralException) HashDocAttributeSet(javax.print.attribute.HashDocAttributeSet) TemplateException(freemarker.template.TemplateException) Fop(org.apache.fop.apps.Fop) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DocPrintJob(javax.print.DocPrintJob) IOException(java.io.IOException) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) PrinterName(javax.print.attribute.standard.PrinterName) ByteArrayInputStream(java.io.ByteArrayInputStream) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) DocFlavor(javax.print.DocFlavor) Writer(java.io.Writer) StringWriter(java.io.StringWriter) PrintServiceAttributeSet(javax.print.attribute.PrintServiceAttributeSet) HashPrintServiceAttributeSet(javax.print.attribute.HashPrintServiceAttributeSet) HashPrintRequestAttributeSet(javax.print.attribute.HashPrintRequestAttributeSet)

Example 13 with VisualTheme

use of org.apache.ofbiz.widget.renderer.VisualTheme in project ofbiz-framework by apache.

the class CmsEvents method cms.

public static String cms(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    ServletContext servletContext = request.getSession().getServletContext();
    HttpSession session = request.getSession();
    VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
    Writer writer = null;
    Locale locale = UtilHttp.getLocale(request);
    String webSiteId = (String) session.getAttribute("webSiteId");
    if (webSiteId == null) {
        webSiteId = WebSiteWorker.getWebSiteId(request);
        if (webSiteId == null) {
            request.setAttribute("_ERROR_MESSAGE_", "Not able to run CMS application; no webSiteId defined for WebApp!");
            return "error";
        }
    }
    // is this a default request or called from a defined request mapping
    String targetRequest = (String) request.getAttribute("targetRequestUri");
    String actualRequest = (String) request.getAttribute("thisRequestUri");
    if (targetRequest != null) {
        targetRequest = targetRequest.replaceAll("\\W", "");
    } else {
        targetRequest = "";
    }
    if (actualRequest != null) {
        actualRequest = actualRequest.replaceAll("\\W", "");
    } else {
        actualRequest = "";
    }
    // place holder for the content id
    String contentId = null;
    String mapKey = null;
    String pathInfo = null;
    String displayMaintenancePage = (String) session.getAttribute("displayMaintenancePage");
    if (UtilValidate.isNotEmpty(displayMaintenancePage) && "Y".equalsIgnoreCase(displayMaintenancePage)) {
        try {
            writer = response.getWriter();
            GenericValue webSiteContent = EntityQuery.use(delegator).from("WebSiteContent").where("webSiteId", webSiteId, "webSiteContentTypeId", "MAINTENANCE_PAGE").filterByDate().queryFirst();
            if (webSiteContent != null) {
                ContentWorker.renderContentAsText(dispatcher, webSiteContent.getString("contentId"), writer, null, locale, "text/html", null, null, true);
                return "success";
            } else {
                request.setAttribute("_ERROR_MESSAGE_", "Not able to display maintenance page for [" + webSiteId + "]");
                return "error";
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        } catch (IOException e) {
            throw new GeneralRuntimeException("Error in the response writer/output stream while rendering content.", e);
        } catch (GeneralException e) {
            throw new GeneralRuntimeException("Error rendering content", e);
        }
    } else {
        // If an override view is present then use that in place of request.getPathInfo()
        String overrideViewUri = (String) request.getAttribute("_CURRENT_CHAIN_VIEW_");
        if (UtilValidate.isNotEmpty(overrideViewUri)) {
            pathInfo = overrideViewUri;
        } else {
            pathInfo = request.getPathInfo();
            if (targetRequest.equals(actualRequest) && pathInfo != null) {
                // was called directly -- path info is everything after the request
                String[] pathParsed = pathInfo.split("/", 3);
                if (pathParsed.length > 2) {
                    pathInfo = pathParsed[2];
                } else {
                    pathInfo = null;
                }
            }
        // if called through the default request, there is no request in pathinfo
        }
        // if path info is null or path info is / (i.e application mounted on root); check for a default content
        if (pathInfo == null || "/".equals(pathInfo)) {
            GenericValue defaultContent = null;
            try {
                defaultContent = EntityQuery.use(delegator).from("WebSiteContent").where("webSiteId", webSiteId, "webSiteContentTypeId", "DEFAULT_PAGE").orderBy("-fromDate").filterByDate().cache().queryFirst();
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
            if (defaultContent != null) {
                pathInfo = defaultContent.getString("contentId");
            }
        }
        // check for path alias first
        if (pathInfo != null) {
            // clean up the pathinfo for parsing
            pathInfo = pathInfo.trim();
            if (pathInfo.startsWith("/")) {
                pathInfo = pathInfo.substring(1);
            }
            if (pathInfo.endsWith("/")) {
                pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
            }
            GenericValue pathAlias = null;
            try {
                pathAlias = EntityQuery.use(delegator).from("WebSitePathAlias").where("webSiteId", webSiteId, "pathAlias", pathInfo).orderBy("-fromDate").cache().filterByDate().queryOne();
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
            if (pathAlias != null) {
                String alias = pathAlias.getString("aliasTo");
                contentId = pathAlias.getString("contentId");
                mapKey = pathAlias.getString("mapKey");
                if (contentId == null && UtilValidate.isNotEmpty(alias)) {
                    if (!alias.startsWith("/")) {
                        alias = "/" + alias;
                    }
                    RequestDispatcher rd = request.getRequestDispatcher(request.getServletPath() + alias);
                    try {
                        rd.forward(request, response);
                    } catch (ServletException e) {
                        Debug.logError(e, module);
                        return "error";
                    } catch (IOException e) {
                        Debug.logError(e, module);
                        return "error";
                    }
                    // null to not process any views
                    return null;
                }
            }
            // get the contentId/mapKey from URL
            if (contentId == null) {
                if (Debug.verboseOn())
                    Debug.logVerbose("Current PathInfo: " + pathInfo, module);
                String[] pathSplit = pathInfo.split("/");
                if (Debug.verboseOn())
                    Debug.logVerbose("Split pathinfo: " + pathSplit.length, module);
                contentId = pathSplit[0];
                if (pathSplit.length > 1) {
                    mapKey = pathSplit[1];
                }
            }
            // verify the request content is associated with the current website
            int statusCode = -1;
            boolean hasErrorPage = false;
            if (contentId != null) {
                try {
                    statusCode = verifyContentToWebSite(delegator, webSiteId, contentId);
                } catch (GeneralException e) {
                    Debug.logError(e, module);
                    throw new GeneralRuntimeException(e.getMessage(), e);
                }
            } else {
                statusCode = HttpServletResponse.SC_NOT_FOUND;
            }
            // We try to find a specific Error page for this website concerning the status code
            if (statusCode != HttpServletResponse.SC_OK) {
                GenericValue errorContainer = null;
                try {
                    errorContainer = EntityQuery.use(delegator).from("WebSiteContent").where("webSiteId", webSiteId, "webSiteContentTypeId", "ERROR_ROOT").orderBy("fromDate").filterByDate().cache().queryFirst();
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
                if (errorContainer != null) {
                    if (Debug.verboseOn())
                        Debug.logVerbose("Found error containers: " + errorContainer, module);
                    GenericValue errorPage = null;
                    try {
                        errorPage = EntityQuery.use(delegator).from("ContentAssocViewTo").where("contentIdStart", errorContainer.getString("contentId"), "caContentAssocTypeId", "TREE_CHILD", "contentTypeId", "DOCUMENT", "caMapKey", String.valueOf(statusCode)).filterByDate().queryFirst();
                    } catch (GenericEntityException e) {
                        Debug.logError(e, module);
                    }
                    if (errorPage != null) {
                        if (Debug.verboseOn()) {
                            Debug.logVerbose("Found error pages " + statusCode + " : " + errorPage, module);
                        }
                        contentId = errorPage.getString("contentId");
                    } else {
                        if (Debug.verboseOn()) {
                            Debug.logVerbose("No specific error page, falling back to the Error Container for " + statusCode, module);
                        }
                        contentId = errorContainer.getString("contentId");
                    }
                    mapKey = null;
                    hasErrorPage = true;
                }
                // We try to find a generic content Error page concerning the status code
                if (!hasErrorPage) {
                    try {
                        GenericValue errorPage = EntityQuery.use(delegator).from("Content").where("contentId", "CONTENT_ERROR_" + statusCode).cache().queryOne();
                        if (errorPage != null) {
                            if (Debug.verboseOn())
                                Debug.logVerbose("Found generic page " + statusCode, module);
                            contentId = errorPage.getString("contentId");
                            mapKey = null;
                            hasErrorPage = true;
                        }
                    } catch (GenericEntityException e) {
                        Debug.logError(e, module);
                    }
                }
            }
            if (statusCode == HttpServletResponse.SC_OK || hasErrorPage) {
                // create the template map
                MapStack<String> templateMap = MapStack.create();
                ScreenRenderer.populateContextForRequest(templateMap, null, request, response, servletContext);
                templateMap.put("statusCode", statusCode);
                // make the link prefix
                ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
                RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
                templateMap.put("_REQUEST_HANDLER_", rh);
                response.setStatus(statusCode);
                try {
                    writer = response.getWriter();
                    // TODO: replace "screen" to support dynamic rendering of different output
                    if (visualTheme == null) {
                        String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator);
                        visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId);
                    }
                    FormStringRenderer formStringRenderer = new MacroFormRenderer(visualTheme.getModelTheme().getFormRendererLocation("screen"), request, response);
                    templateMap.put("formStringRenderer", formStringRenderer);
                    // if use web analytics
                    List<GenericValue> webAnalytics = EntityQuery.use(delegator).from("WebAnalyticsConfig").where("webSiteId", webSiteId).queryList();
                    // render
                    if (UtilValidate.isNotEmpty(webAnalytics) && hasErrorPage) {
                        ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true, webAnalytics);
                    } else if (UtilValidate.isEmpty(mapKey)) {
                        ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true);
                    } else {
                        ContentWorker.renderSubContentAsText(dispatcher, contentId, writer, mapKey, templateMap, locale, "text/html", true);
                    }
                } catch (TemplateException e) {
                    throw new GeneralRuntimeException(String.format("Error creating form renderer while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
                } catch (IOException e) {
                    throw new GeneralRuntimeException(String.format("Error in the response writer/output stream while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
                } catch (GeneralException e) {
                    throw new GeneralRuntimeException(String.format("Error rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
                }
                return "success";
            } else {
                String contentName = null;
                String siteName = null;
                try {
                    GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
                    if (content != null && UtilValidate.isNotEmpty(content.getString("contentName"))) {
                        contentName = content.getString("contentName");
                    } else {
                        request.setAttribute("_ERROR_MESSAGE_", "Content: [" + contentId + "] is not a publish point for the current website: [" + webSiteId + "]");
                        return "error";
                    }
                    siteName = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne().getString("siteName");
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
                request.setAttribute("_ERROR_MESSAGE_", "Content: " + contentName + " [" + contentId + "] is not a publish point for the current website: " + siteName + " [" + webSiteId + "]");
                return "error";
            }
        }
    }
    String siteName = null;
    GenericValue webSite = null;
    try {
        webSite = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne();
        if (webSite != null) {
            siteName = webSite.getString("siteName");
        }
        if (siteName == null) {
            siteName = "Not specified";
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (webSite != null) {
        request.setAttribute("_ERROR_MESSAGE_", "Not able to find a page to display for website: " + siteName + " [" + webSiteId + "] not even a default page!");
    } else {
        request.setAttribute("_ERROR_MESSAGE_", "Not able to find a page to display, not even a default page AND the website entity record for WebSiteId:" + webSiteId + " could not be found");
    }
    return "error";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) HttpSession(javax.servlet.http.HttpSession) MacroFormRenderer(org.apache.ofbiz.widget.renderer.macro.MacroFormRenderer) IOException(java.io.IOException) RequestDispatcher(javax.servlet.RequestDispatcher) ServletException(javax.servlet.ServletException) Delegator(org.apache.ofbiz.entity.Delegator) GeneralRuntimeException(org.apache.ofbiz.base.util.GeneralRuntimeException) RequestHandler(org.apache.ofbiz.webapp.control.RequestHandler) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) FormStringRenderer(org.apache.ofbiz.widget.renderer.FormStringRenderer) ServletContext(javax.servlet.ServletContext) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) Writer(java.io.Writer)

Example 14 with VisualTheme

use of org.apache.ofbiz.widget.renderer.VisualTheme in project ofbiz-framework by apache.

the class MacroScreenRenderer method renderLink.

public void renderLink(Appendable writer, Map<String, Object> context, ModelScreenWidget.ScreenLink link) throws IOException {
    HttpServletResponse response = (HttpServletResponse) context.get("response");
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
    ModelTheme modelTheme = visualTheme.getModelTheme();
    String targetWindow = link.getTargetWindow(context);
    String target = link.getTarget(context);
    String uniqueItemName = link.getModelScreen().getName() + "_LF_" + UtilMisc.<String>addToBigDecimalInMap(context, "screenUniqueItemIndex", BigDecimal.ONE);
    String linkType = WidgetWorker.determineAutoLinkType(link.getLinkType(), target, link.getUrlMode(), request);
    String linkUrl = "";
    String actionUrl = "";
    StringBuilder parameters = new StringBuilder();
    String width = link.getWidth();
    if (UtilValidate.isEmpty(width)) {
        width = String.valueOf(modelTheme.getLinkDefaultLayeredModalWidth());
    }
    String height = link.getHeight();
    if (UtilValidate.isEmpty(height)) {
        height = String.valueOf(modelTheme.getLinkDefaultLayeredModalHeight());
    }
    if ("hidden-form".equals(linkType) || "layered-modal".equals(linkType)) {
        StringBuilder sb = new StringBuilder();
        WidgetWorker.buildHyperlinkUrl(sb, target, link.getUrlMode(), null, link.getPrefix(context), link.getFullPath(), link.getSecure(), link.getEncode(), request, response, context);
        actionUrl = sb.toString();
        parameters.append("[");
        for (Map.Entry<String, String> parameter : link.getParameterMap(context).entrySet()) {
            if (parameters.length() > 1) {
                parameters.append(",");
            }
            parameters.append("{'name':'");
            parameters.append(parameter.getKey());
            parameters.append("'");
            parameters.append(",'value':'");
            parameters.append(parameter.getValue());
            parameters.append("'}");
        }
        parameters.append("]");
    }
    String id = link.getId(context);
    String style = link.getStyle(context);
    String name = link.getName(context);
    String text = link.getText(context);
    if (UtilValidate.isNotEmpty(target)) {
        if (!"hidden-form".equals(linkType)) {
            StringBuilder sb = new StringBuilder();
            WidgetWorker.buildHyperlinkUrl(sb, target, link.getUrlMode(), link.getParameterMap(context), link.getPrefix(context), link.getFullPath(), link.getSecure(), link.getEncode(), request, response, context);
            linkUrl = sb.toString();
        }
    }
    String imgStr = "";
    ModelScreenWidget.ScreenImage img = link.getImage();
    if (img != null) {
        StringWriter sw = new StringWriter();
        renderImage(sw, context, img);
        imgStr = sw.toString();
    }
    StringWriter sr = new StringWriter();
    sr.append("<@renderLink ");
    sr.append("parameterList=");
    sr.append(parameters.length() == 0 ? "\"\"" : parameters.toString());
    sr.append(" targetWindow=\"");
    sr.append(targetWindow);
    sr.append("\" target=\"");
    sr.append(target);
    sr.append("\" uniqueItemName=\"");
    sr.append(uniqueItemName);
    sr.append("\" linkType=\"");
    sr.append(linkType);
    sr.append("\" actionUrl=\"");
    sr.append(actionUrl);
    sr.append("\" id=\"");
    sr.append(id);
    sr.append("\" style=\"");
    sr.append(style);
    sr.append("\" name=\"");
    sr.append(name);
    sr.append("\" width=\"");
    sr.append(width);
    sr.append("\" height=\"");
    sr.append(height);
    sr.append("\" linkUrl=\"");
    sr.append(linkUrl);
    sr.append("\" text=\"");
    sr.append(text);
    sr.append("\" imgStr=\"");
    sr.append(imgStr.replaceAll("\"", "\\\\\""));
    sr.append("\" />");
    executeMacro(writer, sr.toString());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) StringWriter(java.io.StringWriter) HttpServletResponse(javax.servlet.http.HttpServletResponse) ModelTheme(org.apache.ofbiz.widget.model.ModelTheme) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) ModelScreenWidget(org.apache.ofbiz.widget.model.ModelScreenWidget) HashMap(java.util.HashMap) Map(java.util.Map) WeakHashMap(java.util.WeakHashMap)

Example 15 with VisualTheme

use of org.apache.ofbiz.widget.renderer.VisualTheme in project ofbiz-framework by apache.

the class MacroScreenRenderer method renderScreenletBegin.

public void renderScreenletBegin(Appendable writer, Map<String, Object> context, boolean collapsed, ModelScreenWidget.Screenlet screenlet) throws IOException {
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");
    VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
    ModelTheme modelTheme = visualTheme.getModelTheme();
    boolean javaScriptEnabled = UtilHttp.isJavaScriptEnabled(request);
    ModelScreenWidget.Menu tabMenu = screenlet.getTabMenu();
    if (tabMenu != null) {
        tabMenu.renderWidgetString(writer, context, this);
    }
    String title = screenlet.getTitle(context);
    boolean collapsible = screenlet.collapsible();
    ModelScreenWidget.Menu navMenu = screenlet.getNavigationMenu();
    ModelScreenWidget.Form navForm = screenlet.getNavigationForm();
    String expandToolTip = "";
    String collapseToolTip = "";
    String fullUrlString = "";
    String menuString = "";
    boolean showMore = false;
    if (UtilValidate.isNotEmpty(title) || navMenu != null || navForm != null || collapsible) {
        showMore = true;
        if (collapsible) {
            this.getNextElementId();
            Map<String, Object> uiLabelMap = UtilGenerics.checkMap(context.get("uiLabelMap"));
            Map<String, Object> paramMap = UtilGenerics.checkMap(context.get("requestParameters"));
            Map<String, Object> requestParameters = new HashMap<>(paramMap);
            if (uiLabelMap != null) {
                expandToolTip = (String) uiLabelMap.get("CommonExpand");
                collapseToolTip = (String) uiLabelMap.get("CommonCollapse");
            }
            if (!javaScriptEnabled) {
                requestParameters.put(screenlet.getPreferenceKey(context) + "_collapsed", collapsed ? "false" : "true");
                String queryString = UtilHttp.urlEncodeArgs(requestParameters);
                fullUrlString = request.getRequestURI() + "?" + queryString;
            }
        }
        StringWriter sb = new StringWriter();
        if (navMenu != null) {
            MenuStringRenderer savedRenderer = (MenuStringRenderer) context.get("menuStringRenderer");
            MenuStringRenderer renderer;
            try {
                renderer = new MacroMenuRenderer(modelTheme.getMenuRendererLocation("screen"), request, response);
                context.put("menuStringRenderer", renderer);
                navMenu.renderWidgetString(sb, context, this);
                context.put("menuStringRenderer", savedRenderer);
            } catch (TemplateException e) {
                Debug.logError(e, module);
            }
        } else if (navForm != null) {
            renderScreenletPaginateMenu(sb, context, navForm);
        }
        menuString = sb.toString();
    }
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("title", title);
    parameters.put("collapsible", collapsible);
    parameters.put("saveCollapsed", screenlet.saveCollapsed());
    if (UtilValidate.isNotEmpty(screenlet.getId(context))) {
        parameters.put("id", screenlet.getId(context));
        parameters.put("collapsibleAreaId", screenlet.getId(context) + "_col");
    } else {
        parameters.put("id", "screenlet_" + screenLetsIdCounter);
        parameters.put("collapsibleAreaId", "screenlet_" + screenLetsIdCounter + "_col");
        screenLetsIdCounter++;
    }
    parameters.put("expandToolTip", expandToolTip);
    parameters.put("collapseToolTip", collapseToolTip);
    parameters.put("fullUrlString", fullUrlString);
    parameters.put("padded", screenlet.padded());
    parameters.put("menuString", menuString);
    parameters.put("showMore", showMore);
    parameters.put("collapsed", collapsed);
    parameters.put("javaScriptEnabled", javaScriptEnabled);
    executeMacro(writer, "renderScreenletBegin", parameters);
}
Also used : HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) TemplateException(freemarker.template.TemplateException) HttpServletResponse(javax.servlet.http.HttpServletResponse) ModelTheme(org.apache.ofbiz.widget.model.ModelTheme) MenuStringRenderer(org.apache.ofbiz.widget.renderer.MenuStringRenderer) HttpServletRequest(javax.servlet.http.HttpServletRequest) StringWriter(java.io.StringWriter) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) ModelScreenWidget(org.apache.ofbiz.widget.model.ModelScreenWidget)

Aggregations

VisualTheme (org.apache.ofbiz.widget.renderer.VisualTheme)18 TemplateException (freemarker.template.TemplateException)11 IOException (java.io.IOException)10 GeneralException (org.apache.ofbiz.base.util.GeneralException)9 ModelTheme (org.apache.ofbiz.widget.model.ModelTheme)9 ScreenRenderer (org.apache.ofbiz.widget.renderer.ScreenRenderer)9 ScreenStringRenderer (org.apache.ofbiz.widget.renderer.ScreenStringRenderer)9 StringWriter (java.io.StringWriter)8 Writer (java.io.Writer)8 MacroScreenRenderer (org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer)8 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)7 SAXException (org.xml.sax.SAXException)7 Delegator (org.apache.ofbiz.entity.Delegator)6 Locale (java.util.Locale)5 GenericValue (org.apache.ofbiz.entity.GenericValue)5 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 StringReader (java.io.StringReader)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4