KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > party > communication > CommunicationEventServices


1 /*
2 *
3 * Copyright (c) 2005 The Open For Business Project - www.ofbiz.org
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included
13 * in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
20 * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
21 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 *
23 * @author Si Chen (sichen@opensourcestrategies.com)
24 */

25 package org.ofbiz.party.communication;
26
27 import java.util.*;
28
29 import org.ofbiz.base.util.*;
30 import org.ofbiz.entity.GenericDelegator;
31 import org.ofbiz.entity.GenericEntityException;
32 import org.ofbiz.entity.GenericValue;
33 import org.ofbiz.entity.condition.EntityConditionList;
34 import org.ofbiz.entity.condition.EntityExpr;
35 import org.ofbiz.entity.condition.EntityOperator;
36 import org.ofbiz.entity.util.EntityFindOptions;
37 import org.ofbiz.entity.util.EntityListIterator;
38 import org.ofbiz.entity.util.EntityUtil;
39 import org.ofbiz.service.DispatchContext;
40 import org.ofbiz.service.GenericServiceException;
41 import org.ofbiz.service.LocalDispatcher;
42 import org.ofbiz.service.ServiceUtil;
43
44 public class CommunicationEventServices {
45     
46     public static final String JavaDoc module = CommunicationEventServices.class.getName();
47     public static final String JavaDoc resource = "PartyUiLabels";
48     
49     public static Map sendCommEventAsEmail(DispatchContext ctx, Map context) {
50         GenericDelegator delegator = ctx.getDelegator();
51         LocalDispatcher dispatcher = ctx.getDispatcher();
52         GenericValue userLogin = (GenericValue) context.get("userLogin");
53         Locale locale = (Locale) context.get("locale");
54                 
55         String JavaDoc communicationEventId = (String JavaDoc) context.get("communicationEventId");
56         
57         Map result = ServiceUtil.returnSuccess();
58         List errorMessages = new LinkedList(); // used to keep a list of all error messages returned from sending emails to contact list
59

60         try {
61             // find the communication event and make sure that it is actually an email
62
GenericValue communicationEvent = delegator.findByPrimaryKey("CommunicationEvent", UtilMisc.toMap("communicationEventId", communicationEventId));
63             if (communicationEvent == null) {
64                 String JavaDoc errMsg = UtilProperties.getMessage(resource,"commeventservices.communication_event_not_found_failure", locale);
65                 return ServiceUtil.returnError(errMsg + " " + communicationEventId);
66             }
67             if ((communicationEvent.getString("communicationEventTypeId") == null) ||
68                 !(communicationEvent.getString("communicationEventTypeId").equals("EMAIL_COMMUNICATION"))) {
69                 String JavaDoc errMsg = UtilProperties.getMessage(resource,"commeventservices.communication_event_must_be_email_for_email", locale);
70                 return ServiceUtil.returnError(errMsg + " " + communicationEventId);
71             }
72             // make sure the from contact mech is an email if it is specified
73
if ((communicationEvent.getRelatedOne("FromContactMech") == null) ||
74                  (!(communicationEvent.getRelatedOne("FromContactMech").getString("contactMechTypeId").equals("EMAIL_ADDRESS")) ||
75                  (communicationEvent.getRelatedOne("FromContactMech").getString("infoString") == null))) {
76                 String JavaDoc errMsg = UtilProperties.getMessage(resource,"commeventservices.communication_event_from_contact_mech_must_be_email", locale);
77                 return ServiceUtil.returnError(errMsg + " " + communicationEventId);
78             }
79                         
80             // prepare the email
81
Map sendMailParams = new HashMap();
82             sendMailParams.put("sendFrom", communicationEvent.getRelatedOne("FromContactMech").getString("infoString"));
83             sendMailParams.put("subject", communicationEvent.getString("subject"));
84             sendMailParams.put("body", communicationEvent.getString("content"));
85             sendMailParams.put("contentType", communicationEvent.getString("contentMimeTypeId"));
86             sendMailParams.put("userLogin", userLogin);
87             
88             // if there is no contact list, then send look for a contactMechIdTo and partyId
89
if ((communicationEvent.getString("contactListId") == null) ||
90                 (communicationEvent.getString("contactListId").equals(""))) {
91                 
92                 // in this case, first make sure that the to contact mech actually is an email
93
if ((communicationEvent.getRelatedOne("ToContactMech") == null) ||
94                         (!(communicationEvent.getRelatedOne("ToContactMech").getString("contactMechTypeId").equals("EMAIL_ADDRESS")) ||
95                         (communicationEvent.getRelatedOne("ToContactMech").getString("infoString") == null))) {
96                        String JavaDoc errMsg = UtilProperties.getMessage(resource,"commeventservices.communication_event_to_contact_mech_must_be_email", locale);
97                        return ServiceUtil.returnError(errMsg + " " + communicationEventId);
98                    }
99                 
100                 sendMailParams.put("communicationEventId", communicationEventId);
101                 sendMailParams.put("sendTo", communicationEvent.getRelatedOne("ToContactMech").getString("infoString"));
102                 sendMailParams.put("partyId", communicationEvent.getString("partyIdTo")); // who it's going to
103

104                 // send it
105
Map tmpResult = dispatcher.runSync("sendMail", sendMailParams);
106                 if (ServiceUtil.isError(tmpResult)) {
107                     errorMessages.add(ServiceUtil.getErrorMessage(tmpResult));
108                 }
109             } else {
110
111                 // Call the sendEmailToContactList service if there's a contactListId present
112
Map sendEmailToContactListContext = new HashMap();
113                 sendEmailToContactListContext.put("contactListId", communicationEvent.getString("contactListId"));
114                 sendEmailToContactListContext.put("communicationEventId", communicationEventId);
115                 sendEmailToContactListContext.put("userLogin", userLogin);
116                 try {
117                     dispatcher.runAsync("sendEmailToContactList", sendEmailToContactListContext);
118                 } catch( GenericServiceException e ) {
119                     String JavaDoc errMsg = UtilProperties.getMessage(resource, "commeventservices.errorCallingSendEmailToContactListService", locale);
120                     Debug.logError(e, errMsg, module);
121                     errorMessages.add(errMsg);
122                     errorMessages.addAll(e.getMessageList());
123                 }
124             }
125         } catch (GenericEntityException eex) {
126             ServiceUtil.returnError(eex.getMessage());
127         } catch (GenericServiceException esx) {
128             ServiceUtil.returnError(esx.getMessage());
129         }
130         
131         // If there were errors, then the result of this service should be error with the full list of messages
132
if (errorMessages.size() > 0) {
133             result = ServiceUtil.returnError(errorMessages);
134         }
135         return result;
136     }
137     
138     public static Map sendEmailToContactList(DispatchContext ctx, Map context) {
139         GenericDelegator delegator = ctx.getDelegator();
140         LocalDispatcher dispatcher = ctx.getDispatcher();
141         GenericValue userLogin = (GenericValue) context.get("userLogin");
142         Locale locale = (Locale) context.get("locale");
143
144         List errorMessages = new ArrayList();
145         String JavaDoc errorCallingSendMailService = UtilProperties.getMessage(resource, "commeventservices.errorCallingSendMailService", locale);
146         String JavaDoc errorInSendEmailToContactListService = UtilProperties.getMessage(resource, "commeventservices.errorForEmailAddress", locale);
147         String JavaDoc skippingInvalidEmailAddress = UtilProperties.getMessage(resource, "commeventservices.skippingInvalidEmailAddress", locale);
148         
149         String JavaDoc contactListId = (String JavaDoc) context.get("contactListId");
150         String JavaDoc communicationEventId = (String JavaDoc) context.get("communicationEventId");
151
152         // Any exceptions thrown in this block will cause the service to return error
153
try {
154             
155             GenericValue communicationEvent = delegator.findByPrimaryKey("CommunicationEvent", UtilMisc.toMap("communicationEventId", communicationEventId));
156             GenericValue contactList = delegator.findByPrimaryKey("ContactList", UtilMisc.toMap("contactListId", contactListId));
157
158             Map sendMailParams = new HashMap();
159             sendMailParams.put("sendFrom", communicationEvent.getRelatedOne("FromContactMech").getString("infoString"));
160             sendMailParams.put("subject", communicationEvent.getString("subject"));
161             sendMailParams.put("body", communicationEvent.getString("content"));
162             sendMailParams.put("contentType", communicationEvent.getString("contentMimeTypeId"));
163             sendMailParams.put("userLogin", userLogin);
164
165             // Find a list of distinct email addresses from active, ACCEPTED parties in the contact list
166
// using a list iterator (because there can be a large number)
167
List conditionList = UtilMisc.toList(
168                         new EntityExpr("contactListId", EntityOperator.EQUALS, contactList.get("contactListId")),
169                         new EntityExpr("statusId", EntityOperator.EQUALS, "CLPT_ACCEPTED"),
170                         new EntityExpr("preferredContactMechId", EntityOperator.NOT_EQUAL, null),
171                         EntityUtil.getFilterByDateExpr()
172                         );
173             EntityConditionList conditions = new EntityConditionList(conditionList, EntityOperator.AND);
174             List fieldsToSelect = UtilMisc.toList("infoString");
175
176             List sendToEmails = delegator.findByCondition("ContactListPartyAndContactMech", conditions, null, fieldsToSelect, null,
177                     new EntityFindOptions(true, EntityFindOptions.TYPE_SCROLL_INSENSITIVE, EntityFindOptions.CONCUR_READ_ONLY, true));
178             
179             // Send an email to each contact list member
180

181             List orderBy = UtilMisc.toList("-fromDate");
182             Iterator sendToEmailsIt = sendToEmails.iterator();
183             while (sendToEmailsIt.hasNext()) {
184                 
185                 GenericValue contactListPartyAndContactMech = (GenericValue) sendToEmailsIt.next();
186
187                 // Any exceptions thrown in this inner block will only relate to a single email of the list, so should
188
// only be logged and not cause the service to return an error
189
try {
190     
191                     String JavaDoc emailAddress = contactListPartyAndContactMech.getString("infoString");
192                     if (emailAddress == null) continue;
193                     emailAddress = emailAddress.trim();
194                     
195                     if (! UtilValidate.isEmail(emailAddress, true)) {
196                         
197                         // If validation fails, just log and skip the email address
198
Debug.logError(skippingInvalidEmailAddress + ": " + emailAddress, module);
199                         errorMessages.add(skippingInvalidEmailAddress + ": " + emailAddress);
200                         continue;
201                     }
202     
203                     // Because we're retrieving infoString only above (so as not to pollute the distinctness), we
204
// need to retrieve the partyId it's related to. Since this could be multiple parties, get
205
// only the most recent valid one via ContactListPartyAndContactMech.
206
List clpConditionList = new ArrayList(conditionList);
207                     clpConditionList.add(new EntityExpr("infoString", EntityOperator.EQUALS, emailAddress));
208                     EntityConditionList clpConditions = new EntityConditionList(clpConditionList, EntityOperator.AND);
209     
210                     List emailCLPaCMs = delegator.findByConditionCache("ContactListPartyAndContactMech", clpConditions, null, orderBy);
211                     GenericValue lastContactListPartyACM = EntityUtil.getFirst(emailCLPaCMs);
212                     if (lastContactListPartyACM == null) continue;
213                     
214                     String JavaDoc partyId = lastContactListPartyACM.getString("partyId");
215                     
216                     sendMailParams.put("sendTo", emailAddress);
217                     sendMailParams.put("partyId", partyId);
218                     
219                     if (! contactList.getString("contactListTypeId").equals("NEWSLETTER")) {
220                         sendMailParams.put("communicationEventId", communicationEventId);
221                     }
222                     
223                     // Retrieve a record for this contactMechId from ContactListCommStatus
224
Map contactListCommStatusRecordMap = UtilMisc.toMap("contactListId", contactListId, "communicationEventId", communicationEventId, "contactMechId", lastContactListPartyACM.getString("preferredContactMechId"));
225                     GenericValue contactListCommStatusRecord = delegator.findByPrimaryKey("ContactListCommStatus", contactListCommStatusRecordMap);
226                     if (contactListCommStatusRecord == null) {
227                         
228                         // No attempt has been made previously to send to this address, so create a record to reflect
229
// the beginning of the current attempt
230
Map newContactListCommStatusRecordMap = new HashMap(contactListCommStatusRecordMap);
231                         newContactListCommStatusRecordMap.put("statusId", "COM_IN_PROGRESS");
232                         contactListCommStatusRecord = delegator.create("ContactListCommStatus", newContactListCommStatusRecordMap);
233                     } else if (contactListCommStatusRecord.get("statusId") != null && contactListCommStatusRecord.getString("statusId").equals("COM_COMPLETE")) {
234     
235                         // There was a successful earlier attempt, so skip this address
236
continue;
237                     }
238
239                     Map tmpResult = null;
240                     
241                     // Make the attempt to send the email to the address
242
tmpResult = dispatcher.runSync("sendMail", sendMailParams);
243                     if (tmpResult == null || ServiceUtil.isError(tmpResult)) {
244     
245                         // If the send attempt fails, just log and skip the email address
246
Debug.logError(errorCallingSendMailService + ": " + ServiceUtil.getErrorMessage(tmpResult), module);
247                         errorMessages.add(errorCallingSendMailService + ": " + ServiceUtil.getErrorMessage(tmpResult));
248                         continue;
249                     }
250                     
251                     // All is successful, so update the ContactListCommStatus record
252
contactListCommStatusRecord.set("statusId", "COM_COMPLETE");
253                     delegator.store(contactListCommStatusRecord);
254                     
255                 // Don't return a service error just because of failure for one address - just log the error and continue
256
} catch (GenericEntityException nonFatalGEE) {
257                     Debug.logError(nonFatalGEE, errorInSendEmailToContactListService, module);
258                     errorMessages.add(errorInSendEmailToContactListService + ": " + nonFatalGEE.getMessage());
259                 } catch (GenericServiceException nonFatalGSE) {
260                     Debug.logError(nonFatalGSE, errorInSendEmailToContactListService, module);
261                     errorMessages.add(errorInSendEmailToContactListService + ": " + nonFatalGSE.getMessage());
262                 }
263             }
264             
265         } catch (GenericEntityException fatalGEE) {
266             ServiceUtil.returnError(fatalGEE.getMessage());
267         }
268
269         return errorMessages.size() == 0 ? ServiceUtil.returnSuccess() : ServiceUtil.returnError(errorMessages);
270     }
271
272
273     public static Map setCommEventComplete(DispatchContext dctx, Map context) {
274         LocalDispatcher dispatcher = dctx.getDispatcher();
275         GenericValue userLogin = (GenericValue) context.get("userLogin");
276         String JavaDoc communicationEventId = (String JavaDoc) context.get("communicationEventId");
277         
278         // assume it's a success unless updateCommunicationEvent gives us an error
279
Map result = ServiceUtil.returnSuccess();
280         try {
281             Map tmpResult = dispatcher.runSync("updateCommunicationEvent", UtilMisc.toMap("communicationEventId", communicationEventId,
282                     "statusId", "COM_COMPLETE", "userLogin", userLogin));
283             if (ServiceUtil.isError(result)) {
284                 result = ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
285             }
286         } catch (GenericServiceException esx) {
287             return ServiceUtil.returnError(esx.getMessage());
288         }
289
290         return result;
291     }
292 }
293
Popular Tags