Search in sources :

Example 1 with ModelScreen

use of org.apache.ofbiz.widget.model.ModelScreen in project ofbiz-framework by apache.

the class ArtifactInfoFactory method prepareTaskForComponentAnalysis.

private Callable<Void> prepareTaskForComponentAnalysis(final ComponentConfig componentConfig) {
    return new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            String componentName = componentConfig.getGlobalName();
            String rootComponentPath = componentConfig.getRootLocation();
            List<File> screenFiles = new ArrayList<File>();
            List<File> formFiles = new ArrayList<File>();
            List<File> controllerFiles = new ArrayList<File>();
            try {
                screenFiles = FileUtil.findXmlFiles(rootComponentPath, null, "screens", "widget-screen.xsd");
            } catch (IOException ioe) {
                Debug.logWarning(ioe.getMessage(), module);
            }
            try {
                formFiles = FileUtil.findXmlFiles(rootComponentPath, null, "forms", "widget-form.xsd");
            } catch (IOException ioe) {
                Debug.logWarning(ioe.getMessage(), module);
            }
            try {
                controllerFiles = FileUtil.findXmlFiles(rootComponentPath, null, "site-conf", "site-conf.xsd");
            } catch (IOException ioe) {
                Debug.logWarning(ioe.getMessage(), module);
            }
            for (File screenFile : screenFiles) {
                String screenFilePath = screenFile.getAbsolutePath();
                screenFilePath = screenFilePath.replace('\\', '/');
                String screenFileRelativePath = screenFilePath.substring(rootComponentPath.length());
                String screenLocation = "component://" + componentName + "/" + screenFileRelativePath;
                Map<String, ModelScreen> modelScreenMap = null;
                try {
                    modelScreenMap = ScreenFactory.getScreensFromLocation(screenLocation);
                } catch (Exception exc) {
                    Debug.logWarning(exc.getMessage(), module);
                }
                for (String screenName : modelScreenMap.keySet()) {
                    getScreenWidgetArtifactInfo(screenName, screenLocation);
                }
            }
            for (File formFile : formFiles) {
                String formFilePath = formFile.getAbsolutePath();
                formFilePath = formFilePath.replace('\\', '/');
                String formFileRelativePath = formFilePath.substring(rootComponentPath.length());
                String formLocation = "component://" + componentName + "/" + formFileRelativePath;
                Map<String, ModelForm> modelFormMap = null;
                try {
                    modelFormMap = FormFactory.getFormsFromLocation(formLocation, getEntityModelReader(), getDispatchContext());
                } catch (Exception exc) {
                    Debug.logWarning(exc.getMessage(), module);
                }
                for (String formName : modelFormMap.keySet()) {
                    try {
                        getFormWidgetArtifactInfo(formName, formLocation);
                    } catch (GeneralException ge) {
                        Debug.logWarning(ge.getMessage(), module);
                    }
                }
            }
            for (File controllerFile : controllerFiles) {
                URL controllerUrl = null;
                try {
                    controllerUrl = controllerFile.toURI().toURL();
                } catch (MalformedURLException mue) {
                    Debug.logWarning(mue.getMessage(), module);
                }
                if (controllerUrl == null)
                    continue;
                ControllerConfig cc = ConfigXMLReader.getControllerConfig(controllerUrl);
                for (String requestUri : cc.getRequestMapMap().keySet()) {
                    try {
                        getControllerRequestArtifactInfo(controllerUrl, requestUri);
                    } catch (GeneralException e) {
                        Debug.logWarning(e.getMessage(), module);
                    }
                }
                for (String viewUri : cc.getViewMapMap().keySet()) {
                    try {
                        getControllerViewArtifactInfo(controllerUrl, viewUri);
                    } catch (GeneralException e) {
                        Debug.logWarning(e.getMessage(), module);
                    }
                }
            }
            return null;
        }
    };
}
Also used : MalformedURLException(java.net.MalformedURLException) ControllerConfig(org.apache.ofbiz.webapp.control.ConfigXMLReader.ControllerConfig) GeneralException(org.apache.ofbiz.base.util.GeneralException) ArrayList(java.util.ArrayList) ModelScreen(org.apache.ofbiz.widget.model.ModelScreen) IOException(java.io.IOException) Callable(java.util.concurrent.Callable) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) WebAppConfigurationException(org.apache.ofbiz.webapp.control.WebAppConfigurationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) URL(java.net.URL) File(java.io.File) ModelForm(org.apache.ofbiz.widget.model.ModelForm)

Example 2 with ModelScreen

use of org.apache.ofbiz.widget.model.ModelScreen 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 ModelScreen

use of org.apache.ofbiz.widget.model.ModelScreen in project ofbiz-framework by apache.

the class MacroScreenRenderer method renderPortalPagePortletBody.

public void renderPortalPagePortletBody(Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage, GenericValue portalPortlet) throws GeneralException, IOException {
    String portalPortletId = portalPortlet.getString("portalPortletId");
    String screenName = portalPortlet.getString("screenName");
    String screenLocation = portalPortlet.getString("screenLocation");
    ModelScreen modelScreen = null;
    if (UtilValidate.isNotEmpty(screenName) && UtilValidate.isNotEmpty(screenLocation)) {
        try {
            modelScreen = ScreenFactory.getScreenFromLocation(screenLocation, screenName);
        } catch (IOException | SAXException | ParserConfigurationException e) {
            String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString();
            Debug.logError(e, errMsg, module);
            throw new RuntimeException(errMsg);
        }
    }
    if (writer != null && context != null) {
        modelScreen.renderScreenString(writer, context, this);
    } else {
        Debug.logError("Null on some Path: writer" + writer + ", context: " + context, module);
    }
}
Also used : ModelScreen(org.apache.ofbiz.widget.model.ModelScreen) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 4 with ModelScreen

use of org.apache.ofbiz.widget.model.ModelScreen in project ofbiz-framework by apache.

the class ScreenRenderer method render.

/**
 * Renders the named screen using the render environment configured when this ScreenRenderer was created.
 *
 * @param resourceName The name/location of the resource to use, can use "component://[component-name]/" and "ofbiz://" and other special OFBiz style URLs
 * @param screenName The name of the screen within the XML file specified by the resourceName.
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 */
public String render(String resourceName, String screenName) throws GeneralException, IOException, SAXException, ParserConfigurationException {
    ModelScreen modelScreen = ScreenFactory.getScreenFromLocation(resourceName, screenName);
    if (modelScreen.getUseCache()) {
        // if in the screen definition use-cache is set to true
        // then try to get an already built screen output from the cache:
        // 1) if we find it then we get it and attach it to the passed in writer
        // 2) if we can't find one, we create a new StringWriter,
        // and pass it to the renderScreenString;
        // then we wrap its content and put it in the cache;
        // and we attach it to the passed in writer
        WidgetContextCacheKey wcck = new WidgetContextCacheKey(context);
        String screenCombinedName = resourceName + ":" + screenName;
        ScreenCache screenCache = new ScreenCache();
        GenericWidgetOutput gwo = screenCache.get(screenCombinedName, wcck);
        if (gwo == null) {
            Writer sw = new StringWriter();
            modelScreen.renderScreenString(sw, context, screenStringRenderer);
            gwo = new GenericWidgetOutput(sw.toString());
            screenCache.put(screenCombinedName, wcck, gwo);
            writer.append(gwo.toString());
        } else {
            writer.append(gwo.toString());
        }
    } else {
        context.put("renderFormSeqNumber", String.valueOf(renderFormSeqNumber));
        modelScreen.renderScreenString(writer, context, screenStringRenderer);
    }
    return "";
}
Also used : WidgetContextCacheKey(org.apache.ofbiz.widget.cache.WidgetContextCacheKey) ScreenCache(org.apache.ofbiz.widget.cache.ScreenCache) StringWriter(java.io.StringWriter) ModelScreen(org.apache.ofbiz.widget.model.ModelScreen) GenericWidgetOutput(org.apache.ofbiz.widget.cache.GenericWidgetOutput) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Aggregations

ModelScreen (org.apache.ofbiz.widget.model.ModelScreen)4 IOException (java.io.IOException)3 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)3 SAXException (org.xml.sax.SAXException)3 File (java.io.File)2 GeneralException (org.apache.ofbiz.base.util.GeneralException)2 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)2 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)2 ModelForm (org.apache.ofbiz.widget.model.ModelForm)2 TemplateException (freemarker.template.TemplateException)1 FileNotFoundException (java.io.FileNotFoundException)1 StringWriter (java.io.StringWriter)1 Writer (java.io.Writer)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 Timestamp (java.sql.Timestamp)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1