01: package org.conform;
02:
03: import org.conform.format.FormatFactory;
04: import org.conform.format.ResourceProvider;
05:
06: import java.lang.reflect.Field;
07: import java.lang.reflect.Method;
08: import java.util.*;
09:
10: /**
11: * A domain provider for hibernate UserType pseudo enumerations.
12: * It is using <code>type.getClass().getName() + "." + o.toString()</code> as the key to ResourceProvider
13: * and a java.text.Collator for locale-sensitive sorting.
14: */
15: public class NoEnumDomainProvider extends AbstractDomainProvider {
16: protected Class type;
17: protected List<String> names;
18: protected List<Object> literals;
19:
20: public NoEnumDomainProvider(Class type) {
21: super (null);
22: this .type = type;
23: }
24:
25: public NoEnumDomainProvider(String propertyName, Class type) {
26: super (propertyName);
27: this .type = type;
28: }
29:
30: @Override
31: protected List createValues() {
32: try {
33: Method namesMethod = type.getMethod("names");
34: names = (List<String>) namesMethod.invoke(null);
35: literals = new ArrayList(names.size());
36: for (int i = 0; i < type.getFields().length; i++) {
37: Field field = type.getFields()[i];
38: Object value = field.get(null);
39: if (value != null
40: && type.isAssignableFrom(value.getClass()))
41: literals.add(value);
42: }
43:
44: List list = new ArrayList(literals);
45: list.add(0, null);
46: return list;
47: } catch (Exception e) {
48: throw new RuntimeException("" + propertyName, e);
49: }
50: }
51:
52: @Override
53: protected String formatValue(Object object) {
54: if (object == null)
55: return null;
56:
57: if (literals == null)
58: getDomain();
59:
60: int index = literals.indexOf(object);
61: if (index != -1)
62: object = names.get(index);
63:
64: FormatFactory formatFactory = FormatFactory.getInstance();
65: Locale locale = formatFactory.getLocale();
66: ResourceProvider resourceProvider = formatFactory
67: .getResourceProvider();
68: return resourceProvider.getMessage(locale, type.getName() + "."
69: + object);
70: }
71: }
|