KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mvnforum > MyUtil


1 /*
2  * $Header: /cvsroot/mvnforum/mvnforum/src/com/mvnforum/MyUtil.java,v 1.42 2006/04/14 17:05:25 minhnn Exp $
3  * $Author: minhnn $
4  * $Revision: 1.42 $
5  * $Date: 2006/04/14 17:05:25 $
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;
42
43 import java.awt.image.BufferedImage JavaDoc;
44 import java.io.IOException JavaDoc;
45 import java.io.OutputStream JavaDoc;
46 import java.util.*;
47
48 import javax.servlet.http.*;
49
50 import com.mvnforum.auth.*;
51 import com.mvnforum.db.*;
52 import com.sun.image.codec.jpeg.JPEGCodec;
53 import com.sun.image.codec.jpeg.JPEGImageEncoder;
54 import net.myvietnam.mvncore.MVNCoreInfo;
55 import net.myvietnam.mvncore.exception.*;
56 import net.myvietnam.mvncore.filter.*;
57 import net.myvietnam.mvncore.util.*;
58 import net.myvietnam.mvncore.web.GenericRequest;
59 import net.myvietnam.mvncore.web.GenericResponse;
60 import org.apache.commons.logging.Log;
61 import org.apache.commons.logging.LogFactory;
62
63 public class MyUtil {
64
65     private static Log log = LogFactory.getLog(MyUtil.class);
66
67     public static final String JavaDoc CSS_ROW_BODY = "portlet-section-body";
68     public static final String JavaDoc CSS_ROW_ALTERNATE = "portlet-section-alternate";
69
70     private static RankCache rankCache = RankCache.getInstance();
71
72     public static String JavaDoc filter(String JavaDoc input, boolean enableHTML, boolean enableEmotion,
73                                 boolean enableMVNCode, boolean enableNewLine, boolean enableURL) {
74         String JavaDoc output = input;
75
76         if (enableHTML) {
77             output = EnableHtmlTagFilter.filter(output);
78         } else {
79             output = DisableHtmlTagFilter.filter(output);
80         }
81
82         if (enableEmotion) {
83             output = EnableEmotionFilter.filter(output, ParamUtil.getContextPath() + MVNForumGlobal.EMOTION_DIR);
84         }
85
86         if (enableMVNCode) {
87             output = EnableMVNCodeFilter.filter(output);
88         }
89
90         if (enableNewLine) {
91             output = HtmlNewLineFilter.filter(output);
92         }
93
94         if (enableURL) {
95             output = URLFilter.filter(output);
96         }
97         return output;
98     }
99
100     public static String JavaDoc getMemberTitle(int postCount) {
101         String JavaDoc title = "";
102         try {
103             ArrayList rankBeans = rankCache.getBeans();
104             for (int i = 0; i < rankBeans.size(); i++) {
105                 RankBean rankBean = (RankBean)rankBeans.get(i);
106                 if (rankBean.getRankMinPosts() <= postCount) {
107                     title = EnableMVNCodeFilter.filter(rankBean.getRankTitle());
108                 } else {
109                     break;
110                 }
111             }//for
112
} catch (Exception JavaDoc ex) {
113             log.error("Exception in getMemberTitile", ex);
114         }
115         return title;
116     }
117
118     public static String JavaDoc getForumIconName(long lastLogon, long lastPost) {
119         String JavaDoc forumIcon = null;
120         if (lastLogon > lastPost) {// no new post
121
forumIcon = "f_norm_no.gif";
122         } else {// new post
123
forumIcon = "f_norm_new.gif";
124         }
125         return forumIcon;
126     }
127
128     public static String JavaDoc getThreadIconName(long lastLogon, long lastPost, int postCount) {
129         String JavaDoc threadIcon = null;
130         if (postCount < MVNForumConfig.getHotTopicThreshold()) {//not hot topic
131
if (lastLogon > lastPost) {// no new post
132
threadIcon = "f_norm_no.gif";
133             } else {// new post
134
threadIcon = "f_norm_new.gif";
135             }
136         } else {// hot topic
137
if (lastLogon > lastPost) {// no new post
138
threadIcon = "f_hot_no.gif";
139             } else {// new post
140
threadIcon = "f_hot_new.gif";
141             }
142         }
143         return threadIcon;
144     }
145
146     public static String JavaDoc getThreadStatusName(Locale locale, int threadStatus) {
147         String JavaDoc result = null;
148         switch (threadStatus) {
149         case ThreadBean.THREAD_STATUS_DEFAULT:
150             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.normal");
151             break;
152         case ThreadBean.THREAD_STATUS_DISABLED:
153             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.disabled");
154             break;
155         case ThreadBean.THREAD_STATUS_LOCKED:
156             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.locked");
157             break;
158         case ThreadBean.THREAD_STATUS_CLOSED:
159             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.status.closed");
160             break;
161         default:
162             //throw new AssertionException("Cannot find matching thread status.");
163
}
164         return result;
165     }
166
167     public static String JavaDoc getThreadTypeName(Locale locale, int threadType) {
168         String JavaDoc result = "Unknown";
169         switch (threadType) {
170         case ThreadBean.THREAD_TYPE_DEFAULT:
171             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.normal_thread");
172             break;
173         case ThreadBean.THREAD_TYPE_STICKY:
174             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.sticky_thread");
175             break;
176         case ThreadBean.THREAD_TYPE_FORUM_ANNOUNCEMENT:
177             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.announcement_thread");
178             break;
179         case ThreadBean.THREAD_TYPE_GLOBAL_ANNOUNCEMENT:
180             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.thread.type.global_announcement_thread");
181             break;
182         default:
183             //throw new AssertionException("Cannot find matching thread type.");
184
}
185         return result;
186     }
187
188     public static String JavaDoc getForumStatusName(Locale locale, int forumStatus) {
189         String JavaDoc result = null;
190         switch (forumStatus) {
191         case ForumBean.FORUM_STATUS_DEFAULT:
192             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.normal");
193             break;
194         case ForumBean.FORUM_STATUS_DISABLED:
195             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.disabled");
196             break;
197         case ForumBean.FORUM_STATUS_LOCKED:
198             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.locked");
199             break;
200         case ForumBean.FORUM_STATUS_CLOSED:
201             result = MVNForumResourceBundle.getString(locale, "mvnforum.common.forum.status.closed");
202             break;
203         default:
204             //throw new AssertionException("Cannot find matching forum status.");
205
}
206         return result;
207     }
208
209     public static boolean canViewAnyForumInCategory(int categoryID, MVNForumPermission permission) {
210         try {
211             Collection forumBeans = ForumCache.getInstance().getBeans();
212             for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
213                 ForumBean forumBean = (ForumBean)iter.next();
214                 if (forumBean.getCategoryID() == categoryID) {
215                     if (canViewForum(forumBean, permission)) {
216                         return true;
217                     }
218                 }
219             }
220         } catch (DatabaseException ex) {
221             log.error("Cannot load the data in table Forum", ex);
222         }
223         return false;
224     }
225
226     public static boolean canViewForum(ForumBean forumBean, MVNForumPermission permission) {
227         if (permission.canReadPost(forumBean.getForumID()) &&
228             (forumBean.getForumStatus() != ForumBean.FORUM_STATUS_DISABLED) ) {
229             return true;
230         }
231         return false;
232     }
233
234     public static int getViewablePosts(Collection forumBeans, MVNForumPermission permission) {
235         int count = 0;
236         for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
237             ForumBean forumBean = (ForumBean)iter.next();
238             if (canViewForum(forumBean, permission)) {
239                 count += forumBean.getForumPostCount();
240             }
241         }
242         return count;
243     }
244
245     public static int getViewableThreads(Collection forumBeans, MVNForumPermission permission) {
246         int count = 0;
247         for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
248             ForumBean forumBean = (ForumBean)iter.next();
249             if (canViewForum(forumBean, permission)) {
250                 count += forumBean.getForumThreadCount();
251             }
252         }
253         return count;
254     }
255
256     public static int getViewableForums(Collection forumBeans, MVNForumPermission permission) {
257         int count = 0;
258         for (Iterator iter = forumBeans.iterator(); iter.hasNext(); ) {
259             ForumBean forumBean = (ForumBean)iter.next();
260             if (canViewForum(forumBean, permission)) {
261                 count++;
262             }
263         }
264         return count;
265     }
266
267     public static int getViewableCategories(Collection categoryBeans, MVNForumPermission permission) {
268         int count = 0;
269         for (Iterator iter = categoryBeans.iterator(); iter.hasNext(); ) {
270             CategoryBean categoryBean = (CategoryBean)iter.next();
271             if (canViewAnyForumInCategory(categoryBean.getCategoryID(), permission)) {
272                 count++;
273             }
274         }
275         return count;
276     }
277
278     /**
279      * Get the String with a slash character '/' before the locale name
280      * @param localeName the user's preferred locale
281      * @return the String with a slash character '/' before the locale name if
282      * this locale is configed to support it. Otherwise,
283      * an empty String will be return
284      */

285     public static String JavaDoc getLocaleNameAndSlash(String JavaDoc localeName) {
286         if ( (localeName == null) || (localeName.length() == 0) ) {
287             return "";
288         }
289
290         String JavaDoc retValue = "";
291         String JavaDoc[] supportedLocales = MVNForumConfig.getSupportedLocaleNames();
292
293         if (supportedLocales == null) {
294             log.error("Assertion in MyUtil.getLocaleNameAndSlash. Please check your configuration.");
295             return "";
296         }
297
298         for (int i = 0; i < supportedLocales.length; i++) {
299             if (localeName.equals(supportedLocales[i])) {
300                 retValue = "/" + localeName;
301                 break;
302             }
303         }
304         return retValue;
305     }
306
307     public static String JavaDoc getCompanyCssPath(CompanyBean companyBean, String JavaDoc contextPath) {
308         String JavaDoc cssPath = null;
309         if (companyBean.getCompanyCss().length() > 0) {
310             cssPath = companyBean.getCompanyCss();
311         } else {
312             // use default company css
313
cssPath = MVNForumGlobal.COMPANY_DEFAULT_CSS_PATH;
314         }
315         return contextPath + cssPath;
316     }
317
318     public static String JavaDoc getCompanyLogoPath(CompanyBean companyBean, String JavaDoc contextPath) {
319         String JavaDoc logoPath = null;
320         if (companyBean.getCompanyLogo().length() > 0) {
321             logoPath = companyBean.getCompanyLogo();
322         } else {
323             // use default company logo
324
logoPath = MVNForumGlobal.COMPANY_DEFAULT_LOGO_PATH;
325         }
326         return contextPath + logoPath;
327     }
328
329     /**
330      * Get the locale from locale name
331      * @param localeName : in this format la_CO_VA, eg. en_US
332      * @return the locale instance of the localeName
333      */

334     public static Locale getLocale(String JavaDoc localeName) {
335         // now, find out the 3 elements of a locale: language, country, variant
336
String JavaDoc[] localeElement = StringUtil.getStringArray(localeName, "_");
337         String JavaDoc language = "";
338         String JavaDoc country = "";
339         String JavaDoc variant = "";
340         if (localeElement.length >= 1) {
341             language = localeElement[0];
342         }
343         if (localeElement.length >= 2) {
344             country = localeElement[1];
345         }
346         if (localeElement.length >= 3) {
347             variant = localeElement[2];
348         }
349         return new Locale(language, country, variant);
350     }
351
352     public static void ensureCorrectCurrentPassword(GenericRequest request)
353         throws BadInputException, AssertionException, DatabaseException, AuthenticationException {
354
355         if (request.isServletRequest()) {
356             ensureCorrectCurrentPassword(request.getServletRequest());
357         } else {
358             //@todo implement later
359
//throw new IllegalStateException("Not implemented.");
360
}
361     }
362
363     public static void ensureCorrectCurrentPassword(HttpServletRequest request)
364         throws BadInputException, AssertionException, DatabaseException, AuthenticationException {
365
366         OnlineUser onlineUser = OnlineUserManager.getInstance().getOnlineUser(request);
367         OnlineUserFactory onlineUserFactory = ManagerFactory.getOnlineUserFactory();
368
369         try {
370             if (onlineUser.getAuthenticationType() == OnlineUser.AUTHENTICATION_TYPE_REALM) {
371                 onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), OnlineUserManager.PASSWORD_OF_METHOD_REALM, true);
372             } else if (onlineUser.getAuthenticationType() == OnlineUser.AUTHENTICATION_TYPE_CUSTOMIZATION) {
373                 if(MVNForumConfig.getEnablePasswordlessAuth()) {
374                     // dont need password
375
onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), OnlineUserManager.PASSWORD_OF_METHOD_CUSTOMIZATION, true);
376                 } else {
377                     // must have password
378
// @todo: implement this case by using Authenticator
379
onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), OnlineUserManager.PASSWORD_OF_METHOD_CUSTOMIZATION, true);
380                 }
381             } else {
382                 //This user did not login by REALM or CUSTOMIZATION
383
String JavaDoc memberPassword = "";
384                 String JavaDoc memberPasswordMD5 = ParamUtil.getParameter(request, "md5pw", false);
385                 if (memberPasswordMD5.length() == 0 || (memberPasswordMD5.endsWith("==") == false)) {
386                     // md5 is not valid, try to use unencoded password method
387
memberPassword = ParamUtil.getParameterPassword(request, "MemberCurrentMatkhau", 3, 0);
388
389                     if (memberPassword.length() == 0) {
390                         throw new AssertionException("Cannot allow memberPassword's length is 0. Serious Assertion Failed.");
391                     }
392                 }
393
394                 // Please note that below code ONLY CORRECT when the ParamUtil.getParameterPassword
395
// return a NON-EMPTY string
396
if (memberPassword.length() > 0) {
397                     // that is we cannot find the md5 password
398
onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), memberPassword, false);
399                 } else {
400                     // have the md5, go ahead
401
onlineUserFactory.ensureCorrectPassword(onlineUser.getMemberName(), memberPasswordMD5, true);
402                 }
403             }
404         } catch (AuthenticationException e) {
405             Locale locale = I18nUtil.getLocaleInRequest(request);
406             String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.wrong_password");
407             throw new BadInputException(localizedMessage);
408             //throw new BadInputException("You have typed the wrong password. Cannot proceed.");
409
}
410     }
411
412     public static void writeMvnForumImage(HttpServletRequest request, HttpServletResponse response) throws IOException JavaDoc {
413
414         BufferedImage JavaDoc image = MVNForumInfo.getImage();
415         OutputStream JavaDoc outputStream = null;
416         try {
417             outputStream = response.getOutputStream();
418             response.setContentType("image/jpeg");
419
420             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
421             encoder.encode(image);
422
423             outputStream.flush();
424         } catch (IOException JavaDoc ex) {
425             throw ex;
426         } finally {
427             if (outputStream != null) {
428                 try {
429                     outputStream.close();
430                 } catch (IOException JavaDoc ex) { }
431             }
432         }
433     }
434
435     public static void writeMvnCoreImage(HttpServletRequest request, HttpServletResponse response) throws IOException JavaDoc {
436
437         BufferedImage JavaDoc image = MVNCoreInfo.getImage();
438         OutputStream JavaDoc outputStream = null;
439         try {
440             outputStream = response.getOutputStream();
441             response.setContentType("image/jpeg");
442
443             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outputStream);
444             encoder.encode(image);
445
446             outputStream.flush();
447         } catch (IOException JavaDoc ex) {
448             throw ex;
449         } finally {
450             if (outputStream != null) {
451                 try {
452                     outputStream.close();
453                 } catch (IOException JavaDoc ex) { }
454             }
455         }
456     }
457
458     public static void checkClassName(Locale locale, String JavaDoc className, boolean required) throws BadInputException {
459         if (required == false) {
460             if (className.length() == 0) return;
461         }
462
463         try {
464             Class.forName(className);
465         } catch (ClassNotFoundException JavaDoc ex) {
466             throw new BadInputException("Cannot load class: " + className);
467         }
468     }
469
470     public static void saveVNTyperMode(GenericRequest request, GenericResponse response) {
471
472         if (request.isServletRequest()) {
473             saveVNTyperMode(request.getServletRequest(), response.getServletResponse());
474         }
475     }
476
477     public static void saveVNTyperMode(HttpServletRequest request, HttpServletResponse response) {
478
479         String JavaDoc vnTyperMode = ParamUtil.getParameter(request, "vnselector");
480         if (vnTyperMode.equals("VNI") || vnTyperMode.equals("TELEX") ||
481             vnTyperMode.equals("VIQR") || vnTyperMode.equals("NOVN")) {
482             Cookie typerModeCookie = new Cookie(MVNForumConstant.VN_TYPER_MODE, vnTyperMode);
483             typerModeCookie.setPath("/");
484             response.addCookie(typerModeCookie);
485         }
486     }
487
488     // note that this method can check for duplicate but difference in case: Admin,admin,ADMIN
489
public static Hashtable checkMembers(String JavaDoc[] memberNames, Locale locale)
490         throws AssertionException, DatabaseException, BadInputException {
491
492         Hashtable memberMap = new Hashtable();
493         boolean isFailed = false;
494         StringBuffer JavaDoc missingNames = new StringBuffer JavaDoc(512);
495
496         for (int i = 0; i < memberNames.length; i++) {
497             int receivedMemberID = -1;
498             String JavaDoc memberName = memberNames[i];
499             StringUtil.checkGoodName(memberName);
500             try {
501                 receivedMemberID = DAOFactory.getMemberDAO().getMemberIDFromMemberName(memberName);
502             } catch (ObjectNotFoundException ex) {
503                 isFailed = true;
504                 if (missingNames.length() > 0) {
505                     missingNames.append(", ");
506                 }
507                 missingNames.append(memberName);
508                 continue;
509             }
510             memberMap.put(new Integer JavaDoc(receivedMemberID), memberName);
511         } // end for
512

513         if (isFailed) { // the receivers does not exist.
514
String JavaDoc localizedMessage = MVNForumResourceBundle.getString(locale, "mvncore.exception.BadInputException.receivers_are_not_members", new Object JavaDoc[] {missingNames});
515             throw new BadInputException(localizedMessage);
516         }
517         return memberMap;
518     }
519     
520     /**
521      * Check if the online user is Root Admin
522      */

523     public static boolean isRootAdmin(GenericRequest request) throws AuthenticationException, AssertionException, DatabaseException {
524         return ( OnlineUserManager.getInstance().getOnlineUser(request).getMemberID() == MVNForumConstant.MEMBER_ID_OF_ADMIN);
525     }
526
527     /**
528      * Check if the online user is Root Admin
529      */

530     public static boolean isRootAdmin(HttpServletRequest request) throws AuthenticationException, AssertionException, DatabaseException {
531         return ( OnlineUserManager.getInstance().getOnlineUser(request).getMemberID() == MVNForumConstant.MEMBER_ID_OF_ADMIN );
532     }
533
534     /**
535      * check if memberID belongs to admin's id
536      */

537     public static boolean isRootAdminID(int memberID) {
538         return (memberID == MVNForumConstant.MEMBER_ID_OF_ADMIN);
539     }
540
541     public static String JavaDoc getRowCSS(int rowIndex) {
542         return (rowIndex%2 == 0 ? CSS_ROW_BODY : CSS_ROW_ALTERNATE);
543     }
544     
545 // public static void checkInstance(String className, Class clazz) throws BadInputException {
546
// try {
547
// Class.forName(className);
548
// throw new BadInputException("Class " + className + " is not a implementation of " + clazz);
549
// } catch (ClassNotFoundException e) {
550
// e.printStackTrace();
551
// throw new BadInputException("Cannot load class " + className);
552
// }
553
// }
554
}
555
556
Popular Tags