]> git.argeo.org Git - lgpl/argeo-commons.git/blob - Msg.java
dd38c7483563b3cd551cc69ccc25c49802565e0e
[lgpl/argeo-commons.git] / Msg.java
1 package org.argeo.cms.i18n;
2
3 import java.lang.reflect.Field;
4 import java.lang.reflect.Modifier;
5
6 import org.argeo.cms.CmsException;
7 import org.argeo.cms.CmsSession;
8 import org.eclipse.rap.rwt.RWT;
9
10 /** A single message to be internationalised. */
11 public class Msg {
12 private String id;
13 private ClassLoader classLoader;
14 private final Object defaultLocal;
15
16 public Msg() {
17 defaultLocal = null;
18 }
19
20 public Msg(Object defaultMessage) {
21 this.defaultLocal = defaultMessage;
22 }
23
24 public String getId() {
25 return id;
26 }
27
28 public void setId(String id) {
29 this.id = id;
30 }
31
32 public ClassLoader getClassLoader() {
33 return classLoader;
34 }
35
36 public void setClassLoader(ClassLoader classLoader) {
37 this.classLoader = classLoader;
38 }
39
40 public Object getDefault() {
41 return defaultLocal;
42 }
43
44 public String toString() {
45 return local().toString();
46 }
47
48 /** When used as the first word of a sentence. */
49 public String lead() {
50 String raw = toString();
51 return raw.substring(0, 1).toUpperCase(RWT.getLocale())
52 + raw.substring(1);
53 }
54
55 public Object local() {
56 CmsSession cmSession = CmsSession.current.get();
57 Object local = cmSession.local(this);
58 if (local == null)
59 local = getDefault();
60 if (local == null)
61 throw new CmsException("No translation found for " + id);
62 return local;
63 }
64
65 public static void init(Class<?> clss) {
66 final Field[] fieldArray = clss.getDeclaredFields();
67 ClassLoader loader = clss.getClassLoader();
68
69 for (Field field : fieldArray) {
70 if (Modifier.isStatic(field.getModifiers())
71 && field.getType().isAssignableFrom(Msg.class)) {
72 try {
73 Object obj = field.get(null);
74 String id = clss.getCanonicalName() + "." + field.getName();
75 obj.getClass().getMethod("setId", String.class)
76 .invoke(obj, id);
77 obj.getClass()
78 .getMethod("setClassLoader", ClassLoader.class)
79 .invoke(obj, loader);
80 } catch (Exception e) {
81 throw new CmsException("Cannot prepare field " + field);
82 }
83 }
84 }
85 }
86 }