01: package org.vraptor.i18n;
02:
03: import org.vraptor.LogicRequest;
04:
05: import java.util.Locale;
06:
07: public class JstlWrapper {
08: private static final String DEFAULT_BUNDLE_NAME = "messages";
09:
10: public Object find(LogicRequest context, String name) {
11: if (context.getRequestContext().hasAttribute(name + ".request")) {
12: return context.getRequestContext().getAttribute(
13: name + ".request");
14: } else if (context.getSessionContext().hasAttribute(
15: name + ".session")) {
16: return context.getSessionContext().getAttribute(
17: name + ".session");
18: } else if (context.getApplicationContext().hasAttribute(
19: name + ".application")) {
20: return context.getApplicationContext().getAttribute(
21: name + ".application");
22: }
23: return context.getRequest().getSession().getServletContext()
24: .getInitParameter(name);
25: }
26:
27: public Locale findLocale(LogicRequest context) {
28: Object obj = find(context, "javax.servlet.jsp.jstl.fmt.locale");
29: if (obj instanceof String) {
30: return stringToLocale((String) obj);
31: } else if (obj != null) {
32: return (Locale) obj;
33: } else {
34: return context.getRequest().getLocale();
35: }
36: }
37:
38: /**
39: * Extracted from XStream project, copyright Joe Walnes
40: * @param str the string to convert
41: * @return the locale
42: */
43: public Locale stringToLocale(String str) {
44: int[] underscorePositions = underscorePositions(str);
45: String language, country, variant;
46: if (underscorePositions[0] == -1) { // "language"
47: language = str;
48: country = "";
49: variant = "";
50: } else if (underscorePositions[1] == -1) { // "language_country"
51: language = str.substring(0, underscorePositions[0]);
52: country = str.substring(underscorePositions[0] + 1);
53: variant = "";
54: } else { // "language_country_variant"
55: language = str.substring(0, underscorePositions[0]);
56: country = str.substring(underscorePositions[0] + 1,
57: underscorePositions[1]);
58: variant = str.substring(underscorePositions[1] + 1);
59: }
60: return new Locale(language, country, variant);
61: }
62:
63: private int[] underscorePositions(String in) {
64: int[] result = new int[2];
65: for (int i = 0; i < result.length; i++) {
66: int last = i == 0 ? 0 : result[i - 1];
67: result[i] = in.indexOf('_', last + 1);
68: }
69: return result;
70: }
71:
72: public Locale findFallbackLocale(LogicRequest context) {
73: Object obj = find(context,
74: "javax.servlet.jsp.jstl.fmt.fallbackLocale");
75: if (obj instanceof String) {
76: return stringToLocale((String) obj);
77: } else if (obj != null) {
78: return (Locale) obj;
79: } else {
80: return context.getRequest().getLocale();
81: }
82: }
83:
84: public String findLocalizationContext(LogicRequest request) {
85: String localizationContext = (String) find(request,
86: "javax.servlet.jsp.jstl.fmt.localizationContext");
87: if (localizationContext == null) {
88: localizationContext = DEFAULT_BUNDLE_NAME;
89: }
90: return localizationContext;
91: }
92: }
|