View Javadoc

1   /*
2    * Copyright 2004-2005, 2007 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * the License at
7    * 
8    * http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
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  		// do this outside of previous loop because instanceof is a relatively
55  		// expensive operation
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  }