Search in sources :

Example 6 with VisualTheme

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

the class MacroScreenViewHandler method render.

public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
    try {
        Writer writer = response.getWriter();
        VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
        ModelTheme modelTheme = visualTheme.getModelTheme();
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        // compress output if configured to do so
        if (UtilValidate.isEmpty(encoding)) {
            encoding = modelTheme.getEncoding(getName());
        }
        boolean compressOutput = "compressed".equals(encoding);
        if (!compressOutput) {
            compressOutput = "true".equals(modelTheme.getCompress(getName()));
        }
        if (!compressOutput && this.servletContext != null) {
            compressOutput = "true".equals(this.servletContext.getAttribute("compressHTML"));
        }
        if (compressOutput) {
            // StandardCompress defaults to a 2k buffer. That could be increased
            // to speed up output.
            writer = new StandardCompress().getWriter(writer, null);
        }
        MapStack<String> context = MapStack.create();
        ScreenRenderer.populateContextForRequest(context, null, request, response, servletContext);
        ScreenStringRenderer screenStringRenderer = loadRenderers(request, response, context, writer);
        ScreenRenderer screens = new ScreenRenderer(writer, context, screenStringRenderer);
        context.put("screens", screens);
        context.put("simpleEncoder", UtilCodec.getEncoder(visualTheme.getModelTheme().getEncoder(getName())));
        screenStringRenderer.renderScreenBegin(writer, context);
        screens.render(page);
        screenStringRenderer.renderScreenEnd(writer, context);
        writer.flush();
    } catch (TemplateException e) {
        Debug.logError(e, "Error initializing screen renderer", module);
        throw new ViewHandlerException(e.getMessage());
    } catch (IOException e) {
        throw new ViewHandlerException("Error in the response writer/output stream: " + e.toString(), e);
    } catch (SAXException | ParserConfigurationException e) {
        throw new ViewHandlerException("XML Error rendering page: " + e.toString(), e);
    } catch (GeneralException e) {
        throw new ViewHandlerException("Lower level error rendering page: " + e.toString(), e);
    }
}
Also used : ViewHandlerException(org.apache.ofbiz.webapp.view.ViewHandlerException) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) ScreenRenderer(org.apache.ofbiz.widget.renderer.ScreenRenderer) ModelTheme(org.apache.ofbiz.widget.model.ModelTheme) IOException(java.io.IOException) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) StandardCompress(freemarker.template.utility.StandardCompress) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Writer(java.io.Writer)

Example 7 with VisualTheme

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

the class EmailServices method sendMailFromScreen.

/**
 * JavaMail Service that gets body content from a Screen Widget
 * defined in the product store record and if available as attachment also.
 *@param dctx The DispatchContext that this service is operating in
 *@param rServiceContext Map containing the input parameters
 *@return Map with the result of the service, the output parameters
 */
public static Map<String, Object> sendMailFromScreen(DispatchContext dctx, Map<String, ? extends Object> rServiceContext) {
    Map<String, Object> serviceContext = UtilMisc.makeMapWritable(rServiceContext);
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String webSiteId = (String) serviceContext.remove("webSiteId");
    String bodyText = (String) serviceContext.remove("bodyText");
    String bodyScreenUri = (String) serviceContext.remove("bodyScreenUri");
    String xslfoAttachScreenLocationParam = (String) serviceContext.remove("xslfoAttachScreenLocation");
    String attachmentNameParam = (String) serviceContext.remove("attachmentName");
    List<String> xslfoAttachScreenLocationListParam = UtilGenerics.checkList(serviceContext.remove("xslfoAttachScreenLocationList"));
    List<String> attachmentNameListParam = UtilGenerics.checkList(serviceContext.remove("attachmentNameList"));
    VisualTheme visualTheme = (VisualTheme) rServiceContext.get("visualTheme");
    if (visualTheme == null) {
        visualTheme = ThemeFactory.resolveVisualTheme(null);
    }
    List<String> xslfoAttachScreenLocationList = new LinkedList<>();
    List<String> attachmentNameList = new LinkedList<>();
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationParam)) {
        xslfoAttachScreenLocationList.add(xslfoAttachScreenLocationParam);
    }
    if (UtilValidate.isNotEmpty(attachmentNameParam)) {
        attachmentNameList.add(attachmentNameParam);
    }
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationListParam)) {
        xslfoAttachScreenLocationList.addAll(xslfoAttachScreenLocationListParam);
    }
    if (UtilValidate.isNotEmpty(attachmentNameListParam)) {
        attachmentNameList.addAll(attachmentNameListParam);
    }
    List<String> attachmentTypeList = new LinkedList<>();
    String attachmentTypeParam = (String) serviceContext.remove("attachmentType");
    List<String> attachmentTypeListParam = UtilGenerics.checkList(serviceContext.remove("attachmentTypeList"));
    if (UtilValidate.isNotEmpty(attachmentTypeParam)) {
        attachmentTypeList.add(attachmentTypeParam);
    }
    if (UtilValidate.isNotEmpty(attachmentTypeListParam)) {
        attachmentTypeList.addAll(attachmentTypeListParam);
    }
    Locale locale = (Locale) serviceContext.get("locale");
    Map<String, Object> bodyParameters = UtilGenerics.checkMap(serviceContext.remove("bodyParameters"));
    if (bodyParameters == null) {
        bodyParameters = MapStack.create();
    }
    if (!bodyParameters.containsKey("locale")) {
        bodyParameters.put("locale", locale);
    } else {
        locale = (Locale) bodyParameters.get("locale");
    }
    String partyId = (String) serviceContext.get("partyId");
    if (partyId == null) {
        partyId = (String) bodyParameters.get("partyId");
    }
    String orderId = (String) bodyParameters.get("orderId");
    String returnId = (String) serviceContext.get("returnId");
    String custRequestId = (String) bodyParameters.get("custRequestId");
    bodyParameters.put("communicationEventId", serviceContext.get("communicationEventId"));
    NotificationServices.setBaseUrl(dctx.getDelegator(), webSiteId, bodyParameters);
    String contentType = (String) serviceContext.remove("contentType");
    StringWriter bodyWriter = new StringWriter();
    MapStack<String> screenContext = MapStack.create();
    screenContext.put("locale", locale);
    ScreenStringRenderer screenStringRenderer = null;
    try {
        screenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme(), "screen");
    } catch (TemplateException | IOException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    ScreenRenderer screens = new ScreenRenderer(bodyWriter, screenContext, screenStringRenderer);
    screens.populateContextForService(dctx, bodyParameters);
    screenContext.putAll(bodyParameters);
    if (bodyScreenUri != null) {
        try {
            screens.render(bodyScreenUri);
        } catch (GeneralException | IOException | SAXException | ParserConfigurationException e) {
            Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale));
        }
    }
    boolean isMultiPart = false;
    // check if attachment screen location passed in
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationList)) {
        List<Map<String, ? extends Object>> bodyParts = new LinkedList<Map<String, ? extends Object>>();
        if (bodyText != null) {
            bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
            bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyText, "type", UtilValidate.isNotEmpty(contentType) ? contentType : "text/html"));
        } else {
            bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyWriter.toString(), "type", UtilValidate.isNotEmpty(contentType) ? contentType : "text/html"));
        }
        for (int i = 0; i < xslfoAttachScreenLocationList.size(); i++) {
            String xslfoAttachScreenLocation = xslfoAttachScreenLocationList.get(i);
            String attachmentName = "Details.pdf";
            if (UtilValidate.isNotEmpty(attachmentNameList) && attachmentNameList.size() >= i) {
                attachmentName = attachmentNameList.get(i);
            }
            String attachmentType = MimeConstants.MIME_PDF;
            if (UtilValidate.isNotEmpty(attachmentTypeList) && attachmentTypeList.size() >= i) {
                attachmentType = attachmentTypeList.get(i);
            }
            isMultiPart = true;
            // start processing fo pdf attachment
            try {
                Writer writer = new StringWriter();
                // substitute the freemarker variables...
                ScreenStringRenderer foScreenStringRenderer = null;
                if (MimeConstants.MIME_PLAIN_TEXT.equals(attachmentType)) {
                    foScreenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme(), "screentext");
                } else {
                    foScreenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme(), "screenfop");
                }
                ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContext, foScreenStringRenderer);
                screensAtt.populateContextForService(dctx, bodyParameters);
                screensAtt.render(xslfoAttachScreenLocation);
                // create the output stream for the generation
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                if (MimeConstants.MIME_PLAIN_TEXT.equals(attachmentType)) {
                    baos.write(writer.toString().getBytes("UTF-8"));
                } else {
                    // create the input stream for the generation
                    StreamSource src = new StreamSource(new StringReader(writer.toString()));
                    Fop fop = ApacheFopWorker.createFopInstance(baos, attachmentType);
                    ApacheFopWorker.transform(src, null, fop);
                }
                // and generate the attachment
                baos.flush();
                baos.close();
                // store in the list of maps for sendmail....
                bodyParts.add(UtilMisc.<String, Object>toMap("content", baos.toByteArray(), "type", attachmentType, "filename", attachmentName));
            } catch (GeneralException | IOException | SAXException | ParserConfigurationException | TemplateException ge) {
                Debug.logError(ge, "Error rendering PDF attachment for email: " + ge.toString(), module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendRenderingScreenPdfError", UtilMisc.toMap("errorString", ge.toString()), locale));
            }
            serviceContext.put("bodyParts", bodyParts);
        }
    } else {
        isMultiPart = false;
        // store body and type for single part message in the context.
        if (bodyText != null) {
            bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
            serviceContext.put("body", bodyText);
        } else {
            serviceContext.put("body", bodyWriter.toString());
        }
        // and would require specific handling.
        if (contentType != null && contentType.equalsIgnoreCase("text/plain")) {
            serviceContext.put("contentType", "text/plain");
        } else {
            serviceContext.put("contentType", "text/html");
        }
    }
    // also expand the subject at this point, just in case it has the FlexibleStringExpander syntax in it...
    String subject = (String) serviceContext.remove("subject");
    subject = FlexibleStringExpander.expandString(subject, screenContext, locale);
    if (Debug.infoOn()) {
        Debug.logInfo("Expanded email subject to: " + subject, module);
    }
    serviceContext.put("subject", subject);
    serviceContext.put("partyId", partyId);
    if (UtilValidate.isNotEmpty(orderId)) {
        serviceContext.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(returnId)) {
        serviceContext.put("returnId", returnId);
    }
    if (UtilValidate.isNotEmpty(custRequestId)) {
        serviceContext.put("custRequestId", custRequestId);
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("sendMailFromScreen sendMail context: " + serviceContext, module);
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, Object> sendMailResult;
    Boolean hideInLog = (Boolean) serviceContext.get("hideInLog");
    try {
        if (!Boolean.TRUE.equals(hideInLog)) {
            if (isMultiPart) {
                sendMailResult = dispatcher.runSync("sendMailMultiPart", serviceContext);
            } else {
                sendMailResult = dispatcher.runSync("sendMail", serviceContext);
            }
        } else {
            if (isMultiPart) {
                sendMailResult = dispatcher.runSync("sendMailMultiPartHiddenInLog", serviceContext);
            } else {
                sendMailResult = dispatcher.runSync("sendMailHiddenInLog", serviceContext);
            }
        }
    } catch (Exception e) {
        Debug.logError(e, "Error send email:" + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonEmailSendError", UtilMisc.toMap("errorString", e.toString()), locale));
    }
    if (ServiceUtil.isError(sendMailResult)) {
        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(sendMailResult));
    }
    result.put("messageWrapper", sendMailResult.get("messageWrapper"));
    result.put("body", bodyWriter.toString());
    result.put("subject", subject);
    result.put("communicationEventId", sendMailResult.get("communicationEventId"));
    if (UtilValidate.isNotEmpty(orderId)) {
        result.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(returnId)) {
        result.put("returnId", returnId);
    }
    if (UtilValidate.isNotEmpty(custRequestId)) {
        result.put("custRequestId", custRequestId);
    }
    return result;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) 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) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) LinkedList(java.util.LinkedList) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) MessagingException(javax.mail.MessagingException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) SendFailedException(javax.mail.SendFailedException) SAXException(org.xml.sax.SAXException) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) SMTPAddressFailedException(com.sun.mail.smtp.SMTPAddressFailedException) HttpClientException(org.apache.ofbiz.base.util.HttpClientException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) Writer(java.io.Writer) StringWriter(java.io.StringWriter)

Example 8 with VisualTheme

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

the class ThemeFactory method getVisualThemeFromId.

/**
 * From a visualThemeId return the VisualTheme object corresponding in cache
 * If it's empty, reload the cache from all Theme definition
 * @param visualThemeId
 * @return
 */
public static VisualTheme getVisualThemeFromId(String visualThemeId) {
    if (visualThemeId == null) {
        return null;
    }
    VisualTheme visualTheme = themeVisualThemeIdCache.get(visualThemeId);
    if (visualTheme == null) {
        synchronized (ThemeFactory.class) {
            visualTheme = themeVisualThemeIdCache.get(visualThemeId);
            if (visualTheme == null) {
                pullModelThemesFromXmlToCache();
            }
            visualTheme = themeVisualThemeIdCache.get(visualThemeId);
            if (visualTheme == null) {
                Debug.logError("Impossible to resolve the modelTheme for the visualThemeId " + visualThemeId + ", Common is returned", module);
                return themeVisualThemeIdCache.get("COMMON");
            }
        }
    }
    return visualTheme;
}
Also used : VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme)

Example 9 with VisualTheme

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

the class ServiceEventHandler method invoke.

/**
 * @see org.apache.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
public String invoke(Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response) throws EventHandlerException {
    // make sure we have a valid reference to the Service Engine
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    if (dispatcher == null) {
        throw new EventHandlerException("The local service dispatcher is null");
    }
    DispatchContext dctx = dispatcher.getDispatchContext();
    if (dctx == null) {
        throw new EventHandlerException("Dispatch context cannot be found");
    }
    // get the details for the service(s) to call
    String mode = SYNC;
    String serviceName = null;
    if (UtilValidate.isEmpty(event.path)) {
        mode = SYNC;
    } else {
        mode = event.path;
    }
    // make sure we have a defined service to call
    serviceName = event.invoke;
    if (serviceName == null) {
        throw new EventHandlerException("Service name (eventMethod) cannot be null");
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Set mode/service]: " + mode + "/" + serviceName, module);
    // some needed info for when running the service
    Locale locale = UtilHttp.getLocale(request);
    TimeZone timeZone = UtilHttp.getTimeZone(request);
    VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    // get the service model to generate context
    ModelService model = null;
    try {
        model = dctx.getModelService(serviceName);
    } catch (GenericServiceException e) {
        throw new EventHandlerException("Problems getting the service model", e);
    }
    if (model == null) {
        throw new EventHandlerException("Problems getting the service model");
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("[Processing]: SERVICE Event", module);
        Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module);
    }
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> multiPartMap = new HashMap<String, Object>();
    if (isMultiPart) {
        // get the http upload configuration
        String maxSizeStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.size", "-1", dctx.getDelegator());
        long maxUploadSize = -1;
        try {
            maxUploadSize = Long.parseLong(maxSizeStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1", module);
            maxUploadSize = -1;
        }
        // get the http size threshold configuration - files bigger than this will be
        // temporarly stored on disk during upload
        String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.sizethreshold", "10240", dctx.getDelegator());
        // 10K
        int sizeThreshold = 10240;
        try {
            sizeThreshold = Integer.parseInt(sizeThresholdStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K", module);
            sizeThreshold = -1;
        }
        // directory used to temporarily store files that are larger than the configured size threshold
        String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general", "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator());
        String encoding = request.getCharacterEncoding();
        // check for multipart content types which may have uploaded items
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));
        // create the progress listener and add it to the session
        FileUploadProgressListener listener = new FileUploadProgressListener();
        upload.setProgressListener(listener);
        session.setAttribute("uploadProgressListener", listener);
        if (encoding != null) {
            upload.setHeaderEncoding(encoding);
        }
        upload.setSizeMax(maxUploadSize);
        List<FileItem> uploadedItems = null;
        try {
            uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
        } catch (FileUploadException e) {
            throw new EventHandlerException("Problems reading uploaded data", e);
        }
        if (uploadedItems != null) {
            for (FileItem item : uploadedItems) {
                String fieldName = item.getFieldName();
                /*
                    Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " +
                            item.getContentType() + " FF: " + item.isFormField(), module);
                    */
                if (item.isFormField() || item.getName() == null) {
                    if (multiPartMap.containsKey(fieldName)) {
                        Object mapValue = multiPartMap.get(fieldName);
                        if (mapValue instanceof List<?>) {
                            checkList(mapValue, Object.class).add(item.getString());
                        } else if (mapValue instanceof String) {
                            List<String> newList = new LinkedList<String>();
                            newList.add((String) mapValue);
                            newList.add(item.getString());
                            multiPartMap.put(fieldName, newList);
                        } else {
                            Debug.logWarning("Form field found [" + fieldName + "] which was not handled!", module);
                        }
                    } else {
                        if (encoding != null) {
                            try {
                                multiPartMap.put(fieldName, item.getString(encoding));
                            } catch (java.io.UnsupportedEncodingException uee) {
                                Debug.logError(uee, "Unsupported Encoding, using deafault", module);
                                multiPartMap.put(fieldName, item.getString());
                            }
                        } else {
                            multiPartMap.put(fieldName, item.getString());
                        }
                    }
                } else {
                    String fileName = item.getName();
                    if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
                        // get just the file name IE and other browsers also pass in the local path
                        int lastIndex = fileName.lastIndexOf('\\');
                        if (lastIndex == -1) {
                            lastIndex = fileName.lastIndexOf('/');
                        }
                        if (lastIndex > -1) {
                            fileName = fileName.substring(lastIndex + 1);
                        }
                    }
                    multiPartMap.put(fieldName, ByteBuffer.wrap(item.get()));
                    multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize()));
                    multiPartMap.put("_" + fieldName + "_fileName", fileName);
                    multiPartMap.put("_" + fieldName + "_contentType", item.getContentType());
                }
            }
        }
    }
    // store the multi-part map as an attribute so we can access the parameters
    request.setAttribute("multiPartMap", multiPartMap);
    Map<String, Object> rawParametersMap = UtilHttp.getCombinedMap(request);
    Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();
    // we have a service and the model; build the context
    Map<String, Object> serviceContext = new HashMap<String, Object>();
    for (ModelParam modelParam : model.getInModelParamList()) {
        String name = modelParam.name;
        // don't include userLogin, that's taken care of below
        if ("userLogin".equals(name))
            continue;
        // don't include locale, that is also taken care of below
        if ("locale".equals(name))
            continue;
        // don't include timeZone, that is also taken care of below
        if ("timeZone".equals(name))
            continue;
        // don't include theme, that is also taken care of below
        if ("visualTheme".equals(name))
            continue;
        Object value = null;
        if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) {
            Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap, modelParam.stringMapPrefix, null);
            value = paramMap;
            if (Debug.verboseOn())
                Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module);
        } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) {
            List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap, modelParam.stringListSuffix, null);
            value = paramList;
        } else {
            // first check the multi-part map
            value = multiPartMap.get(name);
            // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request.getAttribute(UtilValidate.isEmpty(modelParam.requestAttributeName) ? name : modelParam.requestAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }
            // check the request parameters
            if (UtilValidate.isEmpty(value)) {
                ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session, serviceName, dctx.getDelegator());
                // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up
                if ("any".equals(modelParam.allowHtml)) {
                    value = request.getParameter(name);
                } else {
                    // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc
                    value = rawParametersMap.get(name);
                }
                // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes})
                if (value == null) {
                    value = UtilHttp.makeParamValueFromComposite(request, name, locale);
                }
            }
            // then session
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request.getSession().getAttribute(UtilValidate.isEmpty(modelParam.sessionAttributeName) ? name : modelParam.sessionAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }
            // no field found
            if (value == null) {
                // still null, give up for this one
                continue;
            }
            if (value instanceof String && ((String) value).length() == 0) {
                // interpreting empty fields as null values for each in back end handling...
                value = null;
            }
        }
        // set even if null so that values will get nulled in the db later on
        serviceContext.put(name, value);
    }
    // get only the parameters for this service - converted to proper type
    // TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any
    List<Object> errorMessages = new LinkedList<Object>();
    serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone, locale);
    if (errorMessages.size() > 0) {
        // uh-oh, had some problems...
        request.setAttribute("_ERROR_MESSAGE_LIST_", errorMessages);
        return "error";
    }
    // include the UserLogin value object
    if (userLogin != null) {
        serviceContext.put("userLogin", userLogin);
    }
    // include the Locale object
    if (locale != null) {
        serviceContext.put("locale", locale);
    }
    // include the TimeZone object
    if (timeZone != null) {
        serviceContext.put("timeZone", timeZone);
    }
    // include the Theme object
    if (visualTheme != null) {
        serviceContext.put("visualTheme", visualTheme);
    }
    // invoke the service
    Map<String, Object> result = null;
    try {
        if (ASYNC.equalsIgnoreCase(mode)) {
            dispatcher.runAsync(serviceName, serviceContext);
        } else {
            result = dispatcher.runSync(serviceName, serviceContext);
        }
    } catch (ServiceAuthException e) {
        // not logging since the service engine already did
        request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        return "error";
    } catch (ServiceValidationException e) {
        // not logging since the service engine already did
        request.setAttribute("serviceValidationException", e);
        if (e.getMessageList() != null) {
            request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList());
        } else {
            request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        }
        return "error";
    } catch (GenericServiceException e) {
        Debug.logError(e, "Service invocation error", module);
        throw new EventHandlerException("Service invocation error", e.getNested());
    }
    String responseString = null;
    if (result == null) {
        responseString = ModelService.RESPOND_SUCCESS;
    } else {
        if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) {
            responseString = ModelService.RESPOND_SUCCESS;
        } else {
            responseString = (String) result.get(ModelService.RESPONSE_MESSAGE);
        }
        // set the messages in the request; this will be picked up by messages.ftl and displayed
        request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST));
        request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP));
        request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE));
        request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST));
        request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE));
        // set the results in the request
        for (Map.Entry<String, Object> rme : result.entrySet()) {
            String resultKey = rme.getKey();
            Object resultValue = rme.getValue();
            if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey) && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey) && !ModelService.SUCCESS_MESSAGE.equals(resultKey) && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) {
                request.setAttribute(resultKey, resultValue);
            }
        }
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Event Return]: " + responseString, module);
    return responseString;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) DispatchContext(org.apache.ofbiz.service.DispatchContext) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) UtilGenerics.checkList(org.apache.ofbiz.base.util.UtilGenerics.checkList) LinkedList(java.util.LinkedList) List(java.util.List) GenericValue(org.apache.ofbiz.entity.GenericValue) ServiceAuthException(org.apache.ofbiz.service.ServiceAuthException) ServiceValidationException(org.apache.ofbiz.service.ServiceValidationException) HttpSession(javax.servlet.http.HttpSession) ModelParam(org.apache.ofbiz.service.ModelParam) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) LinkedList(java.util.LinkedList) ModelService(org.apache.ofbiz.service.ModelService) FileItem(org.apache.commons.fileupload.FileItem) TimeZone(java.util.TimeZone) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) RequestMap(org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 10 with VisualTheme

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

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