/*
* file: CollectionConstraint.java
* package: oreilly.hcj.datamodeling.constraints
*
* This software is granted under the terms of the Common Public License,
* CPL, which may be found at the following URL:
* http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
*
* Copyright(c) 2003-2005 by the authors indicated in the @author tags.
* All Rights are Reserved by the various authors.
*
########## DO NOT EDIT ABOVE THIS LINE ########## */
package oreilly.hcj.datamodeling.constraints;
import java.util.Collection;
import java.util.Iterator;
/**
* Models a constraint on Collection objects.
*
* <p>
* Objects of this class are immutable.
* </p>
*
* @author <a href="mailto:worderisor@yahoo.com">Robert Simmons jr.</a>
* @version $Revision: 1.1 $
*/
public class CollectionConstraint extends ObjectConstraint {
/** Holds value of property containedType. */
private 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
*/
public CollectionConstraint(final String name, final boolean optional,
final Class dataType, final Class containedType) {
super(name, optional, dataType);
if (!Collection.class.isAssignableFrom(dataType)) {
throw new IllegalArgumentException("The dataType must be a Collection"); //$NON-NLS-1$
}
this.containedType = containedType;
}
/**
* Getter for property containedType.
*
* @return Value of property containedType.
*/
public Class getContainedType() {
return this.containedType;
}
/**
* 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.
*/
public void validate(final Object obj) {
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);
}
}
}
}
}
/* ########## End of File ########## */
|