View Javadoc
1   /*******************************************************************************
2    * Portions created by Sebastian Thomschke are copyright (c) 2005-2011 Sebastian
3    * Thomschke.
4    * 
5    * All Rights Reserved. This program and the accompanying materials
6    * are made available under the terms of the Eclipse Public License v1.0
7    * which accompanies this distribution, and is available at
8    * http://www.eclipse.org/legal/epl-v10.html
9    * 
10   * Contributors:
11   *     Sebastian Thomschke - initial implementation.
12   *******************************************************************************/
13  package net.sf.oval.constraint;
14  
15  import static net.sf.oval.Validator.getCollectionFactory;
16  
17  import java.util.Map;
18  
19  import net.sf.oval.Validator;
20  import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
21  import net.sf.oval.context.OValContext;
22  import net.sf.oval.internal.util.StringUtils;
23  
24  /**
25   * @author Sebastian Thomschke
26   */
27  public class InstanceOfCheck extends AbstractAnnotationCheck<InstanceOf>
28  {
29  	private static final long serialVersionUID = 1L;
30  
31  	private Class< ? >[] types;
32  
33  	@Override
34  	public void configure(final InstanceOf constraintAnnotation)
35  	{
36  		super.configure(constraintAnnotation);
37  		setTypes(constraintAnnotation.value());
38  	}
39  
40  	@Override
41  	protected Map<String, String> createMessageVariables()
42  	{
43  		final Map<String, String> messageVariables = getCollectionFactory().createMap(2);
44  		if (types.length == 1)
45  			messageVariables.put("types", types[0].getName());
46  		else
47  		{
48  			final String[] classNames = new String[types.length];
49  			for (int i = 0, l = classNames.length; i < l; i++)
50  				classNames[i] = types[i].getName();
51  			messageVariables.put("types", StringUtils.implode(classNames, ","));
52  		}
53  		return messageVariables;
54  	}
55  
56  	/**
57  	 * @return the type
58  	 */
59  	public Class< ? >[] getTypes()
60  	{
61  		return types;
62  	}
63  
64  	public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context,
65  			final Validator validator)
66  	{
67  		if (valueToValidate == null) return true;
68  
69  		for (final Class< ? > type : types)
70  			if (!type.isInstance(valueToValidate)) return false;
71  		return true;
72  	}
73  
74  	/**
75  	 * @param types the types to set
76  	 */
77  	public void setTypes(final Class< ? >... types)
78  	{
79  		this.types = types;
80  		requireMessageVariablesRecreation();
81  	}
82  }