1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.composite.validate.validators;
17
18 import java.util.List;
19
20 import net.sf.composite.StrictlyTypedComposite;
21 import net.sf.composite.composites.CompositeDecorator;
22 import net.sf.composite.util.ObjectUtils;
23 import net.sf.composite.validate.ComponentValidationException;
24
25 /***
26 * A simple component validator that requires at least one component be present
27 * in the composite and that there are no null components. If the composite is
28 * strictly typed, this composite also tests that each component is of the
29 * required type.
30 *
31 * @author Matt Sgarlata
32 * @since Mar 11, 2005
33 */
34 public class SimpleComponentValidator extends BaseCompositeValidator {
35
36 protected void validateImpl(Object composite) throws Exception {
37 List components = getComponentAccessor().getComponents(composite);
38
39 if (components == null) {
40 throw new ComponentValidationException(composite,
41 "components cannot be null");
42 }
43
44 for (int i = 0; i < components.size(); i++) {
45 if (components.get(i) == null) {
46 if (composite instanceof CompositeDecorator) {
47 composite = ((CompositeDecorator) composite).getComposite();
48 }
49 throw new ComponentValidationException(composite,
50 "all components in a composite must be non-null but the component at index " + i + " is null");
51 }
52 }
53
54
55
56 if (composite instanceof StrictlyTypedComposite) {
57 StrictlyTypedComposite stc = (StrictlyTypedComposite) composite;
58 for (int i = 0; i < components.size(); i++) {
59 Object component = components.get(i);
60 Class componentType = stc.getComponentType();
61 if (!(componentType.isAssignableFrom(component.getClass()))) {
62 throw new ComponentValidationException(
63 composite,
64 "the component at index "
65 + i
66 + ", "
67 + ObjectUtils.getObjectDescription(component)
68 + ", does not implement "
69 + ObjectUtils.getObjectDescription(stc.getComponentType()));
70 }
71 }
72 }
73 }
74
75 }