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