PageRenderTime 1ms CodeModel.GetById 31ms app.highlight 36ms RepoModel.GetById 10ms app.codeStats 0ms

/framework/birt/src/org/ofbiz/birt/email/BirtEmailServices.java

https://github.com/thanhvc/ofbiz
Java | 255 lines | 201 code | 21 blank | 33 comment | 31 complexity | c7f7e18677babf4301c2a683f12a23f0 MD5 | raw file
  1/*******************************************************************************
  2 * Licensed to the Apache Software Foundation (ASF) under one
  3 * or more contributor license agreements.  See the NOTICE file
  4 * distributed with this work for additional information
  5 * regarding copyright ownership.  The ASF licenses this file
  6 * to you under the Apache License, Version 2.0 (the
  7 * "License"); you may not use this file except in compliance
  8 * with the License.  You may obtain a copy of the License at
  9 *
 10 * http://www.apache.org/licenses/LICENSE-2.0
 11 *
 12 * Unless required by applicable law or agreed to in writing,
 13 * software distributed under the License is distributed on an
 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 15 * KIND, either express or implied.  See the License for the
 16 * specific language governing permissions and limitations
 17 * under the License.
 18 *******************************************************************************/
 19package org.ofbiz.birt.email;
 20
 21import java.io.ByteArrayOutputStream;
 22import java.io.IOException;
 23import java.io.InputStream;
 24import java.io.StringWriter;
 25import java.sql.SQLException;
 26import java.util.HashMap;
 27import java.util.List;
 28import java.util.Locale;
 29import java.util.Map;
 30
 31import javax.xml.parsers.ParserConfigurationException;
 32
 33import javolution.util.FastList;
 34import javolution.util.FastMap;
 35
 36import org.apache.fop.apps.FOPException;
 37import org.eclipse.birt.report.engine.api.EngineException;
 38import org.eclipse.birt.report.engine.api.IReportEngine;
 39import org.eclipse.birt.report.engine.api.IReportRunnable;
 40import org.ofbiz.base.util.Debug;
 41import org.ofbiz.base.util.GeneralException;
 42import org.ofbiz.base.util.UtilGenerics;
 43import org.ofbiz.base.util.UtilMisc;
 44import org.ofbiz.base.util.UtilValidate;
 45import org.ofbiz.base.util.collections.MapStack;
 46import org.ofbiz.base.util.string.FlexibleStringExpander;
 47import org.ofbiz.birt.BirtWorker;
 48import org.ofbiz.birt.container.BirtContainer;
 49import org.ofbiz.common.email.NotificationServices;
 50import org.ofbiz.entity.Delegator;
 51import org.ofbiz.security.Security;
 52import org.ofbiz.service.DispatchContext;
 53import org.ofbiz.service.LocalDispatcher;
 54import org.ofbiz.service.ServiceUtil;
 55import org.ofbiz.birt.widget.BirtFactory;
 56import org.ofbiz.widget.html.HtmlScreenRenderer;
 57import org.ofbiz.widget.screen.ScreenRenderer;
 58import org.xml.sax.SAXException;
 59
 60public class BirtEmailServices {
 61
 62    public static final String module = BirtEmailServices.class.getName();
 63
 64    protected static final HtmlScreenRenderer htmlScreenRenderer = new HtmlScreenRenderer();
 65
 66    /**
 67     * send birt mail
 68     *
 69     * @param ctx the dispatch context
 70     * @param context the context
 71     * @return returns the result of the service execution
 72     */
 73    public static Map<String, Object> sendBirtMail(DispatchContext ctx, Map<String, ? extends Object> context) {
 74        Map<String, Object> serviceContext = UtilMisc.makeMapWritable(context);
 75        Delegator delegator = ctx.getDelegator();
 76        LocalDispatcher dispatcher = ctx.getDispatcher();
 77        Security security = ctx.getSecurity();
 78        
 79        String webSiteId = (String) serviceContext.remove("webSiteId");
 80        String bodyText = (String) serviceContext.remove("bodyText");
 81        String bodyScreenUri = (String) serviceContext.remove("bodyScreenUri");
 82        String birtReportLocation = (String) serviceContext.remove("birtReportLocation");
 83        String attachmentName = (String) serviceContext.remove("attachmentName");
 84        Locale locale = (Locale) serviceContext.get("locale");
 85        Map<String, Object> bodyParameters = UtilGenerics.cast(serviceContext.remove("bodyParameters"));
 86        Locale birtLocale = (Locale) serviceContext.remove(BirtWorker.BIRT_LOCALE);
 87        Map<String, Object> birtParameters = UtilGenerics.cast(serviceContext.remove(BirtWorker.BIRT_PARAMETERS));
 88        String birtImageDirectory = (String) serviceContext.remove(BirtWorker.BIRT_IMAGE_DIRECTORY);
 89        String birtContentType = (String) serviceContext.remove(BirtWorker.BIRT_CONTENT_TYPE);
 90        if (bodyParameters == null) {
 91            bodyParameters = MapStack.create();
 92        }
 93        if (!bodyParameters.containsKey("locale")) {
 94            bodyParameters.put("locale", locale);
 95        } else {
 96            locale = (Locale) bodyParameters.get("locale");
 97        }
 98        String partyId = (String) bodyParameters.get("partyId");
 99        if (UtilValidate.isNotEmpty(webSiteId)) {
100            NotificationServices.setBaseUrl(ctx.getDelegator(), webSiteId, bodyParameters);
101        }
102        String contentType = (String) serviceContext.remove("contentType");
103
104        if (UtilValidate.isEmpty(attachmentName)) {
105            attachmentName = "Details.pdf";
106        }
107        StringWriter bodyWriter = new StringWriter();
108
109        MapStack<String> screenContext = MapStack.create();
110        screenContext.put("locale", locale);
111        ScreenRenderer screens = new ScreenRenderer(bodyWriter, screenContext, htmlScreenRenderer);
112        screens.populateContextForService(ctx, bodyParameters);
113        screenContext.putAll(bodyParameters);
114
115        if (bodyScreenUri != null) {
116            try {
117                screens.render(bodyScreenUri);
118            } catch (GeneralException e) {
119                String errMsg = "Error rendering screen for email: " + e.toString();
120                Debug.logError(e, errMsg, module);
121                return ServiceUtil.returnError(errMsg);
122            } catch (IOException e) {
123                String errMsg = "Error I/O rendering screen for email: " + e.toString();
124                Debug.logError(e, errMsg, module);
125                return ServiceUtil.returnError(errMsg);
126            } catch (SAXException e) {
127                String errMsg = "Error SAX rendering screen for email: " + e.toString();
128                Debug.logError(e, errMsg, module);
129                return ServiceUtil.returnError(errMsg);
130            } catch (ParserConfigurationException e) {
131                String errMsg = "Error parser config rendering screen for email: " + e.toString();
132                Debug.logError(e, errMsg, module);
133                return ServiceUtil.returnError(errMsg);
134            }
135        }
136
137        boolean isMultiPart = false;
138
139        // check if attachment screen location passed in
140        if (UtilValidate.isNotEmpty(birtReportLocation)) {
141            isMultiPart = true;
142            // start processing fo pdf attachment
143            try {
144                // create the output stream for the generation
145                ByteArrayOutputStream baos = new ByteArrayOutputStream();
146
147                Map<String, Object> birtContext = FastMap.newInstance();
148                if (birtLocale == null) {
149                    birtLocale = locale;
150                }
151                birtContext.put(BirtWorker.BIRT_LOCALE, birtLocale);
152                if (birtParameters != null) {
153                    birtContext.put(BirtWorker.BIRT_PARAMETERS, birtParameters);
154                }
155                if (birtImageDirectory != null) {
156                    birtContext.put(BirtWorker.BIRT_IMAGE_DIRECTORY, birtImageDirectory);
157                }
158                if (birtContentType == null) {
159                    birtContentType = "application/pdf";
160                }
161                IReportEngine engine = BirtContainer.getReportEngine();
162                HashMap<String, Object> appContext = UtilGenerics.cast(engine.getConfig().getAppContext());
163                appContext.put("delegator", delegator);
164                appContext.put("dispatcher", dispatcher);
165                appContext.put("security", security);
166                
167                InputStream reportInputStream = BirtFactory.getReportInputStreamFromLocation(birtReportLocation);
168                IReportRunnable design = engine.openReportDesign(reportInputStream);
169                Debug.logInfo("Export report as content type:" + birtContentType, module);
170                BirtWorker.exportReport(design, context, birtContentType, baos);
171                baos.flush();
172                baos.close();
173
174                // store in the list of maps for sendmail....
175                List<Map<String, ? extends Object>> bodyParts = FastList.newInstance();
176                if (bodyText != null) {
177                    bodyText = FlexibleStringExpander.expandString(bodyText, screenContext,  locale);
178                    bodyParts.add(UtilMisc.toMap("content", bodyText, "type", "text/html"));
179                } else {
180                    bodyParts.add(UtilMisc.toMap("content", bodyWriter.toString(), "type", "text/html"));
181                }
182                bodyParts.add(UtilMisc.toMap("content", baos.toByteArray(), "type", "application/pdf", "filename", attachmentName));
183                serviceContext.put("bodyParts", bodyParts);
184            } catch (GeneralException ge) {
185                String errMsg = "Error rendering " + birtContentType + " attachment for email: " + ge.toString();
186                Debug.logError(ge, errMsg, module);
187                return ServiceUtil.returnError(errMsg);
188            } catch (IOException ie) {
189                String errMsg = "Error I/O rendering " + birtContentType + " attachment for email: " + ie.toString();
190                Debug.logError(ie, errMsg, module);
191                return ServiceUtil.returnError(errMsg);
192            } catch (FOPException fe) {
193                String errMsg = "Error FOP rendering " + birtContentType + " attachment for email: " + fe.toString();
194                Debug.logError(fe, errMsg, module);
195                return ServiceUtil.returnError(errMsg);
196            } catch (SAXException se) {
197                String errMsg = "Error SAX rendering " + birtContentType + " attachment for email: " + se.toString();
198                Debug.logError(se, errMsg, module);
199                return ServiceUtil.returnError(errMsg);
200            } catch (ParserConfigurationException pe) {
201                String errMsg = "Error parser rendering " + birtContentType + " attachment for email: " + pe.toString();
202                Debug.logError(pe, errMsg, module);
203                return ServiceUtil.returnError(errMsg);
204            } catch (EngineException ee) {
205                String errMsg = "Error rendering " + birtContentType + " attachment for email: " + ee.toString();
206                Debug.logError(ee, errMsg, module);
207                return ServiceUtil.returnError(errMsg);
208            } catch (SQLException se) {
209                String errMsg = "Error SQL rendering " + birtContentType + " attachment for email: " + se.toString();
210                Debug.logError(se, errMsg, module);
211                return ServiceUtil.returnError(errMsg);
212            }
213        } else {
214            isMultiPart = false;
215            // store body and type for single part message in the context.
216            if (bodyText != null) {
217                bodyText = FlexibleStringExpander.expandString(bodyText, screenContext,  locale);
218                serviceContext.put("body", bodyText);
219            } else {
220                serviceContext.put("body", bodyWriter.toString());
221            }
222
223            // Only override the default contentType in case of plaintext, since other contentTypes may be multipart
224            //    and would require specific handling.
225            if (contentType != null && contentType.equalsIgnoreCase("text/plain")) {
226                serviceContext.put("contentType", "text/plain");
227            } else {
228                serviceContext.put("contentType", "text/html");
229            }
230        }
231
232        // also expand the subject at this point, just in case it has the FlexibleStringExpander syntax in it...
233        String subject = (String) serviceContext.remove("subject");
234        subject = FlexibleStringExpander.expandString(subject, screenContext, locale);
235        serviceContext.put("subject", subject);
236        serviceContext.put("partyId", partyId);
237
238        if (Debug.verboseOn()) Debug.logVerbose("sendMailFromScreen sendMail context: " + serviceContext, module);
239
240        Map<String, Object> result = ServiceUtil.returnSuccess();
241        try {
242            if (isMultiPart) {
243                dispatcher.runSync("sendMailMultiPart", serviceContext);
244            } else {
245                dispatcher.runSync("sendMail", serviceContext);
246            }
247        } catch (Exception e) {
248            String errMsg = "Error send email :" + e.toString();
249            Debug.logError(e, errMsg, module);
250            return ServiceUtil.returnError(errMsg);
251        }
252        result.put("body", bodyWriter.toString());
253        return result;
254    }
255}