Search in sources :

Example 1 with ScreenStringRenderer

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

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

the class ScreenFopViewHandler method renderError.

protected void renderError(String msg, Exception e, String screenOutString, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
    Debug.logError(msg + ": " + e + "; Screen XSL:FO text was:\n" + screenOutString, module);
    try {
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        Writer writer = new StringWriter();
        VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
        ModelTheme modelTheme = visualTheme.getModelTheme();
        ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(modelTheme.getType("screen"), modelTheme.getScreenRendererLocation("screen"));
        ScreenRenderer screens = new ScreenRenderer(writer, null, screenStringRenderer);
        screens.populateContextForRequest(request, response, servletContext);
        screens.getContext().put("errorMessage", msg + ": " + e);
        screens.render(DEFAULT_ERROR_TEMPLATE);
        response.setContentType("text/html");
        response.getWriter().write(writer.toString());
        writer.close();
    } catch (IOException | GeneralException | SAXException | ParserConfigurationException | TemplateException x) {
        Debug.logError("Multiple errors rendering FOP", module);
        throw new ViewHandlerException("Multiple errors rendering FOP", x);
    }
}
Also used : ViewHandlerException(org.apache.ofbiz.webapp.view.ViewHandlerException) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) 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) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) SAXException(org.xml.sax.SAXException) Delegator(org.apache.ofbiz.entity.Delegator) StringWriter(java.io.StringWriter) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 3 with ScreenStringRenderer

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

the class MacroScreenViewHandler method loadRenderers.

private ScreenStringRenderer loadRenderers(HttpServletRequest request, HttpServletResponse response, Map<String, Object> context, Writer writer) throws TemplateException, IOException {
    VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
    ModelTheme modelTheme = visualTheme.getModelTheme();
    String screenMacroLibraryPath = modelTheme.getScreenRendererLocation(getName());
    String formMacroLibraryPath = modelTheme.getFormRendererLocation(getName());
    String treeMacroLibraryPath = modelTheme.getTreeRendererLocation(getName());
    String menuMacroLibraryPath = modelTheme.getMenuRendererLocation(getName());
    ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(modelTheme.getType(getName()), screenMacroLibraryPath);
    if (UtilValidate.isNotEmpty(formMacroLibraryPath)) {
        FormStringRenderer formStringRenderer = new MacroFormRenderer(formMacroLibraryPath, request, response);
        context.put("formStringRenderer", formStringRenderer);
    }
    if (UtilValidate.isNotEmpty(treeMacroLibraryPath)) {
        TreeStringRenderer treeStringRenderer = new MacroTreeRenderer(treeMacroLibraryPath, writer);
        context.put("treeStringRenderer", treeStringRenderer);
    }
    if (UtilValidate.isNotEmpty(menuMacroLibraryPath)) {
        MenuStringRenderer menuStringRenderer = new MacroMenuRenderer(menuMacroLibraryPath, request, response);
        context.put("menuStringRenderer", menuStringRenderer);
    }
    return screenStringRenderer;
}
Also used : TreeStringRenderer(org.apache.ofbiz.widget.renderer.TreeStringRenderer) FormStringRenderer(org.apache.ofbiz.widget.renderer.FormStringRenderer) ModelTheme(org.apache.ofbiz.widget.model.ModelTheme) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) MenuStringRenderer(org.apache.ofbiz.widget.renderer.MenuStringRenderer)

Example 4 with ScreenStringRenderer

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

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

Aggregations

ScreenStringRenderer (org.apache.ofbiz.widget.renderer.ScreenStringRenderer)9 VisualTheme (org.apache.ofbiz.widget.renderer.VisualTheme)9 GeneralException (org.apache.ofbiz.base.util.GeneralException)8 ScreenRenderer (org.apache.ofbiz.widget.renderer.ScreenRenderer)8 TemplateException (freemarker.template.TemplateException)7 IOException (java.io.IOException)7 Writer (java.io.Writer)7 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)7 MacroScreenRenderer (org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer)7 SAXException (org.xml.sax.SAXException)7 StringWriter (java.io.StringWriter)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 StringReader (java.io.StringReader)4 StreamSource (javax.xml.transform.stream.StreamSource)4 Fop (org.apache.fop.apps.Fop)4 ModelTheme (org.apache.ofbiz.widget.model.ModelTheme)4 Locale (java.util.Locale)3 Delegator (org.apache.ofbiz.entity.Delegator)3 ViewHandlerException (org.apache.ofbiz.webapp.view.ViewHandlerException)3 File (java.io.File)2