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 MaxLengthCheck extends AbstractAnnotationCheck<MaxLength> 028 { 029 private static final long serialVersionUID = 1L; 030 031 private int max; 032 033 /** 034 * {@inheritDoc} 035 */ 036 @Override 037 public void configure(final MaxLength constraintAnnotation) 038 { 039 super.configure(constraintAnnotation); 040 setMax(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 messageVariables.put("max", Integer.toString(max)); 051 return messageVariables; 052 } 053 054 /** 055 * {@inheritDoc} 056 */ 057 @Override 058 protected ConstraintTarget[] getAppliesToDefault() 059 { 060 return new ConstraintTarget[]{ConstraintTarget.VALUES}; 061 } 062 063 /** 064 * @return the max 065 */ 066 public int getMax() 067 { 068 return max; 069 } 070 071 /** 072 * {@inheritDoc} 073 */ 074 public boolean isSatisfied(final Object validatedObject, final Object valueToValidate, final OValContext context, 075 final Validator validator) 076 { 077 if (valueToValidate == null) return true; 078 079 final int len = valueToValidate.toString().length(); 080 return len <= max; 081 } 082 083 /** 084 * @param max the max to set 085 */ 086 public void setMax(final int max) 087 { 088 this.max = max; 089 requireMessageVariablesRecreation(); 090 } 091 }