KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensourcestrategies > crmsfa > util > UtilCommon


1 /*
2  * Copyright (c) 2006 - 2007 Open Source Strategies, Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the Honest Public License.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * Honest Public License for more details.
11  *
12  * You should have received a copy of the Honest Public License
13  * along with this program; if not, write to Funambol,
14  * 643 Bair Island Road, Suite 305 - Redwood City, CA 94063, USA
15  */

16 /* Copyright (c) 2005-2006 Open Source Strategies, Inc. */
17
18 /*
19  * $Id:$
20  *
21  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
22  *
23  * Permission is hereby granted, free of charge, to any person obtaining a
24  * copy of this software and associated documentation files (the "Software"),
25  * to deal in the Software without restriction, including without limitation
26  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
27  * and/or sell copies of the Software, and to permit persons to whom the
28  * Software is furnished to do so, subject to the following conditions:
29  *
30  * The above copyright notice and this permission notice shall be included
31  * in all copies or substantial portions of the Software.
32  *
33  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
34  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
35  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
36  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
37  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
38  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
39  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
40  */

41 package com.opensourcestrategies.crmsfa.util;
42
43 import java.util.Map JavaDoc;
44 import java.util.List JavaDoc;
45 import java.util.Locale JavaDoc;
46 import java.util.Calendar JavaDoc;
47 import java.util.Iterator JavaDoc;
48 import java.sql.Timestamp JavaDoc;
49 import java.text.DateFormat JavaDoc;
50 import java.text.SimpleDateFormat JavaDoc;
51 import java.text.ParseException JavaDoc;
52 import javax.servlet.http.HttpServletRequest JavaDoc;
53 import javax.servlet.http.HttpServletResponse JavaDoc;
54 import javax.servlet.http.HttpSession JavaDoc;
55
56 import javax.servlet.http.HttpServletRequest JavaDoc;
57 import javax.servlet.http.HttpServletResponse JavaDoc;
58
59 import org.ofbiz.base.util.Debug;
60 import org.ofbiz.base.util.UtilFormatOut;
61 import org.ofbiz.base.util.UtilValidate;
62 import org.ofbiz.base.util.UtilHttp;
63 import org.ofbiz.base.util.UtilMisc;
64 import org.ofbiz.base.util.UtilNumber;
65 import org.ofbiz.base.util.UtilDateTime;
66 import org.ofbiz.base.util.UtilProperties;
67 import org.ofbiz.base.util.collections.ResourceBundleMapWrapper;
68
69 import org.ofbiz.entity.GenericDelegator;
70 import org.ofbiz.entity.GenericEntityException;
71 import org.ofbiz.entity.GenericValue;
72 import org.ofbiz.service.DispatchContext;
73 import org.ofbiz.service.GenericServiceException;
74 import org.ofbiz.service.LocalDispatcher;
75 import org.ofbiz.service.ServiceUtil;
76 import org.ofbiz.service.ModelService;
77 import org.ofbiz.security.Security;
78
79 import org.ofbiz.securityext.login.LoginServices;
80 import org.ofbiz.party.contact.ContactHelper;
81
82 /**
83  * UtilCommon - A place for common crmsfa helper methods
84  *
85  * @author <a HREF="mailto:leon@opensourcestrategies.com">Leon Torres</a>
86  * @version $Rev: 312 $
87  */

88 public class UtilCommon {
89
90     public static final String JavaDoc module = UtilCommon.class.getName();
91
92
93     /************************************************************************/
94     /** Logging Methods **/
95     /************************************************************************/
96
97
98     /**
99      * Log only a uiLabel to the log file and return the label as a user error.
100      */

101     public static Map JavaDoc createAndLogServiceError(String JavaDoc uiLabel, Locale JavaDoc locale, String JavaDoc _module) {
102         ResourceBundleMapWrapper uiLabelMap = (ResourceBundleMapWrapper) UtilProperties.getResourceBundleMap("CRMSFAUiLabels", locale);
103         String JavaDoc errorMsg = (String JavaDoc) uiLabelMap.get(uiLabel);
104         Debug.logError(null, errorMsg, _module);
105         return ServiceUtil.returnError(errorMsg);
106     }
107
108     /**
109      * Log a uiLabel + message to the log file and return it to the user.
110      */

111     public static Map JavaDoc createAndLogServiceError(String JavaDoc message, String JavaDoc uiLabel, Locale JavaDoc locale, String JavaDoc _module) {
112         ResourceBundleMapWrapper uiLabelMap = (ResourceBundleMapWrapper) UtilProperties.getResourceBundleMap("CRMSFAUiLabels", locale);
113         String JavaDoc errorMsg = (String JavaDoc) uiLabelMap.get(uiLabel) + " " + message;
114         Debug.logError(null, errorMsg, _module);
115         return ServiceUtil.returnError(errorMsg);
116     }
117
118     /**
119      * Log the uiLabel + serviceResult error to the log file and return it to the user.
120      */

121     public static Map JavaDoc createAndLogServiceError(Map JavaDoc serviceResult, String JavaDoc uiLabel, Locale JavaDoc locale, String JavaDoc _module) {
122         ResourceBundleMapWrapper uiLabelMap = (ResourceBundleMapWrapper) UtilProperties.getResourceBundleMap("CRMSFAUiLabels", locale);
123         String JavaDoc errorMsg = (String JavaDoc) uiLabelMap.get(uiLabel) + " " + ServiceUtil.getErrorMessage(serviceResult);
124         Debug.logError(null, errorMsg, _module);
125         return ServiceUtil.returnError(errorMsg);
126     }
127
128     /**
129      * Log the uiLabel + exception message to the log file and return it to the user.
130      */

131     public static Map JavaDoc createAndLogServiceError(Exception JavaDoc e, String JavaDoc uiLabel, Locale JavaDoc locale, String JavaDoc _module) {
132         ResourceBundleMapWrapper uiLabelMap = (ResourceBundleMapWrapper) UtilProperties.getResourceBundleMap("CRMSFAUiLabels", locale);
133         String JavaDoc errorMsg = (String JavaDoc) uiLabelMap.get(uiLabel) + " " + e.getMessage();
134         Debug.logError(e, errorMsg, _module);
135         return ServiceUtil.returnError(errorMsg);
136     }
137
138
139     /************************************************************************/
140     /** Time Methods **/
141     /************************************************************************/
142
143
144     /**
145      * This method takes the date/time/duration form input and transforms it into an end timestamp.
146      * It uses Java Date formatting capabilities to transform the duration input into an interval.
147      *
148      * @param start Full date, hour, minute and second of the starting time
149      * @param duration The user input for hour such as "1:00"
150      * @throws IllegalArgumentException If the duration input is unparseable or negative
151      */

152     public static Timestamp JavaDoc getEndTimestamp(Timestamp JavaDoc start, String JavaDoc duration, Locale JavaDoc locale) throws IllegalArgumentException JavaDoc {
153
154         // return the start timestamp if no duration specified (i.e., duration = 0)
155
if (duration == null || duration.length() == 0) return start;
156
157         Calendar JavaDoc cal = Calendar.getInstance();
158
159         // Turn the duraiton into a date and time with the hour being the duration
160
DateFormat JavaDoc df = new SimpleDateFormat JavaDoc("HH:mm", locale);
161         try {
162             cal.setTime(df.parse(duration));
163         } catch (ParseException JavaDoc e) {
164             throw new IllegalArgumentException JavaDoc("Duration input must be in HH:mm format.");
165         }
166         
167         // extract the days, hours and minutes
168
int days = cal.get(Calendar.DAY_OF_YEAR) - 1;
169         int hours = cal.get(Calendar.HOUR_OF_DAY);
170         int minutes = cal.get(Calendar.MINUTE);
171
172         // set to the start time and add the hours and minutes
173
cal.setTime(start);
174         cal.set(Calendar.DAY_OF_YEAR, days + cal.get(Calendar.DAY_OF_YEAR));
175         cal.set(Calendar.HOUR_OF_DAY, hours + cal.get(Calendar.HOUR_OF_DAY));
176         cal.set(Calendar.MINUTE, minutes + cal.get(Calendar.MINUTE));
177
178         // create the end timestamp
179
Timestamp JavaDoc end = new Timestamp JavaDoc(cal.getTimeInMillis());
180
181         // make sure it's after the start timestamp
182
if (end.before(start)) throw new IllegalArgumentException JavaDoc("Cannot set a negative duration.");
183
184         // return our result as a Timestamp
185
return end;
186     }
187
188     /**
189      * Get the duration between two timestamps in HH:mm format.
190      */

191     public static String JavaDoc getDuration(Timestamp JavaDoc start, Timestamp JavaDoc end) {
192         Calendar JavaDoc cal = Calendar.getInstance();
193
194         // set the time to the beginning of the day
195
cal.setTime(UtilDateTime.getDayStart(start));
196
197         // the duration in milliseconds
198
long duration = end.getTime() - start.getTime();
199
200         // compute number of full hours
201
int hours = (int) (duration / 1000 / 60 / 60);
202
203         // compute number of minutes
204
int minutes = (int) ((duration / 1000 / 60) % 60);
205
206         return hours + ":" + (minutes < 10 ? "0" : "") + minutes;
207     }
208
209     /**
210      * Returns a true if the time period has passed or is closed
211      * @param customTimePeriodId
212      * @return
213      */

214     public static boolean isTimePeriodOpen(String JavaDoc customTimePeriodId, GenericDelegator delegator) throws GenericEntityException {
215         
216         // first check time period -- is closed or passed? if so, cannot create a forecast
217
GenericValue timePeriod = delegator.findByPrimaryKeyCache("CustomTimePeriod", UtilMisc.toMap("customTimePeriodId", customTimePeriodId));
218         if (timePeriod == null) {
219             return false;
220         }
221         if (timePeriod.getString("isClosed") == null) {
222             Debug.logWarning("Time period [" + customTimePeriodId + "] has no isClosed flag set--please set it", module);
223             return false; // really sholdn't have this case, so let's return a false
224
} else if (timePeriod.getString("isClosed").equals("Y")) {
225             return false;
226         }
227         if (timePeriod.getDate("thruDate").before(UtilDateTime.toDate(UtilDateTime.toDateTimeString(UtilDateTime.nowTimestamp())))) {
228             Debug.logInfo(timePeriod.getDate("thruDate") + " is before " + UtilDateTime.nowTimestamp() + " so time period [" + customTimePeriodId + "] is not open", module );
229             return false;
230         }
231        
232         return true;
233     }
234  
235     
236     /************************************************************************/
237     /** Miscellaneous Methods **/
238     /************************************************************************/
239
240
241     /**
242      * This method will read the donePage parameter and return it to the controller as the result.
243      * It is called from controller.xml using <event type="java" path="com.opensourcestrategies.crmsfa.util.UtilCommon" invoke="donePageRequestHelper"/>
244      * Then it can be used with <response name="returnValue" .../> to determine what to do next.
245      *
246      * @return The donePage parameter if it exists, otherwise "error"
247      */

248     public static String JavaDoc donePageRequestHelper(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
249         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
250         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
251
252         String JavaDoc donePage = (String JavaDoc) request.getParameter("donePage");
253         if (donePage == null) {
254             donePage = "error";
255         }
256         return donePage;
257     }
258
259     /**
260      * Custom forgotPassword service because the OFBiz method is reather complicated.
261      * TODO: config properties for sendFrom, subject, and maybe make ftl for body
262      */

263     private static String JavaDoc sendFrom = "ofbiztest@yahoo.com";
264     private static String JavaDoc subject = "CRM password reminder for user ";
265     public static String JavaDoc forgotPassword(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
266         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
267         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
268
269         String JavaDoc resource = "SecurityextUiLabels";
270         String JavaDoc errMsg = null;
271         boolean useEncryption = "true".equals(UtilProperties.getPropertyValue("security.properties", "password.encrypt"));
272
273         // validate the userloginId input
274
String JavaDoc userLoginId = request.getParameter("USERNAME");
275         if ((userLoginId != null) && ("true".equals(UtilProperties.getPropertyValue("security.properties", "username.lowercase")))) {
276             userLoginId = userLoginId.toLowerCase();
277         }
278         if (!UtilValidate.isNotEmpty(userLoginId)) {
279             // the password was incomplete
280
errMsg = UtilProperties.getMessage(resource, "loginevents.username_was_empty_reenter", UtilHttp.getLocale(request));
281             request.setAttribute("_ERROR_MESSAGE_", errMsg);
282             return "error";
283         }
284
285         // get the password of the userlogin or generate a new one if there is encryption
286
GenericValue supposedUserLogin = null;
287         String JavaDoc passwordToSend = null;
288         try {
289             supposedUserLogin = delegator.findByPrimaryKey("UserLogin", UtilMisc.toMap("userLoginId", userLoginId));
290             if (supposedUserLogin == null) {
291                 // the Username was not found
292
errMsg = UtilProperties.getMessage(resource, "loginevents.username_not_found_reenter", UtilHttp.getLocale(request));
293                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
294                 return "error";
295             }
296             if (useEncryption) {
297                 // password encrypted, can't send, generate new password and email to user
298
double randNum = Math.random();
299
300                 // multiply by 100,000 to usually make a 5 digit number
301
passwordToSend = "auto" + ((long) (randNum * 100000));
302                 supposedUserLogin.set("currentPassword", LoginServices.getPasswordHash(passwordToSend));
303                 supposedUserLogin.set("passwordHint", "Auto-Generated Password");
304             } else {
305                 passwordToSend = supposedUserLogin.getString("currentPassword");
306             }
307         } catch (GenericEntityException e) {
308             Debug.logWarning(e, "", module);
309             Map JavaDoc messageMap = UtilMisc.toMap("errorMessage", e.toString());
310             errMsg = UtilProperties.getMessage(resource, "loginevents.error_accessing_password", messageMap, UtilHttp.getLocale(request));
311             request.setAttribute("_ERROR_MESSAGE_", errMsg);
312             return "error";
313         }
314         if (supposedUserLogin == null) {
315             // the Username was not found
316
Map JavaDoc messageMap = UtilMisc.toMap("userLoginId", userLoginId);
317             errMsg = UtilProperties.getMessage(resource, "loginevents.user_with_the_username_not_found", messageMap, UtilHttp.getLocale(request));
318             request.setAttribute("_ERROR_MESSAGE_", errMsg);
319             return "error";
320         }
321
322         // now find the party and the party's primary email
323
GenericValue party = null;
324         StringBuffer JavaDoc emails = new StringBuffer JavaDoc();
325         try {
326             party = supposedUserLogin.getRelatedOne("Party");
327         } catch (GenericEntityException e) {
328             Debug.logWarning(e, "", module);
329             party = null;
330         }
331         if (party != null) {
332             Iterator JavaDoc emailIter = UtilMisc.toIterator(ContactHelper.getContactMechByPurpose(party, "PRIMARY_EMAIL", false));
333             while (emailIter != null && emailIter.hasNext()) {
334                 GenericValue email = (GenericValue) emailIter.next();
335                 emails.append(emails.length() > 0 ? "," : "").append(email.getString("infoString"));
336             }
337         }
338         if (!UtilValidate.isNotEmpty(emails.toString())) {
339             // the Username was not found
340
errMsg = UtilProperties.getMessage(resource, "loginevents.no_primary_email_address_set_contact_customer_service", UtilHttp.getLocale(request));
341             request.setAttribute("_ERROR_MESSAGE_", errMsg);
342             return "error";
343         }
344
345         // construct the body
346
StringBuffer JavaDoc body = new StringBuffer JavaDoc(subject + userLoginId + "\n\n");
347         if (useEncryption) {
348             body.append("A new password was generated for you: ").append(passwordToSend).append("\n\n");
349         } else {
350             body.append("Your password is: ").append(passwordToSend).append("\n\n");
351         }
352         body.append("When you log in, please change your password because this email is not secure.\n");
353
354         // send the email
355
Map JavaDoc input = UtilMisc.toMap("subject", subject + userLoginId, "sendFrom", sendFrom, "contentType", "text/plain");
356         input.put("sendTo", emails.toString());
357         input.put("body", body.toString());
358
359         try {
360             Map JavaDoc result = dispatcher.runSync("sendMail", input);
361
362             if (ServiceUtil.isError(result)) {
363                 Map JavaDoc messageMap = UtilMisc.toMap("errorMessage", result.get(ModelService.ERROR_MESSAGE));
364                 errMsg = UtilProperties.getMessage(resource, "loginevents.error_unable_email_password_contact_customer_service_errorwas", messageMap, UtilHttp.getLocale(request));
365                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
366                 return "error";
367             }
368         } catch (GenericServiceException e) {
369             Debug.logWarning(e, "", module);
370             errMsg = UtilProperties.getMessage(resource, "loginevents.error_unable_email_password_contact_customer_service", UtilHttp.getLocale(request));
371             request.setAttribute("_ERROR_MESSAGE_", errMsg);
372             return "error";
373         }
374
375         // don't save password until after it has been sent
376
if (useEncryption) {
377             try {
378                 supposedUserLogin.store();
379             } catch (GenericEntityException e) {
380                 Debug.logWarning(e, "", module);
381                 Map JavaDoc messageMap = UtilMisc.toMap("errorMessage", e.toString());
382                 errMsg = UtilProperties.getMessage(resource, "loginevents.error_saving_new_password_email_not_correct_password", messageMap, UtilHttp.getLocale(request));
383                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
384                 return "error";
385             }
386         }
387
388         if (useEncryption) {
389             errMsg = UtilProperties.getMessage(resource, "loginevents.new_password_createdandsent_check_email", UtilHttp.getLocale(request));
390             request.setAttribute("_EVENT_MESSAGE_", errMsg);
391         } else {
392             errMsg = UtilProperties.getMessage(resource, "loginevents.new_password_sent_check_email", UtilHttp.getLocale(request));
393             request.setAttribute("_EVENT_MESSAGE_", errMsg);
394         }
395         return "success";
396     }
397
398     /**
399      * Helper method to format a percent string for use in the form widget.
400      * For now, this uses only the forecast percents, but it could be generalized.
401      */

402     public static String JavaDoc toPercent(Number JavaDoc number) {
403         return UtilNumber.toPercentString(number,
404                 com.opensourcestrategies.crmsfa.forecasts.UtilForecast.BD_FORECAST_PERCENT_DECIMALS - 2,
405                 com.opensourcestrategies.crmsfa.forecasts.UtilForecast.BD_FORECAST_PERCENT_ROUNDING);
406     }
407 }
408
Popular Tags