KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > barracuda > plankton > l10n > Locales


1 /*
2  * Copyright (C) 2003 Christian Cryder [christianc@granitepeaks.com]
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * $Id: Locales.java,v 1.5 2004/02/01 05:16:28 christianc Exp $
19  */

20 package org.enhydra.barracuda.plankton.l10n;
21
22 import java.util.*;
23 import javax.servlet.*;
24 import javax.servlet.http.*;
25
26 import org.apache.log4j.*;
27
28 import org.enhydra.barracuda.plankton.http.*;
29
30
31 /**
32  * Simple locale utilities. This class makes it easy to determine the target
33  * locale from an event context or a servlet request. You can also set the locale
34  * and ask the class to save the information for you (in a cookie and/or the
35  * session) so that the locale info will persist across muliple requests
36  */

37 public class Locales {
38
39     //default param names
40
public static String JavaDoc LANGAUGE_KEY = "$loc_lang";
41     public static String JavaDoc COUNTRY_KEY = "$loc_cntry";
42     public static String JavaDoc VARIANT_KEY = "$loc_var";
43
44     //persistance options
45
public static final int NONE = 0;
46     public static final int SESSION = 1;
47     public static final int COOKIES_AND_SESSION = 2;
48
49     //default persistance option
50
public static int PERSIST_DEFAULT = SESSION;
51
52     protected static final Logger logger = Logger.getLogger(Locales.class.getName());
53     private static final String JavaDoc LOCALE = Localize.class.getName()+".Locale";
54
55     /**
56      * Get the client locale from a ServletRequest using the default
57      * param keys and persist option
58      *
59      * @param req the HttpServletRequest from which we'd like to determine Locale
60      * @param resp the HttpServletResponse (needed if we want to save Locale in a cookie
61      * otherwise it may be null)
62      * @return the target client Locale
63      */

64     public static Locale getClientLocale(HttpServletRequest req, HttpServletResponse resp) {
65         return getClientLocale(req, resp, LANGAUGE_KEY, COUNTRY_KEY, VARIANT_KEY, PERSIST_DEFAULT);
66     }
67
68     /**
69      * This method attempts to get the client locale.
70      *
71      * <p>First we look to see if we can determine the locale by the req's
72      * form parameters (language, country, variant). If not, we look in
73      * the session to see if we can get the information from there. If
74      * that fails, we see if we can get the information from a client
75      * cookie (where the value is a comma delimited string containing
76      * language, country, and variant. If we still haven't got the locale
77      * information, we try and retrieve it from the servlet request, and
78      * if that fails, we use the default locale.
79      *
80      * <p>In each of these cases we save (depending on persistOption) the
81      * locale info in both the session and in a client cookie (so as to
82      * speed lookups on subsequent requests).
83      *
84      * @param req the HttpServletRequest from which we'd like to determine Locale
85      * @param resp the HttpServletResponse (needed if we want to save Locale in a cookie
86      * otherwise it may be null)
87      * @param languageKey the key to be used to look in the request for a
88      * language paramter
89      * @param countryKey the key to be used to look in the request for a
90      * country paramter
91      * @param variantKey the key to be used to look in the request for a
92      * variant paramter
93      * @param persistOption how we'd like to persist the Locale (by default, it will be stored
94      * in the SESSION)
95      * @return the target client Locale
96      */

97     public static Locale getClientLocale(HttpServletRequest req, HttpServletResponse resp, String JavaDoc languageKey, String JavaDoc countryKey, String JavaDoc variantKey, int persistOption) {
98         Locale loc = null;
99         if (req!=null) {
100             //first look for manual form parameters; if we find it here
101
//be sure to store the locale both as a cookie and in the session
102
if (loc==null) {
103                 String JavaDoc language = req.getParameter(languageKey);
104                 String JavaDoc country = req.getParameter(countryKey);
105                 String JavaDoc variant = req.getParameter(variantKey);
106                 if (language!=null) {
107                     if (logger.isDebugEnabled()) logger.debug("Found locale in req params");
108                     loc = getLocale(language, country, variant);
109                     saveClientLocale(req, resp, loc, persistOption);
110                 }
111             }
112
113             //next look in the session to see if we can find it there; if so,
114
//make sure we save it as a cookie too
115
if (loc==null && persistOption>=SESSION) {
116                 HttpSession session = SessionServices.getSession(req);
117                 if (session!=null) {
118                     if (logger.isDebugEnabled()) logger.debug("Found locale in session");
119                     loc = (Locale) session.getAttribute(LOCALE);
120                     saveClientLocale(req, resp, loc, persistOption);
121                 }
122             }
123
124             //next see if there is a locale cookie; if there is,
125
//make sure we set the locale in the session as well
126
if (loc==null && persistOption>=COOKIES_AND_SESSION) {
127                 Cookie[] cookies = req.getCookies();
128                 if (cookies!=null) {
129                     for (int i=0, max=cookies.length; i<max; i++) {
130                         if (cookies[i].getName().equals(LOCALE)) {
131                             if (logger.isDebugEnabled()) logger.debug("Found locale in cookie");
132                             loc = readLocaleFromCookie(cookies[i]);
133                             saveClientLocale(req, resp, loc, persistOption);
134                         }
135                     }
136                 }
137             }
138
139             //if we still haven't found a locale, look for it in the servlet
140
//request; be sure to store the locale both as a cookie and in
141
//the session
142
if (loc==null) {
143                 if (logger.isDebugEnabled()) logger.debug("Getting it from servlet request");
144                 loc = req.getLocale();
145                 saveClientLocale(req, resp, loc, persistOption);
146             }
147         }
148         //finally as a last resort, create a default locale; be sure to
149
//store the locale both as a cookie and in the session
150
if (loc==null) {
151             if (logger.isDebugEnabled()) logger.debug("Finding default locale");
152             loc = Locale.getDefault();
153             saveClientLocale(req, resp, loc, persistOption);
154         }
155         if (logger.isDebugEnabled()) logger.debug("return locale "+loc);
156         return loc;
157     }
158
159     private static Locale getLocale(String JavaDoc language, String JavaDoc country, String JavaDoc variant) {
160         Locale locale = null;
161         if (language!=null) {
162             if (country==null) country = "";
163             if (variant!=null) locale = new Locale(language, country, variant);
164             else locale = new Locale(language, country);
165         }
166         return locale;
167     }
168
169
170     private static Locale readLocaleFromCookie(Cookie cookie) {
171         String JavaDoc value = cookie.getValue();
172         String JavaDoc language = null;
173         String JavaDoc country = null;
174         String JavaDoc variant = null;
175         StringTokenizer st = new StringTokenizer(value,",");
176         if (st.hasMoreTokens()) language = st.nextToken();
177         if (st.hasMoreTokens()) country = st.nextToken();
178         if (st.hasMoreTokens()) variant = st.nextToken();
179         Locale locale = getLocale(language, country, variant);
180         if (logger.isDebugEnabled()) logger.debug("Got locale "+locale+" from cookie! (value="+value+")");
181         return locale;
182     }
183
184     private static void writeLocaleInSession(HttpServletRequest req, Locale locale) {
185         if (req==null) return;
186         HttpSession session = SessionServices.getSession(req);
187         if (locale!=null) session.setAttribute(LOCALE, locale);
188         else session.removeAttribute(LOCALE);
189         if (logger.isDebugEnabled()) logger.debug("updated locale: "+locale+" in session!");
190     }
191
192     private static void writeLocaleInCookie(HttpServletResponse resp, Locale locale) {
193         if (resp==null) return;
194         String JavaDoc value = null;
195         if (locale!=null) value = locale.getLanguage()+","+locale.getCountry()+","+locale.getVariant();
196         Cookie cookie = new Cookie(LOCALE, value);
197         cookie.setMaxAge(locale!=null ? Integer.MAX_VALUE : 0);
198         resp.addCookie(cookie);
199         if (logger.isDebugEnabled()) logger.debug("updated locale: "+locale+" in cookie!");
200     }
201
202     /**
203      * Here we actually force a locale to be saved using the default
204      * persist option. It will be stored in a cookie and/or the session.
205      *
206      * @param req the HttpServletRequest (needed to get the HttpSession)
207      * @param resp the HttpServletResponse (needed if we want to save Locale
208      * in a cookie otherwise it may be null)
209      * @param loc the target client locale we'd like to set
210      */

211     public static void saveClientLocale(HttpServletRequest req, HttpServletResponse resp, Locale loc) {
212         saveClientLocale(req, resp, loc, PERSIST_DEFAULT);
213     }
214
215     /**
216      * Here we actually force a locale to be saved. It will be stored in
217      * a cookie and/or the session.
218      *
219      * @param req the HttpServletRequest (needed to get the HttpSession)
220      * @param resp the HttpServletResponse (needed if we want to save Locale
221      * in a cookie otherwise it may be null)
222      * @param loc the target client locale we'd like to set
223      * @param persistOption the specific persistOption to be used
224      */

225     public static void saveClientLocale(HttpServletRequest req, HttpServletResponse resp, Locale loc, int persistOption) {
226         //save it in the session
227
if (persistOption>=SESSION) writeLocaleInSession(req, loc);
228
229         //save it as a cookie
230
if (persistOption>=COOKIES_AND_SESSION) writeLocaleInCookie(resp, loc);
231     }
232
233     /**
234      * Release a client locale (this effectively removes it from whereever
235      * it might have been persisted)
236      *
237      * @param req the HttpServletRequest (needed to get the HttpSession)
238      * @param resp the HttpServletResponse (needed if we want to clear Locale
239      * from a cookie otherwise it may be null)
240      */

241     public static void releaseClientLocale(HttpServletRequest req, HttpServletResponse resp) {
242         releaseClientLocale(req, resp, PERSIST_DEFAULT);
243     }
244
245     /**
246      * Release a client locale (this effectively removes it from whereever
247      * it might have been persisted)
248      *
249      * @param req the HttpServletRequest (needed to get the HttpSession)
250      * @param resp the HttpServletResponse (needed if we want to clear Locale
251      * from a cookie otherwise it may be null)
252      * @param persistOption the specific persistOption to be used (this tells us
253      * where the locale info needs to be removed from)
254      */

255     public static void releaseClientLocale(HttpServletRequest req, HttpServletResponse resp, int persistOption) {
256         //save it in the session
257
if (persistOption>=SESSION) writeLocaleInSession(req, null);
258
259         //save it as a cookie
260
if (persistOption>=COOKIES_AND_SESSION) writeLocaleInCookie(resp, null);
261     }
262
263     /**
264      * This utility function will run through a list of Locales
265      * and return the index of the locale that matches most closely.
266      * If none of them match whatsoever, return the defaultIndex
267      *
268      * @param targetLocale the target locale
269      * @param locales the array of locales to search
270      * @param defaultIndex the default index (if no match is found)
271      * @return the index of the closest matching locale
272      */

273     public static int findClosestLocale(Locale targetLocale, Locale[] locales, int defaultIndex) {
274         int match2 = -1;
275         int match1 = -1;
276
277         for (int i=0, max=locales.length; i<max; i++) {
278             //if we find a direct match (language, country, variant) return immediately
279
if (targetLocale.equals(locales[i])) return i;
280
281             //if we can match on 2, save a reference to the index
282
if (targetLocale.getLanguage().equals(locales[i].getLanguage()) &&
283                 targetLocale.getCountry().equals(locales[i].getCountry())) match2 = i;
284
285             //if we just match on language, save a reference to the index
286
if (targetLocale.getLanguage().equals(locales[i].getLanguage())) match1 = i;
287         }
288         if (match2!=-1) return match2;
289         else if (match1!=-1) return match1;
290         else return defaultIndex;
291     }
292
293 }
294
Popular Tags