/
ObjectFactory.java
337 lines (299 loc) · 12.8 KB
/
ObjectFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package ants;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.MappingJsonFactory;
import org.codehaus.jackson.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ants.annotation.ConfigurableClass;
import ants.annotation.ConfigurableMethod;
import ants.api.Configurable;
import ants.api.IObjectFactory;
import ants.exception.ObjectConfigureException;
import ants.exception.ObjectCreateException;
import ants.exception.ObjectIncompleteException;
import ants.exception.ParseException;
public class ObjectFactory implements IObjectFactory {
private static final Logger logger = LoggerFactory.getLogger(ObjectFactory.class);
private static JsonFactory jsonMapper = new MappingJsonFactory();
private static int autoId = 0;
@Override
public Configurable create(String id, String defaultClass, String tagName) throws ObjectConfigureException, ParseException {
return ObjectStore.getInstance(id, defaultClass, tagName);
}
/**
* parse a json string into an object tree.
*
* @throws ParseException
*/
public static JsonNode parse(String json) throws ParseException {
try {
return ObjectFactory.parse(json,
new ByteArrayInputStream(json.getBytes("utf-8")));
} catch (UnsupportedEncodingException ex) {
// ignored, we dont expect this with utf-8
throw new RuntimeException(ex);
}
}
/**
* parse a json stream into an object tree.
*
* @throws ParseException
*/
public static JsonNode parse(String identifier, InputStream json)
throws ParseException {
JsonNode node = null;
try {
JsonParser parser = jsonMapper.createJsonParser(json);
node = parser.readValueAsTree();
} catch (IOException ex) {
throw new ParseException("Failed to parse JSON: "
+ identifier, ex);
}
return node;
}
/**
* create and configure the object with the given object tree
*
* @throws ObjectConfigureException
*/
public static Configurable configure(JsonNode tree, String defaultClass,
String tagName, String id, String defaultListItemClass,
String listItemTag) throws ObjectConfigureException {
Stack<String> tagStack = new Stack<String>();
Exception ex = null;
try {
return ObjectFactory.configure(tree, defaultClass, tagName,
id, defaultListItemClass, listItemTag, tagStack);
} catch (SecurityException e) {
ex = e;
} catch (IllegalArgumentException e) {
ex = e;
} catch (NoSuchMethodException e) {
ex = e;
} catch (IllegalAccessException e) {
ex = e;
} catch (InvocationTargetException e) {
ex = e;
} catch (ObjectCreateException e) {
ex = e;
} catch (ObjectIncompleteException e) {
ex = e;
} catch (ClassNotFoundException e) {
ex = e;
} catch (InstantiationException e) {
ex = e;
}
String tagStackString = Util.implode(tagStack, "=>");
throw new ObjectConfigureException("Failed to configure: "
+ tagStackString, ex);
}
/**
* Internal method to create and configure the object recursively with the
* given node
*/
private static Configurable configure(JsonNode node,
String defaultClass, String tagName, String id,
String defaultListItemClass, String listItemTag,
Stack<String> tagStack)
throws ObjectCreateException, ObjectIncompleteException,
SecurityException, IllegalArgumentException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException,
ClassNotFoundException, InstantiationException {
Configurable object = ObjectFactory.create(node, defaultClass,
tagName, id);
tagStack.push(object.toTagString());
logger.debug("Configuring node: {}", tagStack.peek());
Class<?> klass = object.getClass();
ConfigurableClass kannotation = klass.getAnnotation(ConfigurableClass.class);
if (node.isValueNode()) {
Method method = klass.getMethod(Const.setValue, String.class);
method.invoke(object, node.asText());
} else if (node.isArray() || ((null != kannotation) && kannotation.expectsList())) {
ObjectFactory.configureWithList(object, node, defaultListItemClass, listItemTag, tagStack);
} else if (node.isObject()) {
ObjectFactory.configureWithObjects(object, (ObjectNode) node, tagStack);
}
tagStack.pop();
return object;
}
/**
* Internal method to configure the object recursively with the given node's
* children, treating them as child objects
*/
private static void configureWithObjects(Configurable object, ObjectNode node,
Stack<String> tagStack) throws ObjectCreateException,
ObjectIncompleteException, SecurityException,
IllegalArgumentException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException,
ClassNotFoundException, InstantiationException {
HashSet<String> setMethods = new HashSet<String>();
Class<?> klass = object.getClass();
ConfigurableClass kannotation = klass.getAnnotation(ConfigurableClass.class);
boolean expectsValue = (null == kannotation ? false : kannotation.expectsValue());
Iterator<Entry<String, JsonNode>> it = node.getFields();
while (it.hasNext()) {
Entry<String, JsonNode> entry = it.next();
String childTagName = entry.getKey();
JsonNode childNode = entry.getValue();
// attributes
if (childTagName.startsWith("@")) {
object.setAttribute(childTagName.substring(1), childNode.asText());
continue;
}
String setMethodName = Const.set
+ childTagName.substring(0, 1).toUpperCase()
+ childTagName.substring(1);
Method method;
if(expectsValue) {
method = klass.getMethod(setMethodName, String.class);
method.invoke(object, childNode.asText());
} else {
method = klass.getMethod(setMethodName, Configurable.class);
ConfigurableMethod mannotation = method
.getAnnotation(ConfigurableMethod.class);
String defaultClass = "";
String defaultListItemClass = "";
String listItemTag = "";
if(null != mannotation) {
defaultClass = mannotation.defaultClass();
defaultListItemClass = mannotation.defaultListItemClass();
listItemTag = mannotation.listItemTag();
}
Configurable childObject = ObjectFactory.configure(childNode,
defaultClass, childTagName, "",
defaultListItemClass, listItemTag, tagStack);
method.invoke(object, childObject);
}
setMethods.add(setMethodName);
}
ObjectFactory.verify(object, setMethods);
}
/**
* Internal method to configure the object recursively with the given node's
* children treating them as a list of child objects
*/
private static void configureWithList(Configurable object, JsonNode node,
String defaultListItemClass, String listItemTag,
Stack<String> tagStack)
throws ObjectCreateException, ObjectIncompleteException,
SecurityException, IllegalArgumentException, NoSuchMethodException,
IllegalAccessException, InvocationTargetException,
ClassNotFoundException, InstantiationException {
Class<?> klass = object.getClass();
Method method = klass.getMethod(Const.setList, LinkedHashMap.class);
ConfigurableMethod mannotation = method
.getAnnotation(ConfigurableMethod.class);
if(null != mannotation) {
if(listItemTag.isEmpty()) {
listItemTag = mannotation.listItemTag();
}
if(defaultListItemClass.isEmpty()) {
defaultListItemClass = mannotation.defaultListItemClass();
}
}
LinkedHashMap<String, Configurable> childList = new LinkedHashMap<String, Configurable>();
if (node.isArray()) {
Iterator<JsonNode> it = node.getElements();
while (it.hasNext()) {
Configurable childObject = ObjectFactory.configure(it.next(),
defaultListItemClass, listItemTag, "", "", "", tagStack);
childList.put(childObject.getId(), childObject);
}
} else if (node.isObject()) {
Iterator<Entry<String, JsonNode>> it = node.getFields();
while (it.hasNext()) {
Entry<String, JsonNode> entry = it.next();
String childId = entry.getKey();
JsonNode childNode = entry.getValue();
// attributes
if (childId.startsWith("@")) {
object.setAttribute(childId.substring(1), childNode.asText());
continue;
}
Configurable childObject = ObjectFactory.configure(childNode,
defaultListItemClass, listItemTag, childId, "", "", tagStack);
childList.put(childObject.getId(), childObject);
}
}
method.invoke(object, childList);
}
/**
* Verifies if all required parameters are set on an object after it is
* configured
*/
private static void verify(Configurable object, Set<String> setMethods)
throws ObjectIncompleteException {
ArrayList<String> missingParams = new ArrayList<String>();
Class<?> klass = object.getClass();
Method[] methods = klass.getMethods();
for (Method method : methods) {
ConfigurableMethod mannotation = method
.getAnnotation(ConfigurableMethod.class);
if (null != mannotation) {
String methodName = method.getName();
boolean required = mannotation.required();
if (required && !setMethods.contains(methodName)) {
missingParams.add(methodName.substring(3).toLowerCase());
}
}
}
if (missingParams.size() > 0) {
String error = "Missing required parameters: "
+ Util.implode(missingParams, Const.comma);
throw new ObjectIncompleteException(error);
}
}
/**
* instantiate an Configurable object using the class name specified in the
* JsonNode or the provided default class name.
*/
private static Configurable create(JsonNode node, String defaultClass,
String tagName, String id) throws ObjectCreateException,
ClassNotFoundException, SecurityException, NoSuchMethodException,
IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException {
String className = defaultClass;
if (node.isObject()) {
JsonNode classNode = node.get(Const.attribute.nodeClass);
if (null != classNode) {
className = classNode.asText();
}
}
if (className.isEmpty()) {
if (node.isValueNode()) {
className = Const.thefault.StringClass;
} else {
className = Const.thefault.ParamsClass;
}
}
if (id.isEmpty()) {
JsonNode idNode = node.get(Const.attribute.nodeId);
if (null != idNode) {
id = idNode.asText();
}
if(id.isEmpty()) {
id = String.format("_id_%d", ObjectFactory.autoId++);
}
}
Class<?> klass = Class.forName(className);
Constructor<?> tc = klass.getConstructor(String.class, String.class);
Object t = tc.newInstance(tagName, id);
return (Configurable) t;
}
}