Search in sources :

Example 1 with MacroFormRenderer

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

the class ScreenFopViewHandler method render.

/**
 * @see org.apache.ofbiz.webapp.view.ViewHandler#render(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@Override
public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
    ModelTheme modelTheme = visualTheme.getModelTheme();
    // render and obtain the XSL-FO
    Writer writer = new StringWriter();
    try {
        ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(modelTheme.getType(getName()), modelTheme.getScreenRendererLocation(getName()));
        FormStringRenderer formStringRenderer = new MacroFormRenderer(modelTheme.getFormRendererLocation(getName()), request, response);
        // TODO: uncomment these lines when the renderers are implemented
        // TreeStringRenderer treeStringRenderer = new MacroTreeRenderer(modelTheme.getTreeRendererLocation(getName()), writer);
        // MenuStringRenderer menuStringRenderer = new MacroMenuRenderer(modelTheme.getMenuRendererLocation(getName()), writer);
        ScreenRenderer screens = new ScreenRenderer(writer, null, screenStringRenderer);
        screens.populateContextForRequest(request, response, servletContext);
        // this is the object used to render forms from their definitions
        screens.getContext().put("formStringRenderer", formStringRenderer);
        screens.getContext().put("simpleEncoder", UtilCodec.getEncoder(modelTheme.getEncoder(getName())));
        screens.render(page);
    } catch (IOException | GeneralException | SAXException | ParserConfigurationException | TemplateException e) {
        renderError("Problems with the response writer/output stream", e, "[Not Yet Rendered]", request, response);
        return;
    }
    // set the input source (XSL-FO) and generate the output stream of contentType
    String screenOutString = writer.toString();
    if (!screenOutString.startsWith("<?xml")) {
        screenOutString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + screenOutString;
    }
    if (Debug.verboseOn())
        Debug.logVerbose("XSL:FO Screen Output: " + screenOutString, module);
    if (UtilValidate.isEmpty(contentType)) {
        contentType = modelTheme.getContentType(getName());
    }
    // get encryption related parameters
    FOUserAgent foUserAgent = null;
    String userPassword = request.getParameter("userPassword");
    String ownerPassword = request.getParameter("ownerPassword");
    boolean allowPrint = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowPrint")) ? ApacheFopWorker.getAllowPrintDefault() : request.getParameter("allowPrint"));
    boolean allowCopyContent = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowCopyContent")) ? ApacheFopWorker.getAllowCopyContentDefault() : request.getParameter("allowCopyContent"));
    boolean allowEditContent = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowEditContent")) ? ApacheFopWorker.getAllowEditContentDefault() : request.getParameter("allowEditContent"));
    boolean allowEditAnnotations = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowEditAnnotations")) ? ApacheFopWorker.getAllowEditAnnotationsDefault() : request.getParameter("allowEditAnnotations"));
    if (UtilValidate.isNotEmpty(userPassword) || UtilValidate.isNotEmpty(ownerPassword) || !allowPrint || !allowCopyContent || allowEditContent || !allowEditAnnotations) {
        int encryptionLength = 128;
        try {
            encryptionLength = Integer.parseInt(request.getParameter("encryption-length"));
        } catch (NumberFormatException e) {
            try {
                encryptionLength = Integer.parseInt(ApacheFopWorker.getEncryptionLengthDefault());
            } catch (NumberFormatException e1) {
            // ignore
            }
        }
        boolean encryptMetadata = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("encrypt-metadata")) ? ApacheFopWorker.getEncryptMetadataDefault() : request.getParameter("encrypt-metadata"));
        boolean allowFillInForms = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowFillInForms")) ? ApacheFopWorker.getAllowFillInFormsDefault() : request.getParameter("allowFillInForms"));
        boolean allowAccessContent = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowAccessContent")) ? ApacheFopWorker.getAllowAccessContentDefault() : request.getParameter("allowAccessContent"));
        boolean allowAssembleDocument = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowAssembleDocument")) ? ApacheFopWorker.getAllowAssembleDocumentDefault() : request.getParameter("allowAssembleDocument"));
        boolean allowPrintHq = Boolean.parseBoolean(UtilValidate.isEmpty(request.getParameter("allowPrintHq")) ? ApacheFopWorker.getAllowPrintHqDefault() : request.getParameter("allowPrintHq"));
        FopFactory fopFactory = ApacheFopWorker.getFactoryInstance();
        foUserAgent = fopFactory.newFOUserAgent();
        PDFEncryptionParams pdfEncryptionParams = new PDFEncryptionParams(userPassword, ownerPassword, allowPrint, allowCopyContent, allowEditContent, allowEditAnnotations, encryptMetadata);
        pdfEncryptionParams.setAllowFillInForms(allowFillInForms);
        pdfEncryptionParams.setAllowAccessContent(allowAccessContent);
        pdfEncryptionParams.setAllowAssembleDocument(allowAssembleDocument);
        pdfEncryptionParams.setAllowPrintHq(allowPrintHq);
        pdfEncryptionParams.setEncryptionLengthInBits(encryptionLength);
        foUserAgent.getRendererOptions().put(PDFEncryptionOption.ENCRYPTION_PARAMS, pdfEncryptionParams);
    }
    Reader reader = new StringReader(screenOutString);
    StreamSource src = new StreamSource(reader);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    /* Debug area, uncomment this to view the xml file generate before analyse by fop
        try { 
                java.io.FileWriter fw = new java.io.FileWriter(new java.io.File("/tmp/temp.xsl.fo"));
                fw.write(screenOutString);
                fw.close();
            } catch (IOException e) {
                Debug.logError(e, "Couldn't save xls debug file: " + e.toString(), module);
            }
        */
    try {
        Fop fop = ApacheFopWorker.createFopInstance(out, contentType, foUserAgent);
        ApacheFopWorker.transform(src, null, fop);
    } catch (Exception e) {
        renderError("Unable to transform FO file", e, screenOutString, request, response);
        return;
    }
    // set the content type and length
    response.setContentType(contentType);
    response.setContentLength(out.size());
    // write to the browser
    try {
        out.writeTo(response.getOutputStream());
        response.getOutputStream().flush();
    } catch (IOException e) {
        renderError("Unable to write to OutputStream", e, screenOutString, request, response);
    }
}
Also used : FOUserAgent(org.apache.fop.apps.FOUserAgent) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) ScreenRenderer(org.apache.ofbiz.widget.renderer.ScreenRenderer) MacroFormRenderer(org.apache.ofbiz.widget.renderer.macro.MacroFormRenderer) Reader(java.io.Reader) StringReader(java.io.StringReader) FopFactory(org.apache.fop.apps.FopFactory) 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) ModelTheme(org.apache.ofbiz.widget.model.ModelTheme) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) TemplateException(freemarker.template.TemplateException) ViewHandlerException(org.apache.ofbiz.webapp.view.ViewHandlerException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator) FormStringRenderer(org.apache.ofbiz.widget.renderer.FormStringRenderer) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) StringWriter(java.io.StringWriter) Writer(java.io.Writer) PDFEncryptionParams(org.apache.fop.pdf.PDFEncryptionParams)

Example 2 with MacroFormRenderer

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

the class DataResourceWorker method renderDataResourceAsText.

public static void renderDataResourceAsText(LocalDispatcher dispatcher, Delegator delegator, String dataResourceId, Appendable out, Map<String, Object> templateContext, Locale locale, String targetMimeTypeId, boolean cache, List<GenericValue> webAnalytics) throws GeneralException, IOException {
    if (delegator == null) {
        delegator = dispatcher.getDelegator();
    }
    if (dataResourceId == null) {
        throw new GeneralException("Cannot lookup data resource with for a null dataResourceId");
    }
    if (templateContext == null) {
        templateContext = new HashMap<>();
    }
    if (UtilValidate.isEmpty(targetMimeTypeId)) {
        targetMimeTypeId = "text/html";
    }
    if (locale == null) {
        locale = Locale.getDefault();
    }
    // FIXME correctly propagate the theme, then fixes also the related FIXME below
    VisualTheme visualTheme = ThemeFactory.getVisualThemeFromId("COMMON");
    ModelTheme modelTheme = visualTheme.getModelTheme();
    // if the target mimeTypeId is not a text type, throw an exception
    if (!targetMimeTypeId.startsWith("text/")) {
        throw new GeneralException("The desired mime-type is not a text type, cannot render as text: " + targetMimeTypeId);
    }
    // get the data resource object
    GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache(cache).queryOne();
    if (dataResource == null) {
        throw new GeneralException("No data resource object found for dataResourceId: [" + dataResourceId + "]");
    }
    // a data template attached to the data resource
    String dataTemplateTypeId = dataResource.getString("dataTemplateTypeId");
    // no template; or template is NONE; render the data
    if (UtilValidate.isEmpty(dataTemplateTypeId) || "NONE".equals(dataTemplateTypeId)) {
        DataResourceWorker.writeDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, out, cache);
    } else {
        // a template is defined; render the template first
        templateContext.put("mimeTypeId", targetMimeTypeId);
        // FTL template
        if ("FTL".equals(dataTemplateTypeId)) {
            try {
                // get the template data for rendering
                String templateText = getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache);
                // if use web analytics.
                if (UtilValidate.isNotEmpty(webAnalytics)) {
                    StringBuffer newTemplateText = new StringBuffer(templateText);
                    String webAnalyticsCode = "<script language=\"JavaScript\" type=\"text/javascript\">";
                    for (GenericValue webAnalytic : webAnalytics) {
                        StringWrapper wrapString = StringUtil.wrapString((String) webAnalytic.get("webAnalyticsCode"));
                        webAnalyticsCode += wrapString.toString();
                    }
                    webAnalyticsCode += "</script>";
                    newTemplateText.insert(templateText.lastIndexOf("</head>"), webAnalyticsCode);
                    templateText = newTemplateText.toString();
                }
                // render the FTL template
                boolean useTemplateCache = cache && !UtilProperties.getPropertyAsBoolean("content", "disable.ftl.template.cache", false);
                // Do not use dataResource.lastUpdatedStamp for dataResource template caching as it may use ftl file or electronicText
                // If dataResource using ftl file use nowTimestamp to avoid freemarker caching
                Timestamp lastUpdatedStamp = UtilDateTime.nowTimestamp();
                // If dataResource is type of ELECTRONIC_TEXT then only use the lastUpdatedStamp of electronicText entity for freemarker caching
                if ("ELECTRONIC_TEXT".equals(dataResource.getString("dataResourceTypeId"))) {
                    GenericValue electronicText = dataResource.getRelatedOne("ElectronicText", true);
                    if (electronicText != null) {
                        lastUpdatedStamp = electronicText.getTimestamp("lastUpdatedStamp");
                    }
                }
                FreeMarkerWorker.renderTemplateFromString("delegator:" + delegator.getDelegatorName() + ":DataResource:" + dataResourceId, templateText, templateContext, out, lastUpdatedStamp.getTime(), useTemplateCache);
            } catch (TemplateException e) {
                throw new GeneralException("Error rendering FTL template", e);
            }
        } else if ("XSLT".equals(dataTemplateTypeId)) {
            File targetFileLocation = new File(System.getProperty("ofbiz.home") + "/runtime/tempfiles/docbook.css");
            // This is related with the other FIXME above: we need to correctly propagate the theme.
            String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator);
            visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId);
            modelTheme = visualTheme.getModelTheme();
            String docbookStylesheet = modelTheme.getProperty("VT_DOCBOOKSTYLESHEET").toString();
            File sourceFileLocation = new File(System.getProperty("ofbiz.home") + "/themes" + docbookStylesheet.substring(1, docbookStylesheet.length() - 1));
            UtilMisc.copyFile(sourceFileLocation, targetFileLocation);
            // get the template data for rendering
            String templateLocation = DataResourceWorker.getContentFile(dataResource.getString("dataResourceTypeId"), dataResource.getString("objectInfo"), (String) templateContext.get("contextRoot")).toString();
            // render the XSLT template and file
            String outDoc = null;
            try {
                outDoc = XslTransform.renderTemplate(templateLocation, (String) templateContext.get("docFile"));
            } catch (TransformerException c) {
                Debug.logError("XSL TransformerException: " + c.getMessage(), module);
            }
            out.append(outDoc);
        // Screen Widget template
        } else if ("SCREEN_COMBINED".equals(dataTemplateTypeId)) {
            try {
                MapStack<String> context = MapStack.create(templateContext);
                context.put("locale", locale);
                // prepare the map for preRenderedContent
                String textData = (String) context.get("textData");
                if (UtilValidate.isNotEmpty(textData)) {
                    Map<String, Object> prc = new HashMap<>();
                    String mapKey = (String) context.get("mapKey");
                    if (mapKey != null) {
                        prc.put(mapKey, mapKey);
                    }
                    // used for default screen defs
                    prc.put("body", textData);
                    context.put("preRenderedContent", prc);
                }
                // get the screen renderer; or create a new one
                ScreenRenderer screens = (ScreenRenderer) context.get("screens");
                if (screens == null) {
                    // TODO: replace "screen" to support dynamic rendering of different output
                    ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(modelTheme.getType("screen"), modelTheme.getScreenRendererLocation("screen"));
                    screens = new ScreenRenderer(out, context, screenStringRenderer);
                    screens.getContext().put("screens", screens);
                }
                // render the screen
                ModelScreen modelScreen = null;
                ScreenStringRenderer renderer = screens.getScreenStringRenderer();
                String combinedName = dataResource.getString("objectInfo");
                if ("URL_RESOURCE".equals(dataResource.getString("dataResourceTypeId")) && UtilValidate.isNotEmpty(combinedName) && combinedName.startsWith("component://")) {
                    modelScreen = ScreenFactory.getScreenFromLocation(combinedName);
                } else {
                    // stored in  a single file, long or short text
                    Document screenXml = UtilXml.readXmlDocument(getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache), true, true);
                    Map<String, ModelScreen> modelScreenMap = ScreenFactory.readScreenDocument(screenXml, "DataResourceId: " + dataResource.getString("dataResourceId"));
                    if (UtilValidate.isNotEmpty(modelScreenMap)) {
                        // get first entry, only one screen allowed per file
                        Map.Entry<String, ModelScreen> entry = modelScreenMap.entrySet().iterator().next();
                        modelScreen = entry.getValue();
                    }
                }
                if (UtilValidate.isNotEmpty(modelScreen)) {
                    modelScreen.renderScreenString(out, context, renderer);
                } else {
                    throw new GeneralException("The dataResource file [" + dataResourceId + "] could not be found");
                }
            } catch (SAXException | ParserConfigurationException e) {
                throw new GeneralException("Error rendering Screen template", e);
            } catch (TemplateException e) {
                throw new GeneralException("Error creating Screen renderer", e);
            }
        } else if ("FORM_COMBINED".equals(dataTemplateTypeId)) {
            try {
                Map<String, Object> context = UtilGenerics.checkMap(templateContext.get("globalContext"));
                context.put("locale", locale);
                context.put("simpleEncoder", UtilCodec.getEncoder(modelTheme.getEncoder("screen")));
                HttpServletRequest request = (HttpServletRequest) context.get("request");
                HttpServletResponse response = (HttpServletResponse) context.get("response");
                ModelForm modelForm = null;
                ModelReader entityModelReader = delegator.getModelReader();
                String formText = getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache);
                Document formXml = UtilXml.readXmlDocument(formText, true, true);
                Map<String, ModelForm> modelFormMap = FormFactory.readFormDocument(formXml, entityModelReader, dispatcher.getDispatchContext(), null);
                if (UtilValidate.isNotEmpty(modelFormMap)) {
                    // get first entry, only one form allowed per file
                    Map.Entry<String, ModelForm> entry = modelFormMap.entrySet().iterator().next();
                    modelForm = entry.getValue();
                }
                String formrenderer = modelTheme.getFormRendererLocation("screen");
                MacroFormRenderer renderer = new MacroFormRenderer(formrenderer, request, response);
                FormRenderer formRenderer = new FormRenderer(modelForm, renderer);
                formRenderer.render(out, context);
            } catch (SAXException | ParserConfigurationException e) {
                throw new GeneralException("Error rendering Screen template", e);
            } catch (TemplateException e) {
                throw new GeneralException("Error creating Screen renderer", e);
            } catch (Exception e) {
                throw new GeneralException("Error rendering Screen template", e);
            }
        } else {
            throw new GeneralException("The dataTemplateTypeId [" + dataTemplateTypeId + "] is not yet supported");
        }
    }
}
Also used : HashMap(java.util.HashMap) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) ScreenRenderer(org.apache.ofbiz.widget.renderer.ScreenRenderer) MacroFormRenderer(org.apache.ofbiz.widget.renderer.macro.MacroFormRenderer) ModelScreen(org.apache.ofbiz.widget.model.ModelScreen) Document(org.w3c.dom.Document) Timestamp(java.sql.Timestamp) SAXException(org.xml.sax.SAXException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ModelReader(org.apache.ofbiz.entity.model.ModelReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException) GenericValue(org.apache.ofbiz.entity.GenericValue) StringWrapper(org.apache.ofbiz.base.util.StringUtil.StringWrapper) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) ModelTheme(org.apache.ofbiz.widget.model.ModelTheme) HttpServletResponse(javax.servlet.http.HttpServletResponse) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) FileNotFoundException(java.io.FileNotFoundException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) TransformerException(javax.xml.transform.TransformerException) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) FileUploadException(org.apache.commons.fileupload.FileUploadException) FormRenderer(org.apache.ofbiz.widget.renderer.FormRenderer) MacroFormRenderer(org.apache.ofbiz.widget.renderer.macro.MacroFormRenderer) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) ModelForm(org.apache.ofbiz.widget.model.ModelForm)

Example 3 with MacroFormRenderer

use of org.apache.ofbiz.widget.renderer.macro.MacroFormRenderer 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)

Aggregations

TemplateException (freemarker.template.TemplateException)3 IOException (java.io.IOException)3 GeneralException (org.apache.ofbiz.base.util.GeneralException)3 VisualTheme (org.apache.ofbiz.widget.renderer.VisualTheme)3 MacroFormRenderer (org.apache.ofbiz.widget.renderer.macro.MacroFormRenderer)3 Writer (java.io.Writer)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 Delegator (org.apache.ofbiz.entity.Delegator)2 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)2 GenericValue (org.apache.ofbiz.entity.GenericValue)2 ModelTheme (org.apache.ofbiz.widget.model.ModelTheme)2 FormStringRenderer (org.apache.ofbiz.widget.renderer.FormStringRenderer)2 ScreenRenderer (org.apache.ofbiz.widget.renderer.ScreenRenderer)2 ScreenStringRenderer (org.apache.ofbiz.widget.renderer.ScreenStringRenderer)2 MacroScreenRenderer (org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 Reader (java.io.Reader)1 StringReader (java.io.StringReader)1