View Javadoc

1   /*
2    *  XNap Commons
3    *
4    *  Copyright (C) 2005  Steffen Pingel
5    *
6    *  This library is free software; you can redistribute it and/or
7    *  modify it under the terms of the GNU Lesser General Public
8    *  License as published by the Free Software Foundation; either
9    *  version 2.1 of the License, or (at your option) any later version.
10   *
11   *  This library is distributed in the hope that it will be useful,
12   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14   *  Lesser General Public License for more details.
15   *
16   *  You should have received a copy of the GNU Lesser General Public
17   *  License along with this library; if not, write to the Free Software
18   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19   */
20  package org.xnap.commons.settings;
21  
22  import org.xnap.commons.i18n.I18n;
23  import org.xnap.commons.i18n.I18nFactory;
24  
25  /***
26   * An integer validator. A range can be defined.
27   */
28  public class IntValidator implements Validator {
29  
30  	private static I18n i18n = I18nFactory.getI18n(IntValidator.class);
31  	
32      private int min;
33      private int max;
34  
35      public IntValidator(int min, int max)
36      {
37  		if (min > max) {
38  			throw new IllegalArgumentException("Min must not be greater than max (" + min + " > " + max + ")");
39  		}
40  
41  		this.min = min;
42  		this.max = max;
43      }
44  
45      public IntValidator(int min)
46      {
47  		this(min, Integer.MAX_VALUE);
48      }
49  
50      public IntValidator()
51      {
52  		this(Integer.MIN_VALUE, Integer.MAX_VALUE);
53      }
54  
55  	public int getMin()
56  	{
57  		return min;
58  	}
59  	
60  	public int getMax()
61  	{
62  		return max;
63  	}
64      
65      /***
66       * Validates <code>String</code>.
67       * @exception IllegalArgumentException if newValue is invalid.
68       */
69      public void validate(String value)
70      {
71  		if (value == null) {
72  			throw new IllegalArgumentException(i18n.tr("Value must not be null"));
73  		}
74  
75  		int i = Integer.parseInt(value);
76  		if (i < min || i > max) {
77  			throw(new IllegalArgumentException(i18n.tr("Value out of range.")));
78  		}
79      }
80  
81  }