01: /*
02: * Created on Nov 23, 2004
03: */
04: package uk.org.ponder.springutil;
05:
06: import java.text.MessageFormat;
07: import java.util.Locale;
08:
09: import org.springframework.context.MessageSource;
10: import org.springframework.context.support.DefaultMessageSourceResolvable;
11:
12: import uk.org.ponder.localeutil.LocaleGetter;
13: import uk.org.ponder.messageutil.MessageLocator;
14: import uk.org.ponder.util.Logger;
15:
16: /**
17: * An adaptation of the Spring "MessageSource" to the RSF/PUC "MessageLocator"
18: * interface. MessageLocator, as well as supplying a greater variety of
19: * "utility" methods, guarantees to always to resolve to at least some form of
20: * default message rather than propagating exceptions.
21: * @author Antranig Basman (antranig@caret.cam.ac.uk)
22: *
23: */
24: public class SpringMessageLocator extends MessageLocator {
25: private MessageSource messagesource;
26: private LocaleGetter localegetter;
27: private String defaultmessagekey;
28: private String defaultmessage = "[Message for key {0} not found]";
29:
30: public void setMessageSource(MessageSource messagesource) {
31: this .messagesource = messagesource;
32: }
33:
34: public void setLocaleGetter(LocaleGetter localegetter) {
35: this .localegetter = localegetter;
36: }
37:
38: public String getMessage(String[] codes, Object[] args) {
39: DefaultMessageSourceResolvable dmsr = new DefaultMessageSourceResolvable(
40: codes, args);
41: Locale locale = localegetter == null ? Locale.getDefault()
42: : localegetter.get();
43: try {
44: return messagesource.getMessage(dmsr, locale);
45: } catch (Exception nsme) {
46: Logger.log.warn("Failed to look up message " + codes[0]
47: + ", falling back to default", nsme);
48: try {
49: if (defaultmessagekey != null) {
50: return messagesource.getMessage(defaultmessagekey,
51: null, locale);
52: }
53: } catch (Exception nsme2) {
54: }
55: }
56: MessageFormat mf = new MessageFormat(defaultmessage);
57: return mf.format(new Object[] { codes[0] });
58: }
59:
60: /** The ultimate fallback message to be rendered in the case of complete
61: * failure to resolve for a message.
62: */
63: public void setDefaultMessage(String defaultmessage) {
64: this .defaultmessage = defaultmessage;
65: }
66:
67: /** A message key for a default message, to be tried in the underlying
68: * MessageSource *before* finally falling
69: * back to defaultMessage.
70: */
71: public void setDefaultMessageKey(String defaultmessagekey) {
72: this.defaultmessagekey = defaultmessagekey;
73: }
74:
75: }
|