1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package be.objectify.led.factory.type;
17
18 import be.objectify.led.FactoryResolver;
19 import be.objectify.led.GenericTypes;
20 import be.objectify.led.ObjectFactory;
21 import be.objectify.led.TypeFactory;
22 import be.objectify.led.factory.object.MapFactory;
23 import be.objectify.led.util.StringUtils;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 import java.lang.reflect.Field;
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.StringTokenizer;
31
32
33
34
35
36 public class MapTypeFactory implements TypeFactory<Map>
37 {
38 private static final Logger LOGGER = LoggerFactory.getLogger(MapTypeFactory.class);
39
40 private final FactoryResolver factoryResolver;
41
42 public MapTypeFactory(FactoryResolver factoryResolver)
43 {
44 this.factoryResolver = factoryResolver;
45 }
46
47
48
49
50 public MapFactory createObjectFactory(Class[] classes,
51 Field field)
52 {
53 return new MapFactory(classes[0],
54 classes[1],
55 field,
56 factoryResolver)
57 {
58 protected Map parse(String propertyName,
59 String propertyValue,
60 ObjectFactory keyObjectFactory,
61 ObjectFactory valueObjectFactory)
62 {
63 Map map = new HashMap();
64 if (!StringUtils.isEmpty(propertyValue))
65 {
66 for (StringTokenizer stringTokenizer = new StringTokenizer(propertyValue); stringTokenizer.hasMoreTokens();)
67 {
68 String s = stringTokenizer.nextToken();
69 String[] strings = s.split(":");
70 if (strings.length == 2)
71 {
72 map.put(keyObjectFactory.createObject(propertyName,
73 strings[0]),
74 valueObjectFactory.createObject(propertyName,
75 strings[1]));
76 }
77 else
78 {
79 LOGGER.error("Could not separate [{}] into key:value",
80 propertyValue);
81 }
82 }
83 }
84 return map;
85 }
86
87 protected Map createMap()
88 {
89 return new HashMap();
90 }
91 };
92 }
93
94
95
96
97 public Class<Map> getBoundClass()
98 {
99 return Map.class;
100 }
101
102
103
104
105 public Class[] determineClassType(Class fieldType,
106 GenericTypes genericTypes)
107 {
108 if (genericTypes == null || genericTypes.value().length != 2)
109 {
110 throw new RuntimeException("GenericTypes(key class, value class) annotation required to determine Map key:value types");
111 }
112 Class[] classes = genericTypes.value();
113 return new Class[]{ classes[0], classes[1] };
114 }
115 }