KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > nemesis > forum > webapp > front > Tools


1 /*
2  * NEMESIS-FORUM.
3  * Copyright (C) 2002 David Laurent(lithium2@free.fr). All rights reserved.
4  *
5  * Copyright (c) 2000 The Apache Software Foundation. All rights reserved.
6  *
7  * Copyright (C) 2001 Yasna.com. All rights reserved.
8  *
9  * Copyright (C) 2000 CoolServlets.com. All rights reserved.
10  *
11  * NEMESIS-FORUM. is free software; you can redistribute it and/or
12  * modify it under the terms of the Apache Software License, Version 1.1,
13  * or (at your option) any later version.
14  *
15  * NEMESIS-FORUM core framework, NEMESIS-FORUM backoffice, NEMESIS-FORUM frontoffice
16  * application are parts of NEMESIS-FORUM and are distributed under
17  * same terms of licence.
18  *
19  *
20  * NEMESIS-FORUM includes software developed by the Apache Software Foundation (http://www.apache.org/)
21  * and software developed by CoolServlets.com (http://www.coolservlets.com).
22  * and software developed by Yasna.com (http://www.yasna.com).
23  *
24  */

25 package org.nemesis.forum.webapp.front;
26
27 import java.text.SimpleDateFormat JavaDoc;
28 import java.util.Date JavaDoc;
29
30 import javax.servlet.http.Cookie JavaDoc;
31 import javax.servlet.http.HttpServletRequest JavaDoc;
32 import javax.servlet.http.HttpServletResponse JavaDoc;
33 import javax.servlet.http.HttpSession JavaDoc;
34
35 import org.nemesis.forum.Authorization;
36 import org.nemesis.forum.AuthorizationFactory;
37 import org.nemesis.forum.Message;
38 import org.nemesis.forum.exception.NotFoundException;
39 import org.nemesis.forum.exception.UnauthorizedException;
40 import org.nemesis.forum.util.CookieManager;
41 import org.nemesis.forum.util.StringUtils;
42
43 /**
44  * @author dlaurent
45  */

46 public class Tools {
47     /** Name of the authentication token (is stored in the user's session) */
48     public static final String JavaDoc AUTH_TOKEN = "_Authorization_";
49
50     /** Name of the cookie used to store user info for auto-login purposes */
51     public static final String JavaDoc AUTOLOGIN_COOKIE = "_AutoLogin_";
52
53     /** Name of the last visited token (is stored in the user's session) */
54     public static final String JavaDoc LASTVISITED_TOKEN = "_LastVisited_";
55
56     /** Name of the cookie used to store last visited timestamp */
57     public static final String JavaDoc LASTVISITED_COOKIE = "_LastVisited_";
58
59     
60
61     /**
62          * Returns an Authorization token for the user. The following steps are
63          * performed to determine the token:<ol>
64          *
65          * <li>Check the session for the existence of a authorization token.
66          * If one is found, it is returned as we assume that the user has logged
67          * in and is authorized.
68          * <li>Check the authorization cookie for a username and password. If found,
69          * attempt to create a authorization token using that data. If
70          * successful, save the token to the session and return it.
71          * NOTE: This check can be skipped by setting
72          * <code>checkCookie</code> to false.
73          * </ol><p>
74          *
75          * @param request the HttpServletRequest object, known as "request" in a
76          * JSP page.
77          * @param response the HttpServletResponse object, known as "response" in
78          * a JSP page.
79          * @param checkCookie a boolean that indicates whether or not we want
80          * to use a cookie for authorization.
81          * @return the authorization token if authenticated, otherwise
82          * <code>null</code>.
83          * @see Authorization
84          */

85     public static Authorization getUserAuthorization(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, boolean checkCookie) {
86         // we can get the session object from the request object:
87
HttpSession JavaDoc session = request.getSession();
88
89         // Check 1: check for the authentication token in the user's session.
90
Authorization authToken = (Authorization) session.getAttribute(AUTH_TOKEN);
91         if (authToken != null) {
92             return authToken;
93         }
94
95         // Check 2: check the cookie for username and password, if we're allowing that
96
if (checkCookie) {
97             Cookie JavaDoc cookie = CookieManager.getCookie(request, AUTOLOGIN_COOKIE);
98             try {
99                 if (cookie != null) {
100                     // at this point, we found a cookie so grab the username & password
101
// from it, create an authorization token and store that in the session
102
String JavaDoc[] values = CookieManager.decodePasswordCookie(cookie.getValue());
103                     String JavaDoc username = values[0];
104                     String JavaDoc password = values[1];
105                     // try to validate the user based on the info from the cookie
106
authToken = AuthorizationFactory.getAuthorization(username, password);
107
108                     // put that token in the user's session:
109
session.setAttribute(AUTH_TOKEN, authToken);
110
111                     // return the authorization token
112
return authToken;
113                 }
114             } catch (Exception JavaDoc e) {
115                 //We want any exceptions in this block to be caught so that an
116
//anonymous authorization token can be returned. The
117
//getAuthorzation(username,password) method above throws an
118
//UnauthorizedException. In the case of this exception or others,
119
//the cookie holds invalid login info, so we should remove it:
120
CookieManager.setCookie(response, AUTOLOGIN_COOKIE, null, 0);
121             }
122         }
123
124         //Got this far, so return null.
125
return null;
126     }
127
128     /**
129      * Returns an Authorization token for the user. This is a convenience method
130      * that that calls the other getUserAuthorization method with
131      * <code>checkCookie</code> set to true.
132      *
133      * @param request the HttpServletRequest object, known as "request" in a
134      * JSP page.
135      * @param response The HttpServletResponse object, known as "response" in
136      * a JSP page.
137      * @return The authorization token if authenticated, otherwise
138      * <code>null</code>.
139      */

140     public static Authorization getUserAuthorization(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
141         return getUserAuthorization(request, response, true);
142     }
143
144     /**
145      * Validates the user and optionally enables auto-login by creating an
146      * auto-login cookie.
147      *
148      * @param request the HttpServletRequest object, known as "request" in a JSP page.
149      * @param response the HttpServletResponse object, known as "response" in a JSP page.
150      * @param username the username.
151      * @param password the password.
152      * @param autoLogin if <code>true</code> create a cookie that enables auto-login.
153      * @throws UserNotFoundException
154      * @throws UnauthorizedException
155      * @return The authorization token if authenticated, otherwise
156      * <code>null</code>
157      */

158     public static Authorization setUserAuthorization(
159         HttpServletRequest JavaDoc request,
160         HttpServletResponse JavaDoc response,
161         String JavaDoc username,
162         String JavaDoc password,
163         boolean autoLogin)
164         throws NotFoundException, UnauthorizedException {
165         HttpSession JavaDoc session = request.getSession();
166         Authorization authToken = AuthorizationFactory.getAuthorization(username, password);
167         session.setAttribute(AUTH_TOKEN, authToken);
168
169         if (autoLogin) {
170             CookieManager.setCookie(response, AUTOLOGIN_COOKIE, CookieManager.encodePasswordCookie(username, password), CookieManager.MAX_COOKIE_AGE);
171         }
172
173         return authToken;
174     }
175
176     /**
177      * Invalidates the cookie that otherwise lets a user auto-login.
178      *
179      * @param request The HttpServletRequest object, known as "request" in a JSP page.
180      * @param response The HttpServletResponse object, known as "response" in a JSP page.
181      */

182     public static void removeUserAuthorization(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
183         HttpSession JavaDoc session = request.getSession();
184         session.removeAttribute(AUTH_TOKEN);
185         
186         CookieManager.setCookie(response, AUTOLOGIN_COOKIE, null,0);
187             
188     }
189
190     /**
191          * Returns the time in milliseconds that the user last visited the system.
192          *
193          * @param request the HttpServletRequest object, known as "request" on a JSP page.
194          * @param response the HttpServletRequest object, known as "response" on a JSP page.
195          * @param updateLastVisitedTime Set to <code>true</code> if you wish to update
196          * the user's last visited time to the current time; set to <code>false</code> otherwise.
197          * @return The time (in milliseconds) that the suer last visited .
198          */

199     public static long getLastVisited(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, boolean updateLastVisitedTime) {
200         //Get session object
201
HttpSession JavaDoc session = request.getSession();
202
203         //The current instant in time.
204
long now = System.currentTimeMillis();
205
206         //First, try to retrieve the value from the session
207
String JavaDoc lastTime = (String JavaDoc) session.getAttribute(LASTVISITED_TOKEN);
208
209         //Found a value in the session, so return it
210
if (lastTime != null) {
211             try {
212                 long time = Long.parseLong(lastTime);
213                 // update the last visited time to now, but don't update the
214
// last visited time in the session:
215
CookieManager.setCookie(response, LASTVISITED_TOKEN, Long.toString(now), CookieManager.MAX_COOKIE_AGE);
216                 // return the time value
217
return time;
218             } catch (NumberFormatException JavaDoc e) {
219                 //log.error("",e);
220
}
221         }
222
223         // getting to this point means no time value was found in the session,
224
// so look for it in the cookie:
225
long time = now;
226         lastTime = CookieManager.getCookieValue(request, LASTVISITED_TOKEN);
227         if (lastTime != null) {
228             try {
229                 time = Long.parseLong(lastTime);
230             } catch (NumberFormatException JavaDoc e) {
231             }
232         }
233
234         // set the value in the cookie, return the time
235

236         session.setAttribute(LASTVISITED_TOKEN, Long.toString(time));
237         CookieManager.setCookie(response, LASTVISITED_TOKEN, Long.toString(now), CookieManager.MAX_COOKIE_AGE);
238
239         return time;
240     }
241     /**
242      * Returns the time in milliseconds that the user last visited .
243      *
244      * @param request the HttpServletRequest object, known as "request" on a JSP page.
245      * @param response the HttpServletRequest object, known as "response" on a JSP page.
246      * @return The time (in milliseconds) that the suer last visited .
247      */

248     public static long getLastVisited(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) {
249         return getLastVisited(request, response, true);
250     }
251     
252     private static final long SECOND = 1000;
253         private static final long MINUTE = 60 * SECOND;
254         private static final long HOUR = 60 * MINUTE;
255         private static final long DAY = 24 * HOUR;
256         private static final long WEEK = 7 * DAY;
257 // Days of the week
258
private static final String JavaDoc[] DAYS_OF_WEEK =
259           { "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" };
260
261       // SimpleDateFormat objects for use in the dateToText method
262
private static final SimpleDateFormat JavaDoc dateFormatter =
263           new SimpleDateFormat JavaDoc("EEEE, MMM d 'at' h:mm a");
264       private static final SimpleDateFormat JavaDoc yesterdayFormatter =
265           new SimpleDateFormat JavaDoc("'Yesterday at' h:mm a");
266     /**
267          * Returns a String describing the amount of time between now (current
268          * system time) and the passed in date time. Example output is "5 hours
269          * ago" or "Yesterday at 3:30 pm"
270          *
271          * @param date the Date to compare the current time with.
272          * @return a description of the difference in time, ie: "5 hours ago"
273          * or "Yesterday at 3:30pm"
274          */

275         public static String JavaDoc dateToText(Date JavaDoc date) {
276             if (date == null) {
277                 return "";
278             }
279
280             long delta = System.currentTimeMillis() - date.getTime();
281
282             // within the last hour
283
if ((delta / HOUR) < 1) {
284                 long minutes = (delta / MINUTE);
285                 if (minutes == 0) {
286                     return "Less than 1 min ago";
287                 } else if (minutes == 1) {
288                     return "1 minute ago";
289                 } else {
290                     return (minutes + " minutes ago");
291                 }
292             }
293
294             // sometime today
295
if ((delta / DAY) < 1) {
296                 long hours = (delta / HOUR);
297                 if (hours <= 1) {
298                     return "1 hour ago";
299                 } else {
300                     return (hours + " hours ago");
301                 }
302             }
303
304             // within the last week
305
if ((delta / WEEK) < 1) {
306                 double days = ((double) delta / (double) DAY);
307                 if (days <= 1.0) {
308                     return yesterdayFormatter.format(date);
309                 } else {
310                     return dateFormatter.format(date);
311                 }
312             }
313
314             // before a week ago
315
else {
316                 return dateFormatter.format(date);
317             }
318         }
319         
320
321     /**
322      * Formats the unfiltered body of a message to make it appear in the "quote
323      * original" format. This is simply the body of the message with the
324      * delimiter appended to the beginning of each line. The delimiter
325      * is most often "> " by convention. A desired length for each line in the
326      * returned String can be specified to aid in formatting.<p>
327      *
328      * This method uses message.getUnfilteredBody() in order to get the body of
329      * the message. This usually yields better results for the formatting
330      * required by this method. However, it also has the potential of being
331      * a security risk if malicious HTML code is embedded in the body. Therefore,
332      * you should always filter HTML from the result of this method before
333      * showing it in an environment where HTML is interpreted. If you are
334      * showing the results of this method in an HTML &lt;textarea&gt;, there is
335      * no need to worry about malicious HTML.
336      *
337      * @param message the message to quote.
338      * @param delimiter a String that will start each line of the quoted
339      * message. For example, "> ";
340      * @param lineLength the desired length of each line in the quoted message.
341      * @return the unfiltered body of the message in the "quote original" format.
342      */

343     public static String JavaDoc quoteOriginal(String JavaDoc body, String JavaDoc delimiter, int lineLength) {
344         if (body == null || body.length() == 0) {
345             return "";
346         }
347         int length = body.length();
348         //Create a StringBuffer to hold the quoted body; approximate size.
349
StringBuffer JavaDoc buf = new StringBuffer JavaDoc(body.length());
350         //i maintains the current position in the String.
351
for (int i = 0; i < length;) {
352             String JavaDoc partialString = StringUtils.chopAtWord(body.substring(i), lineLength);
353             
354             i += partialString.length() + 1;
355             buf.append(delimiter).append(partialString.trim()).append("\\n");
356         }
357         return buf.toString();
358     }
359     
360     /**
361          * Returns true if the message has been created or updated since
362          * the last time the user visisted.
363          *
364          * @param message the message to check.
365          * @param lastVisted the time the user last visisted the forum.
366          * @return true if the message has been created or updated since the user's
367          * last visit.
368          */

369         public static boolean isNewMessage(Message message, long lastVisited) {
370             if (message.getModifiedDate().getTime() > lastVisited) {
371                 return true;
372             } else {
373                 return false;
374             }
375         }
376
377 }
378
Popular Tags