001 /******************************************************************************* 002 * Portions created by Sebastian Thomschke are copyright (c) 2005-2011 Sebastian 003 * Thomschke. 004 * 005 * All Rights Reserved. This program and the accompanying materials 006 * are made available under the terms of the Eclipse Public License v1.0 007 * which accompanies this distribution, and is available at 008 * http://www.eclipse.org/legal/epl-v10.html 009 * 010 * Contributors: 011 * Sebastian Thomschke - initial implementation. 012 *******************************************************************************/ 013 package net.sf.oval.constraint; 014 015 import static net.sf.oval.Validator.getCollectionFactory; 016 017 import java.util.Map; 018 019 import net.sf.oval.Validator; 020 import net.sf.oval.configuration.annotation.AbstractAnnotationCheck; 021 import net.sf.oval.context.OValContext; 022 import net.sf.oval.internal.util.StringUtils; 023 024 /** 025 * @author Sebastian Thomschke 026 */ 027 public class InstanceOfAnyCheck extends AbstractAnnotationCheck<InstanceOfAny> 028 { 029 private static final long serialVersionUID = 1L; 030 031 private Class< ? >[] types; 032 033 /** 034 * {@inheritDoc} 035 */ 036 @Override 037 public void configure(final InstanceOfAny constraintAnnotation) 038 { 039 super.configure(constraintAnnotation); 040 setTypes(constraintAnnotation.value()); 041 } 042 043 /** 044 * {@inheritDoc} 045 */ 046 @Override 047 protected Map<String, String> createMessageVariables() 048 { 049 final Map<String, String> messageVariables = getCollectionFactory().createMap(2); 050 if (types.length == 1) 051 messageVariables.put("types", types[0].getName()); 052 else 053 { 054 final String[] classNames = new String[types.length]; 055 for (int i = 0, l = classNames.length; i < l; i++) 056 classNames[i] = types[i].getName(); 057 messageVariables.put("types", StringUtils.implode(classNames, ",")); 058 } 059 return messageVariables; 060 } 061 062 /** 063 * @return the type 064 */ 065 public Class< ? >[] getTypes() 066 { 067 return types; 068 } 069 070 /** 071 * {@inheritDoc} 072 */ 073 public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context, 074 final Validator validator) 075 { 076 if (valueToValidate == null) return true; 077 078 for (final Class< ? > type : types) 079 if (type.isInstance(valueToValidate)) return true; 080 return false; 081 } 082 083 /** 084 * @param types the types to set 085 */ 086 public void setTypes(final Class< ? >... types) 087 { 088 this.types = types; 089 requireMessageVariablesRecreation(); 090 } 091 }