1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.composite.extract.extractors;
17
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Set;
24
25 import net.sf.composite.StrictlyTypedComposite;
26 import net.sf.composite.extract.ComponentAccessorException;
27 import net.sf.composite.util.ClassUtils;
28 import net.sf.composite.util.ObjectUtils;
29
30 /***
31 * Extracts the components from a composite that stores its components as an
32 * array or {@link java.util.Collection}. Can set the components of arrays,
33 * Lists and Sets.
34 *
35 * @author Matt Sgarlata
36 * @since Mar 11, 2005
37 */
38 public class ContainerPropertyComponentAccessor extends BasePropertyComponentAccessor {
39
40 protected List getComponentsImpl(Object composite) throws Exception {
41 Object components = invokeGetter(composite, getComponentProperty());
42 if (components == null) {
43 return null;
44 }
45 if (components instanceof Object[]) {
46 return Arrays.asList((Object[]) components);
47 }
48 if (components instanceof Collection) {
49 return new ArrayList((Collection) components);
50 }
51 throw new ComponentAccessorException(
52 "Components were retrieved, but were of an unrecognized type, '"
53 + ObjectUtils.getObjectDescription(components.getClass())
54 + "'. Only object arrays and Collections are gettable with this accessor");
55 }
56
57 protected void setComponentsImpl(Object composite,
58 List components) throws Exception {
59
60
61 Class type = getType(composite, getComponentProperty());
62
63
64 if (components == null) {
65 invokeSetter(composite, getComponentProperty(), null);
66 }
67 else if (type.isArray()) {
68 Object[] array;
69 if (composite instanceof StrictlyTypedComposite) {
70 array = (Object[]) ClassUtils.createArray(
71 ((StrictlyTypedComposite) composite).getComponentType(),
72 components.size());
73 components.toArray(array);
74 }
75 else {
76 array = components.toArray();
77 }
78 invokeSetter(composite, getComponentProperty(), array);
79 }
80 else if (Set.class.isAssignableFrom(type)) {
81 invokeSetter(composite, getComponentProperty(), new HashSet(components));
82 }
83 else if (Collection.class.isAssignableFrom(type)) {
84 invokeSetter(composite, getComponentProperty(), components);
85 }
86 else {
87 throw new ComponentAccessorException(
88 "Components to be set were of an unrecognized type, '"
89 + ObjectUtils.getObjectDescription(components.getClass())
90 + "'. Only object arrays and certain types of Collections are settable with this accessor");
91 }
92 }
93 }