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.ConstraintTarget; 020 import net.sf.oval.Validator; 021 import net.sf.oval.configuration.annotation.AbstractAnnotationCheck; 022 import net.sf.oval.context.OValContext; 023 024 /** 025 * @author Sebastian Thomschke 026 */ 027 public class LengthCheck extends AbstractAnnotationCheck<Length> 028 { 029 private static final long serialVersionUID = 1L; 030 031 private int min; 032 private int max; 033 034 /** 035 * {@inheritDoc} 036 */ 037 @Override 038 public void configure(final Length constraintAnnotation) 039 { 040 super.configure(constraintAnnotation); 041 setMax(constraintAnnotation.max()); 042 setMin(constraintAnnotation.min()); 043 } 044 045 /** 046 * {@inheritDoc} 047 */ 048 @Override 049 protected Map<String, String> createMessageVariables() 050 { 051 final Map<String, String> messageVariables = getCollectionFactory().createMap(2); 052 messageVariables.put("max", Integer.toString(max)); 053 messageVariables.put("min", Integer.toString(min)); 054 return messageVariables; 055 } 056 057 /** 058 * {@inheritDoc} 059 */ 060 @Override 061 protected ConstraintTarget[] getAppliesToDefault() 062 { 063 return new ConstraintTarget[]{ConstraintTarget.VALUES}; 064 } 065 066 /** 067 * @return the max 068 */ 069 public int getMax() 070 { 071 return max; 072 } 073 074 /** 075 * @return the min 076 */ 077 public int getMin() 078 { 079 return min; 080 } 081 082 /** 083 * {@inheritDoc} 084 */ 085 public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context, 086 final Validator validator) 087 { 088 if (valueToValidate == null) return true; 089 090 final int len = valueToValidate.toString().length(); 091 return len >= min && len <= max; 092 } 093 094 /** 095 * @param max the max to set 096 */ 097 public void setMax(final int max) 098 { 099 this.max = max; 100 requireMessageVariablesRecreation(); 101 } 102 103 /** 104 * @param min the min to set 105 */ 106 public void setMin(final int min) 107 { 108 this.min = min; 109 requireMessageVariablesRecreation(); 110 } 111 }