1 package org.apache.turbine.services.localization;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import java.util.Locale;
20 import java.util.StringTokenizer;
21
22 import org.apache.commons.configuration.Configuration;
23
24 import org.apache.turbine.Turbine;
25 import org.apache.turbine.util.RunData;
26
27 /***
28 * This class returns a Locale object based on the HTTP
29 * Accept-Language header.
30 *
31 * This class is based on examples from Jason Hunter's book <i>Java
32 * Servlet Programming</i>.
33 *
34 * @author <a href="mailto:frank.kim@clearink.com">Frank Y. Kim</a>
35 * @author <a href="mailto:jon@collab.net">Jon S. Stevens</a>
36 * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>
37 * @version $Id: LocaleDetector.java 264148 2005-08-29 14:21:04Z henning $
38 * @deprecated Use LocaleTokenizer instead.
39 */
40 public class LocaleDetector
41 {
42 /***
43 * Attempts to pull the "Accept-Language" header out of the
44 * HttpServletRequest object and then parse it. If the header is
45 * not present, it will return a null Locale.
46 *
47 * @param data Turbine information.
48 * @return A Locale.
49 */
50 public static Locale getLocale(RunData data)
51 {
52 String header = data.getRequest().getHeader("Accept-Language");
53 if (header == null || header.length() == 0)
54 return null;
55 return getLocale(header);
56 }
57
58 /***
59 * This method parses the Accept-Language header and attempts to
60 * create a Locale out of it.
61 *
62 * @param languageHeader A String with the language header.
63 * @return A Locale.
64 */
65 public static Locale getLocale(String languageHeader)
66 {
67 Configuration conf = Turbine.getConfiguration();
68
69
70
71 if (languageHeader == null ||
72 languageHeader.trim().equals(""))
73 {
74 return new Locale(
75 conf.getString("locale.default.language", "en"),
76 conf.getString("locale.default.country", "US"));
77 }
78
79
80
81
82 StringTokenizer tokenizer = new StringTokenizer(languageHeader, ",");
83
84
85
86 String language = tokenizer.nextToken();
87
88
89 return getLocaleForLanguage(language.trim());
90
91 }
92
93 /***
94 * This method creates a Locale from the language.
95 *
96 * @param language A String with the language.
97 * @return A Locale.
98 */
99 private static Locale getLocaleForLanguage(String language)
100 {
101 Locale locale;
102 int semi, dash;
103
104
105 if ((semi = language.indexOf(';')) != -1)
106 {
107 language = language.substring(0, semi);
108 }
109
110 language = language.trim();
111
112
113
114 if ((dash = language.indexOf('-')) == -1)
115 {
116
117 locale = new Locale(language, "");
118 }
119 else
120 {
121 locale = new Locale(language.substring(0, dash),
122 language.substring(dash + 1));
123 }
124
125 return locale;
126 }
127 }