KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mvnforum > auth > OnlineUserImpl


1 /*
2  * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/auth/OnlineUserImpl.java,v 1.46 2006/04/14 17:05:26 minhnn Exp $
3  * $Author: minhnn $
4  * $Revision: 1.46 $
5  * $Date: 2006/04/14 17:05:26 $
6  *
7  * ====================================================================
8  *
9  * Copyright (C) 2002-2006 by MyVietnam.net
10  *
11  * All copyright notices regarding mvnForum MUST remain
12  * intact in the scripts and in the outputted HTML.
13  * The "powered by" text/logo with a link back to
14  * http://www.mvnForum.com and http://www.MyVietnam.net in
15  * the footer of the pages MUST remain visible when the pages
16  * are viewed on the internet or intranet.
17  *
18  * This program is free software; you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation; either version 2 of the License, or
21  * any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program; if not, write to the Free Software
30  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31  *
32  * Support can be obtained from support forums at:
33  * http://www.mvnForum.com/mvnforum/index
34  *
35  * Correspondence and Marketing Questions can be sent to:
36  * info at MyVietnam net
37  *
38  * @author: Minh Nguyen
39  * @author: Mai Nguyen
40  */

41 package com.mvnforum.auth;
42
43 import java.awt.image.BufferedImage JavaDoc;
44 import java.sql.Timestamp JavaDoc;
45 import java.text.DateFormat JavaDoc;
46 import java.util.Locale JavaDoc;
47
48 import javax.servlet.http.HttpServletRequest JavaDoc;
49
50 import com.mvnforum.*;
51 import com.mvnforum.common.MVNCaptchaService;
52 import com.mvnforum.db.*;
53 import com.octo.captcha.image.ImageCaptcha;
54 import net.myvietnam.mvncore.exception.*;
55 import net.myvietnam.mvncore.util.DateUtil;
56 import net.myvietnam.mvncore.util.GenericParamUtil;
57 import net.myvietnam.mvncore.web.GenericRequest;
58 import net.myvietnam.mvncore.web.impl.GenericRequestServletImpl;
59 import org.apache.commons.logging.Log;
60 import org.apache.commons.logging.LogFactory;
61
62 class OnlineUserImpl implements OnlineUser {
63
64     private static long CHECK_NEW_MESSAGE_INTERVAL = 5 * DateUtil.MINUTE;// five minutes
65

66     private static Log log = LogFactory.getLog(OnlineUserImpl.class);
67
68     private int memberID = MVNForumConstant.MEMBER_ID_OF_GUEST;
69
70     private String JavaDoc memberName = "";
71
72     private int authenticationType = AUTHENTICATION_TYPE_UNAUTHENTICATED;
73
74     private MVNForumPermission permission = null;
75
76     private OnlineUserAction onlineUserAction = new OnlineUserAction();
77
78     private int memberPostsPerPage = 10;
79     private int memberMessagesPerPage = 10;
80
81     private boolean invisible = false;
82
83     private int newMessageCount = 0;
84
85     private String JavaDoc memberCssPath = null;
86     private String JavaDoc memberLogoPath = null;
87
88     private double hourOffset = 0;
89     /* private DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
90      * Igor: previous line should be: new SimpleDateFormat(..., Locale.US)
91      * Otherwise won't work for users who don't have en/US as default.
92      */

93     private DateFormat JavaDoc timestampFormatter = null;
94     private DateFormat JavaDoc dateFormatter = null;
95
96     private Timestamp JavaDoc lastLogonTimestamp = null;
97
98     private Timestamp JavaDoc lastCheckNewMessageTimestamp = null;
99
100     private String JavaDoc lastLogonIP = null;
101
102     private String JavaDoc localeName = "";
103
104     private Locale JavaDoc locale = null;
105
106     private boolean gender = true;
107
108     private ImageCaptcha imageCaptcha = null;
109
110     /**
111      * Default access constructor, prevent outsite creation
112      * NOTE: the implementation should init the following:
113      * - Is Guest or not <br/>
114      * - Call initRemoteAddr_UserAgent() <br/>
115      * - The memberCssPath <br/>
116      * - The memberLogoPath <br/>
117      */

118     OnlineUserImpl(HttpServletRequest JavaDoc request, boolean isGuest) throws DatabaseException {
119         GenericRequest genericRequest = new GenericRequestServletImpl(request);
120         init(genericRequest, isGuest);
121     }
122
123     OnlineUserImpl(GenericRequest request, boolean isGuest) throws DatabaseException {
124         init(request, isGuest);
125     }
126
127     private void init(GenericRequest request, boolean isGuest) throws DatabaseException {
128         if (isGuest) {
129             setMemberID(MVNForumConstant.MEMBER_ID_OF_GUEST);
130             setMemberName(MVNForumConfig.getDefaultGuestName());
131         }
132         getOnlineUserAction().initRemoteAddr_UserAgent(request);
133         String JavaDoc contextPath = request.getContextPath();
134         memberCssPath = contextPath + MVNForumGlobal.CSS_FULLPATH;
135         memberLogoPath = contextPath + MVNForumGlobal.LOGO_FULLPATH;
136         if (isGuest && MVNForumConfig.getEnableCompany()) {
137             try {
138                 int companyID = GenericParamUtil.getParameterInt(request, "companyid");
139                 CompanyBean companyBean = DAOFactory.getCompanyDAO().getCompany(companyID);
140
141                 // Load the css Path for this user
142
memberCssPath = MyUtil.getCompanyCssPath(companyBean, request.getContextPath());
143
144                 // Load the logo Path for this user
145
memberLogoPath = MyUtil.getCompanyLogoPath(companyBean, request.getContextPath());
146             } catch (ObjectNotFoundException ex) {
147                 // cannot find the Company in the database, just ignore
148
} catch (BadInputException ex) {
149                 // cannot find the companyid in the request, just ignore
150
}
151         }
152     }
153
154     public int getMemberID() {
155         return memberID;
156     }
157
158     public String JavaDoc getMemberName() {
159         return memberName;
160     }
161
162     public boolean isGuest() {
163         return ( (memberID==0) || (memberID==MVNForumConstant.MEMBER_ID_OF_GUEST) );
164     }
165
166     public boolean isMember() {
167         return !isGuest();
168     }
169
170     public boolean isInvisibleMember() {
171         // @todo: temp implementation
172
return this.invisible;
173     }
174
175     public int getAuthenticationType() {
176         return authenticationType;
177     }
178
179     public MVNForumPermission getPermission() {
180         return permission;
181     }
182
183     public void reloadPermission() {
184         try {
185             if (isGuest()) {
186                 permission = MVNForumPermissionFactory.getAnonymousPermission();
187             } else {
188                 permission = MVNForumPermissionFactory.getAuthenticatedPermission(memberID);
189             }
190         } catch (Exception JavaDoc ex) {
191             log.error("Error when reload permission in OnlineUserImpl for memberID = " + memberID , ex);
192         }
193     }
194
195     public void reloadProfile() {
196         try {
197             if (isGuest()) {
198                 // currently just do nothing, implement later
199
} else {
200                 MemberBean memberBean = DAOFactory.getMemberDAO().getMember_forViewCurrentMember(memberID);
201
202                 double timeZone = memberBean.getMemberTimeZone();
203                 localeName = memberBean.getMemberLanguage();
204                 int postsPerPage = memberBean.getMemberPostsPerPage();
205
206                 setTimeZone(timeZone);
207                 setLocaleName(localeName);
208                 setGender(memberBean.getMemberGender() != 0);
209                 setPostsPerPage(postsPerPage);
210                 setInvisible(memberBean.isInvisible());
211             }
212         } catch (Exception JavaDoc ex) {
213             log.error("Error when reload profile in OnlineUserImpl for memberID = " + memberID , ex);
214         }
215     }
216
217     public boolean updateNewMessageCount(boolean forceUpdate) {
218
219         if (isGuest()) return false;
220
221         int currentMessageCount = newMessageCount;
222         Timestamp JavaDoc now = DateUtil.getCurrentGMTTimestamp();
223         long lastRequest = 0;
224         if (lastCheckNewMessageTimestamp != null ) {
225             lastRequest = lastCheckNewMessageTimestamp.getTime();
226         }
227         if ((lastCheckNewMessageTimestamp == null) ||
228             forceUpdate ||
229             ((lastRequest + CHECK_NEW_MESSAGE_INTERVAL) <= now.getTime())) {
230             try {
231                 lastCheckNewMessageTimestamp = now;
232                 newMessageCount = DAOFactory.getMessageDAO().getNumberOfUnreadNonPublicMessages_inMember_inFolder(memberID, MVNForumConstant.MESSAGE_FOLDER_INBOX);
233                 if (currentMessageCount < newMessageCount) {
234                     return true;
235                 }
236             } catch (Exception JavaDoc ex) {
237                 log.error("Error when udpate new message count in OnlineUserImpl for memberID = " + memberID , ex);
238             }
239         }
240         return false;
241     }
242
243     public OnlineUserAction getOnlineUserAction() {
244         return onlineUserAction;
245     }
246
247     public java.util.Date JavaDoc convertGMTDate(java.util.Date JavaDoc gmtDate) {
248         return DateUtil.convertGMTDate(gmtDate, hourOffset);
249     }
250
251     public Timestamp JavaDoc convertGMTTimestamp(Timestamp JavaDoc gmtTimestamp) {
252         return DateUtil.convertGMTTimestamp(gmtTimestamp, hourOffset);
253     }
254
255     public String JavaDoc getGMTDateFormat(java.util.Date JavaDoc gmtDate) {
256        return getGMTDateFormat(gmtDate, true);
257     }
258
259     public synchronized String JavaDoc getGMTDateFormat(java.util.Date JavaDoc gmtDate, boolean adjustTimeZone) {
260         if (gmtDate == null) return "";
261
262         java.util.Date JavaDoc date = gmtDate;
263         if (adjustTimeZone) {
264             date = DateUtil.convertGMTDate(gmtDate, hourOffset);
265         }
266         return dateFormatter.format(date);
267     }
268
269     public String JavaDoc getGMTTimestampFormat(Timestamp JavaDoc gmtTimestamp) {
270        return getGMTTimestampFormat(gmtTimestamp, true);
271     }
272
273     public synchronized String JavaDoc getGMTTimestampFormat(Timestamp JavaDoc gmtTimestamp, boolean adjustTimeZone) {
274         if (gmtTimestamp == null) return "";
275
276         Timestamp JavaDoc timestamp = gmtTimestamp;
277         if (adjustTimeZone) {
278             timestamp = DateUtil.convertGMTTimestamp(gmtTimestamp, hourOffset);
279         }
280         return timestampFormatter.format(timestamp);
281     }
282
283     public String JavaDoc getLocaleName() {
284         return localeName;
285     }
286
287     public void setLocaleName(String JavaDoc localeName) {
288         if (localeName == null) {
289             localeName = "";
290         }
291         this.localeName = localeName;
292
293         if (localeName.length() == 0) {
294             this.localeName = MVNForumConfig.getDefaultLocaleName();
295             this.locale = MVNForumConfig.getDefaultLocale();
296         } else {
297             locale = MyUtil.getLocale(localeName);
298         }
299
300         // now init the 2 class variables
301
dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
302         timestampFormatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
303     }
304
305     public Locale JavaDoc getLocale() {
306         return locale;
307     }
308
309     public String JavaDoc getLastLogonIP() {
310         if (isGuest()) {
311             return "";
312          }
313         return lastLogonIP;
314     }
315
316     public Timestamp JavaDoc getLastLogonTimestamp() {
317         return lastLogonTimestamp;
318     }
319
320 /*
321     public boolean getGender() {
322         return gender;
323     }
324 */

325     public int getPostsPerPage() {
326         return memberPostsPerPage;
327     }
328
329     public int getMessagesPerPage() {
330         return memberMessagesPerPage;
331     }
332
333     public int getNewMessageCount() {
334         return newMessageCount;
335     }
336
337     public String JavaDoc getCssPath() {
338         return memberCssPath;
339     }
340
341     public String JavaDoc getLogoPath() {
342         return memberLogoPath;
343     }
344
345     /**
346      * Build a new captcha, this method must be called before using some
347      * action that need captcha validation.
348      */

349     public void buildNewCaptcha() {
350         destroyCurrentCaptcha();
351
352         // this line of code could throw Exception in case the captcha image
353
// is small to hold the whole captcha
354
imageCaptcha = MVNCaptchaService.getInstance().getNextImageCaptcha();
355     }
356
357     /**
358      * Destroy the current captcha, this method must be called after validate
359      * the captcha
360      */

361     public void destroyCurrentCaptcha() {
362         imageCaptcha = null;
363     }
364
365     /**
366      * Get the captcha image to challenge the user
367      *
368      * @return BufferedImage the captcha image to challenge the user
369      */

370     public BufferedImage JavaDoc getCurrentCaptchaImage() {
371         if (imageCaptcha == null) {
372             return null;
373         }
374         return (BufferedImage JavaDoc)(imageCaptcha.getChallenge());
375     }
376
377     /**
378      * Validate the anwser of the captcha from user
379      *
380      * @param anwser String the captcha anwser from user
381      * @return boolean true if the answer is valid, otherwise return false
382      */

383     public boolean validateCaptchaResponse(String JavaDoc anwser) {
384         if (imageCaptcha == null) {
385             log.info("validateCaptchaResponse returned false due to imageCaptcha is null");
386             return false;
387         }
388         anwser = anwser.toUpperCase();//use upper case for easier usage
389
boolean result = (imageCaptcha.validateResponse(anwser)).booleanValue();
390         if (result == false) {
391             // minhnn: I comment the below code because cannot get private variable 'response' from class Gimpy
392
//log.info("validateCaptchaResponse returned false due to wrong answer. The input is '" + anwser + "' but expect '" + imageCaptcha.getQuestion() + "'");
393
}
394         return result;
395     }
396
397     /**
398      * Check to make sure that the captcha answer is correct
399      *
400      * @param answer String the captcha answer to check
401      * @throws BadInputException in case the captcha answer is not correct
402      */

403     public void ensureCorrectCaptchaResponse(String JavaDoc answer)
404         throws BadInputException {
405
406         if (validateCaptchaResponse(answer) == false) {
407             throw new BadInputException(MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.wrong_captcha"));
408         }
409     }
410
411 /*****************************************************************
412  * Default-scope methods, only for internal package usage
413  *****************************************************************/

414     void setMemberID(int memberID) {
415         if (memberID == 0) {
416             this.memberID = MVNForumConstant.MEMBER_ID_OF_GUEST;
417         } else {
418             this.memberID = memberID;
419         }
420         onlineUserAction.setMemberID(this.memberID);
421     }
422
423     void setMemberName(String JavaDoc memberName) {
424         this.memberName = memberName;
425         onlineUserAction.setMemberName(memberName);
426     }
427
428     void setInvisible(boolean invisible) {
429         this.invisible = invisible;
430         onlineUserAction.setMemberInvisible(invisible);
431     }
432
433     void setAuthenticationType(int authType) {
434         authenticationType = authType;
435     }
436
437     /**
438      * NOTE: this method SHOULD ONLY BE CALLED from OnlineUserFactory
439      */

440     void setPermission(MVNForumPermission permission) {
441         this.permission = permission;
442     }
443
444     void setTimeZone(double timeZone) {
445         if ( (timeZone >= -12) && (timeZone <= 12) ) {
446             this.hourOffset = timeZone;
447         }
448     }
449
450     void setLastLogonTimestamp(Timestamp JavaDoc lastLogon) {
451         lastLogonTimestamp = lastLogon;
452     }
453
454     void setLastLogonIP(String JavaDoc lastLogonIP) {
455         this.lastLogonIP = lastLogonIP;
456     }
457
458     void setGender(boolean gender) {
459         this.gender = gender;
460     }
461
462     void setPostsPerPage(int postsPerPage) {
463         if (postsPerPage < 5) {
464             postsPerPage = 5;
465         }
466         this.memberPostsPerPage = postsPerPage;
467     }
468
469     public void setCssPath(String JavaDoc cssPath) {
470         this.memberCssPath = cssPath;
471     }
472
473     public void setLogoPath(String JavaDoc logoPath) {
474         this.memberLogoPath = logoPath;
475     }
476
477     // add this method to remove eclipse's warning
478
public boolean getGender() {
479         return gender;
480     }
481 }
482
Popular Tags