FileDocCategorySizeDatePackage
CollectionConstraint.javaAPI DocExample3265Sun Dec 14 22:47:40 GMT 2003oreilly.hcj.datamodeling.constraints

CollectionConstraint

public class CollectionConstraint extends ObjectConstraint
Models a constraint on Collection objects.

Objects of this class are immutable.

author
Robert Simmons jr.
version
$Revision: 1.1 $

Fields Summary
private Class
containedType
Holds value of property containedType.
Constructors Summary
public CollectionConstraint(String name, boolean optional, Class dataType, Class containedType)
Creates a new instance of CollectionConstraint.

param
name Contains the name of the constraint.
param
optional Indicates if the property is optional.
param
dataType The data type of the object being constrained.
param
containedType The type of values in the container; null if it doesnt matter.
throws
IllegalArgumentException If dataType isn't a subclass of Collection.
see
mirror.datamodel.constraints.Constraint

		super(name, optional, dataType);

		if (!Collection.class.isAssignableFrom(dataType)) {
			throw new IllegalArgumentException("The dataType must be a Collection");  //$NON-NLS-1$
		}

		this.containedType = containedType;
	
Methods Summary
public java.lang.ClassgetContainedType()
Getter for property containedType.

return
Value of property containedType.

		return this.containedType;
	
public voidvalidate(java.lang.Object obj)
Validate the given object against the constraint. Checks to make sure the collection is not null if not allowed. If a non-null collection is passed then the members of the collection are tested to be of the type given for the set contents. Passing null for a data type allows all data types.

param
obj The object to validate.
throws
ConstraintException If the constraint is violated.

		if (obj == null) {
			throw new ConstraintException(ConstraintExceptionType.NULL_NOT_ALLOWED);
		}
		if (!getDataType()
		         .isAssignableFrom(obj.getClass())) {
			throw new ConstraintException(ConstraintExceptionType.INVALID_DATA_TYPE);
		}
		Collection coll = (Collection)obj;
		if (coll.isEmpty()) {
			if (!isOptional()) {
				throw new ConstraintException(ConstraintExceptionType.COLLECTION_CANNOT_BE_EMPTY);
			}
		}
		if (containedType != null) {
			Iterator iter = coll.iterator();
			while (iter.hasNext()) {
				if (!containedType.isAssignableFrom(iter.next().getClass())) {
					throw new ConstraintException(ConstraintExceptionType.INVALID_COLLECTION_MEMBER);
				}
			}
		}