Search in sources :

Example 1 with FormRenderer

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

Aggregations

TemplateException (freemarker.template.TemplateException)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 Timestamp (java.sql.Timestamp)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 TransformerException (javax.xml.transform.TransformerException)1 FileUploadException (org.apache.commons.fileupload.FileUploadException)1 GeneralException (org.apache.ofbiz.base.util.GeneralException)1 StringWrapper (org.apache.ofbiz.base.util.StringUtil.StringWrapper)1 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)1 GenericValue (org.apache.ofbiz.entity.GenericValue)1 ModelReader (org.apache.ofbiz.entity.model.ModelReader)1 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)1 ModelForm (org.apache.ofbiz.widget.model.ModelForm)1