1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.caches.memcached;
17
18 import java.beans.BeanInfo;
19 import java.beans.IntrospectionException;
20 import java.beans.Introspector;
21 import java.beans.PropertyDescriptor;
22 import java.lang.reflect.Method;
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.Properties;
26
27
28
29
30
31
32 abstract class AbstractPropertySetter<T> {
33
34
35
36
37 private static Map<String, Method> WRITERS = new HashMap<String, Method>();
38
39 static {
40 try {
41 BeanInfo memcachedConfigInfo = Introspector.getBeanInfo(MemcachedConfiguration.class);
42 for (PropertyDescriptor descriptor : memcachedConfigInfo.getPropertyDescriptors()) {
43 WRITERS.put(descriptor.getName(), descriptor.getWriteMethod());
44 }
45 } catch (IntrospectionException e) {
46
47 }
48 }
49
50
51
52
53 private final String propertyKey;
54
55
56
57
58 private final String propertyName;
59
60
61
62
63 private final Method propertyWriterMethod;
64
65
66
67
68 private final T defaultValue;
69
70
71
72
73
74
75
76
77
78
79
80 public AbstractPropertySetter(final String propertyKey, final String propertyName, final T defaultValue) {
81 this.propertyKey = propertyKey;
82 this.propertyName = propertyName;
83
84 this.propertyWriterMethod = WRITERS.get(propertyName);
85 if (this.propertyWriterMethod == null) {
86 throw new RuntimeException(
87 "Class '" + MemcachedConfiguration.class.getName() + "' doesn't contain a property '" + propertyName + "'");
88 }
89
90 this.defaultValue = defaultValue;
91 }
92
93
94
95
96
97
98
99
100
101 public final void set(Properties config, MemcachedConfiguration memcachedConfiguration) {
102 String propertyValue = config.getProperty(propertyKey);
103 T value;
104
105 try {
106 value = this.convert(propertyValue);
107 if (value == null) {
108 value = defaultValue;
109 }
110 } catch (Exception e) {
111 value = defaultValue;
112 }
113
114 try {
115 propertyWriterMethod.invoke(memcachedConfiguration, value);
116 } catch (Exception e) {
117 throw new RuntimeException("Impossible to set property '" + propertyName + "' with value '" + value
118 + "', extracted from ('" + propertyKey + "'=" + propertyValue + ")", e);
119 }
120 }
121
122
123
124
125
126
127
128
129
130
131
132
133 protected abstract T convert(String value) throws Exception;
134
135 }