FileDocCategorySizeDatePackage
ObjectConstraint.javaAPI DocExample2829Sun Dec 14 22:47:42 GMT 2003oreilly.hcj.datamodeling.constraints

ObjectConstraint.java

/*
 *     file: ObjectConstraint.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;

/**  
 * Models a constraint on a property.
 * 
 * <p>
 * This constraint enforces whether an object can be null as well as if the data type of
 * the object beign validated is the same or subclass of the data type given.
 * </p>
 * 
 * <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 ObjectConstraint extends Constraint {
	/** Holds the error message for attempting to validate primitives. */
	private static final String ERR_PRIMITIVE = "The dataType cannot be a primitive";  //$NON-NLS-1$

	/** Holds value of property dataType. */
	private Class dataType;

	/** Holds value of property optional. */
	private boolean optional;

	/** 
	 * Creates a new instance of Constraint.
	 *
	 * @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.
	 *
	 * @throws IllegalArgumentException If dataType is a primitive.
	 *
	 * @see mirror.datamodel.constraints.Constraint
	 */
	public ObjectConstraint(final String name, final boolean optional,
	                        final Class dataType) {
		super(name);
		if (dataType.isPrimitive()) {
			throw new IllegalArgumentException(ERR_PRIMITIVE);
		}
		this.optional = optional;
		this.dataType = dataType;
	}

	/** 
	 * Getter for property dataType.
	 *
	 * @return Value of property dataType.
	 */
	public Class getDataType() {
		return this.dataType;
	}

	/** 
	 * Getter for property optional.
	 *
	 * @return Value of property optional.
	 */
	public boolean isOptional() {
		return this.optional;
	}

	/** 
	 * Validate the given object against the constraint.
	 *
	 * @param obj The object to validate.
	 *
	 * @throws ConstraintException If the constraint is violated.
	 */
	public void validate(final Object obj) {
		if (obj == null) {
			if (!optional) {
				throw new ConstraintException(ConstraintExceptionType.NULL_NOT_ALLOWED);
			}
		} else {
			if (!dataType.isAssignableFrom(obj.getClass())) {
				throw new ConstraintException(ConstraintExceptionType.INVALID_DATA_TYPE);
			}
		}
	}
}

/* ########## End of File ########## */