01: package org.vraptor.reflection;
02:
03: import java.lang.reflect.ParameterizedType;
04: import java.lang.reflect.Type;
05: import java.util.Collection;
06: import java.util.Iterator;
07:
08: import org.vraptor.component.ComponentInstantiationException;
09:
10: /**
11: * Collection implementation.
12: *
13: * @author Guilherme Silveira
14: */
15: public class CollectionDealer implements SetDealer {
16:
17: @SuppressWarnings("unchecked")
18: public Object resizeAndSet(Object object, int position,
19: boolean mayCreate, Type type) throws SettingException {
20: int length = position + 1;
21:
22: Collection collection = (Collection) object;
23: int realLen = collection.size();
24:
25: if (realLen >= length) {
26: return object;
27: }
28:
29: if ((!mayCreate) || length != realLen + 1) {
30: throw new SettingException(
31: "Invalid array index - probably missed one object in between: "
32: + length);
33: }
34:
35: Class desiredClass = (type instanceof ParameterizedType) ? (Class) ((ParameterizedType) type)
36: .getActualTypeArguments()[0]
37: : Object.class;
38:
39: try {
40: collection.add(ReflectionUtil.instantiate(desiredClass));
41: } catch (ComponentInstantiationException e) {
42: throw new SettingException(e.getMessage(), e);
43: }
44: return object;
45:
46: }
47:
48: public Object getPosition(Object object, int arrayPosition,
49: boolean mayCreate) throws SettingException {
50: Collection collection = (Collection) object;
51: if (arrayPosition >= collection.size()) {
52: throw new SettingException("Invalid collection index: "
53: + arrayPosition);
54: }
55: return iterate((Collection) object, arrayPosition);
56: }
57:
58: /**
59: * Iterates over a collection n times
60: *
61: * @param collection
62: * the collection
63: * @param index
64: * n
65: * @return the object at this position
66: */
67: Object iterate(Collection set, int index) {
68: Iterator it = set.iterator();
69: for (int i = 0; i < index; i++, it.next()) {
70: ;
71: }
72: return it.next();
73: }
74:
75: @SuppressWarnings("unchecked")
76: public Object resizeAndSet(Object obj, int position, Object value)
77: throws SettingException {
78: Collection collection = (Collection) obj;
79: if (collection.size() > position) {
80: throw new SettingException(
81: "There is already an object in this position!");
82: }
83: if (collection.size() != position) {
84: throw new SettingException(
85: "Invalid array index - probably missed one object in between: "
86: + position);
87: }
88: collection.add(value);
89: return obj;
90: }
91:
92: public Class getType(Type type) {
93: return (Class) ((ParameterizedType) type)
94: .getActualTypeArguments()[0];
95: }
96:
97: }
|