01: package org.osbl.spring;
02:
03: import org.conform.format.ResourceProvider;
04: import org.springframework.context.MessageSource;
05: import org.springframework.context.NoSuchMessageException;
06: import org.springframework.beans.BeansException;
07:
08: import java.util.Locale;
09: import java.util.List;
10:
11: public class SpringResourceProvider implements ResourceProvider {
12: MessageSource messageSource;
13: List<Locale> supportedLocales;
14:
15: public void setMessageSource(MessageSource messageSource)
16: throws BeansException {
17: this .messageSource = messageSource;
18: }
19:
20: /**
21: * Get a localized message in a UserPrincipal independent way.
22: *
23: * @param locale
24: * the localization
25: * @param code
26: * the key for the resource bundle
27: * @param args
28: * arguments for the localization (string replacement)
29: * @return localized value for the message key
30: */
31: public String getMessage(Locale locale, String code, Object... args) {
32: String msg;
33: try {
34: msg = messageSource.getMessage(code, args, locale);
35: if (msg == null || msg.length() == 0) {
36: msg = shorten(code);
37: }
38: } catch (NoSuchMessageException e) {
39: try {
40: msg = messageSource.getMessage(generifyCode(code),
41: args, locale);
42: if (msg == null || msg.length() == 0) {
43: msg = shorten(code);
44: }
45: } catch (NoSuchMessageException ee) {
46: msg = shorten(code);
47: }
48: }
49:
50: return msg;
51: }
52:
53: private String shorten(String code) {
54: int len = code.length();
55: if (len > 23)
56: return "..." + code.substring(len - 20);
57: else
58: return code;
59: }
60:
61: public List<Locale> getSupportedLocales() {
62: return supportedLocales;
63: }
64:
65: public void setSupportedLocales(List<Locale> supportedLocales) {
66: this .supportedLocales = supportedLocales;
67: }
68:
69: static String generifyCode(String code) {
70: if (code == null)
71: return code;
72:
73: int pos = code.indexOf(".buttons.");
74: if (pos != -1)
75: return "businessobject" + code.substring(pos);
76: pos = code.indexOf(".messages.");
77: if (pos != -1)
78: return "businessobject" + code.substring(pos);
79: pos = code.indexOf(".titles.");
80: if (pos != -1)
81: return "businessobject" + code.substring(pos);
82: pos = code.lastIndexOf('.');
83: if (pos != -1)
84: return "businessobject" + code.substring(pos);
85:
86: return code;
87: }
88: }
|