001 package de.mospace.swing.text;
002
003 /* de.mospace.swing library
004 * Copyright (C) 2005 Moritz Ringler
005 * $Id: GeneralInputVerifier.java 12 2007-07-27 09:48:53Z ringler $
006 *
007 * This program is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU General Public License
009 * as published by the Free Software Foundation; either version 2
010 * of the License, or (at your option) any later version.
011 *
012 * This program is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
015 * GNU General Public License for more details.
016 *
017 * You should have received a copy of the GNU General Public License
018 * along with this program; if not, write to the Free Software
019 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
020 */
021
022 import java.lang.reflect.Constructor;
023 import java.lang.reflect.InvocationTargetException;
024 import java.lang.reflect.Method;
025 import java.lang.reflect.Modifier;
026 import javax.swing.InputVerifier;
027 import javax.swing.JComponent;
028 import javax.swing.text.JTextComponent;
029
030 /** An input verifier that checks if a text component's text can be interpreted
031 * as a value of a particular class and optionally if it falls into an allowed
032 * range of values of that class.<p>
033 * Here is some sample code
034 * <pre>
035 static GeneralInputVerifier giv;
036 static JTextComponent text = new javax.swing.JTextField();
037
038 private static void test(String s){
039 text.setText(s);
040 System.out.println(s + ", " + giv.verify(text) + ", " + giv.explain());
041 }
042
043 public static void main(String[] argv) throws Exception{
044 System.out.println("Double, > -1, < 10");
045 giv = new GeneralInputVerifier(Double.class, new Double(-1), new Double(10));
046 test("-2");
047 test("-1");
048 test("5");
049 test("10");
050 test("11");
051 test("x12");
052
053 System.out.println();
054 System.out.println("Date, yyyy-MM-dd, > 2007-02-15" );
055 java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
056 giv = new GeneralInputVerifier(java.util.Date.class,
057 java.text.DateFormat.class.getMethod("parse", new Class[]{String.class}),
058 format);
059 giv.setLowerLimit(format.parse("2007-02-15"));
060 test("2007-08-15");
061 test("200a-08-15");
062 test("2005-08-15");
063 }
064 </pre>
065 * The output is
066 * <pre>
067 Double, > -1, < 10
068 -2, false, null
069 -1, true, null
070 5, true, null
071 10, true, null
072 11, false, null
073 x12, false, java.lang.NumberFormatException: For input string: "x12"
074
075 Date, yyyy-MM-dd, > 2007-02-15
076 2007-08-15, true, null
077 200a-08-15, false, java.text.ParseException: Unparseable date: "200a-08-15"
078 2005-08-15, false, null
079 </pre>
080 *
081 * @version $Revision: 12 $ ($Date: 2007-07-27 11:48:53 +0200 (Fr, 27 Jul 2007) $)
082 * @author Moritz Ringler
083 */
084 public class GeneralInputVerifier extends InputVerifier implements java.io.Serializable{
085 private Class myClass;
086 private Method method;
087 private Object obj = null;
088 private Constructor constructor;
089 private Comparable min = null;
090 private Comparable max = null;
091 private transient Throwable ex = null;
092
093 /** Constructs a new GeneralInputVerifier for the given class and the given
094 * limits.
095 * @param c the class that input will be interpreted as
096 * @param min lower limit. null for none.
097 * @param max upper limit. null for none.
098 * @throws IllegalArgumentException if <code>c</code> does not have a
099 * public static <code>valueOf(String)</code> method or a
100 * public constructor with a single string argument.
101 * @throws ClassCastException if <code>min</code> and <code>max</code> are
102 * neither <code>null</code> nor instances of <code>c</code>.
103 */
104 public GeneralInputVerifier(Class c, Comparable min, Comparable max){
105 setInputClass(c);
106 setUpperLimit(max);
107 setLowerLimit(min);
108 }
109
110 /** Constructs a new GeneralInputVerifier for the full range of values
111 * in the specified class.
112 * @param c the class that input will be interpreted as
113 * @throws IllegalArgumentException if <code>c</code> does not have a
114 * public static
115 * <code>valueOf(String)</code> method or a public constructor with
116 * a single String argument
117 */
118 public GeneralInputVerifier(Class c){
119 setInputClass(c);
120 }
121
122 /** Creates a new GeneralInputVerifier for the specified class
123 * that uses the specified static method to construct a value from a string.
124 * @param c the class that input will be interpreted as
125 * @param m a public static method that accepts a single
126 * string argument and whose return type can be assigned to <code>c</code>
127 * @throws IllegalArgumentException if <code>method</code>
128 * is not a public static method that accepts a single
129 * string argument and has a return type of <code>c</code>
130 */
131 public GeneralInputVerifier(Class c, Method m){
132 setInputClass(c, m);
133 }
134
135 /** Creates a new GeneralInputVerifier for the specified class
136 * that uses the specified method and object
137 * to construct a value from a string. This will
138 * automatically reset the allowed range to the full range of values
139 * in this class.
140 * @param c the class that input will be interpreted as
141 * @param m a method that accepts a single
142 * string argument and whose return type can be assigned to <code>c</code>
143 * @param o the object to invoke the method on, or <code>null</code>
144 * if <code>m</code> is static
145 * @throws IllegalArgumentException if <code>method</code>
146 * is not a public method of <code>o</code> that accepts a single
147 * string argument and has a return type of <code>c</code>
148 */
149 public GeneralInputVerifier(Class c, Method m, Object o){
150 setInputClass(c, m, o);
151 }
152
153 /** Returns the class against which input will be checked.
154 * @see #setInputClass
155 */
156 public Class getInputClass(){
157 return myClass;
158 }
159
160 /** Sets the class against which input will be checked. This will
161 * automatically reset the allowed range to the full range of values
162 * in this class.
163 * @param c the class that input will be interpreted as
164 * @throws IllegalArgumentException if <code>c</code> does not have a public
165 * static
166 * <code>valueOf(String)</code> method that returns a value of <code>c</code>
167 * or a public constructor with a single string argument.
168 */
169 public void setInputClass(Class c){
170 method = null;
171 constructor = null;
172 final Class[] singleString = new Class[]{String.class};
173 try{
174 setInputClass(c, c.getMethod("valueOf", singleString));
175 } catch (Exception exm){
176 try {
177 constructor = c.getConstructor(singleString);
178 if(!Modifier.isPublic(constructor.getModifiers())){
179 throw new IllegalArgumentException(
180 "Constructor is not public.");
181 }
182 myClass = c;
183 min = max = null;
184 } catch (NoSuchMethodException exc){
185 throw new IllegalArgumentException("Caused by " + exc.toString());
186 }
187 }
188 }
189
190 /** Sets the class against which input will be checked and the
191 * static method used to construct values of this class from a string.
192 * This will reset the allowed range to the full range of values
193 * in this class.
194 * @param c the class that input will be interpreted as
195 * @param m a static method that accepts a single
196 * string argument and whose return type can be assigned to <code>c</code>
197 * @throws IllegalArgumentException if <code>method</code>
198 * is not a public static method that accepts a single
199 * string argument and has a return type of <code>c</code>
200 */
201 public void setInputClass(Class c, Method m){
202 setInputClass(c, m, null);
203 }
204
205 /** Sets the class against which input will be checked and the
206 * method and object used
207 * to construct values of this class from a string. This will
208 * automatically reset the allowed range to the full range of values
209 * in this class.
210 * @param c the class that input will be interpreted as
211 * @param m a method that accepts a single
212 * string argument and whose return type can be assigned to <code>c</code>
213 * @param o the object to invoke the method on, or <code>null</code>
214 * if <code>m</code> is static
215 * @throws IllegalArgumentException if <code>method</code>
216 * is not a public method of <code>o</code> that accepts a single
217 * string argument and has a return type of <code>c</code>
218 */
219 public void setInputClass(Class c, Method m, Object o){
220 /* check return type */
221 if(!c.isAssignableFrom(m.getReturnType())){
222 throw new IllegalArgumentException(
223 c + " is not assignable from the return type of " + m);
224 }
225
226 /* check parameter types */
227 Class[] params = m.getParameterTypes();
228 if(params.length != 1 || !params[0].equals(String.class)){
229 throw new IllegalArgumentException(
230 m + " does not have the correct parameter types.");
231 }
232
233 /* check modifiers */
234 final int modifiers = m.getModifiers();
235
236 /* check public access */
237 if(!Modifier.isPublic(modifiers)){
238 throw new IllegalArgumentException(
239 m + " is not public.");
240 }
241
242 if(o == null){
243 /* check whether m is static */
244 if(!Modifier.isStatic(modifiers)){
245 throw new IllegalArgumentException(
246 m + " is not static.");
247 }
248
249 } else {
250 /* check whether m can be invoked on o */
251 if(!m.getDeclaringClass().isInstance(o)){
252 throw new IllegalArgumentException(
253 m + " cannot be invoked on " + o);
254 }
255 }
256 myClass = c;
257 method = m;
258 obj = o;
259 }
260
261 /** Sets the largest allowed value.
262 * @param max upper limit. null for none.
263 * @throws ClassCastException if <code>max</code> is neither <code>null</code>
264 * nor an instance of <code>getInputClass</code>.
265 */
266 public void setUpperLimit(Comparable max){
267 if(max == null){
268 this.max = null;
269 } else {
270 if(!(myClass.isInstance(max))){
271 throw new ClassCastException("max (" + max + ") is not an " +
272 "instance of " + myClass);
273 }
274 this.max = max;
275 }
276 }
277
278 /** Returns the largest allowed value.
279 * @return upper limit. null for none.
280 */
281 public Comparable getUpperLimit(){
282 return max;
283 }
284
285 /** Sets the smallest allowed value.
286 * @param min lower limit. null for none.
287 * @throws ClassCastException if <code>min</code> is neither <code>null</code>
288 * nor an instance of <code>getInputClass</code>.
289 */
290 public void setLowerLimit(Comparable min){
291 if(min == null){
292 this.min = null;
293 } else {
294 if(!(myClass.isInstance(min))){
295 throw new ClassCastException("min (" + min + ") is not an " +
296 "instance of " + myClass);
297 }
298 this.min = min;
299 }
300 }
301
302 /** Explains why the last call to {@link #verify(String) verify}
303 * returned false. This method will return
304 * any exception thrown within the {@link #verify(String) verify} methods.
305 * @return a throwable or <code>null</code>
306 */
307 public Throwable explain(){
308 return ex;
309 }
310
311 /** Returns the smallest allowed value.
312 * @return lower limit. null for none.
313 */
314 public Comparable getLowerLimit(){
315 return min;
316 }
317
318 /**
319 * Verifies the current text of a {@link javax.swing.text.JTextComponent}.
320 * @param c a swing text component
321 * @return whether the current text of <code>c</code> is legal input
322 * @throws ClassCastException if <code>c</code> is not a
323 * JTextComponent
324 */
325 public boolean verify(JComponent c){
326 return verify( ((JTextComponent) c).getText() );
327 }
328
329 /**
330 * Verifies the specified text.
331 * @param text the input to verify
332 * @return whether <code>text</code> is legal input.
333 */
334 public boolean verify(String text){
335 boolean result = false;
336 ex = null;
337 final Object[] in = new Object[]{text};
338 try{
339 Object value = (method == null)
340 ? constructor.newInstance(in)
341 : method.invoke(obj, in);
342 result =
343 ( min == null || min.compareTo(value) <= 0 ) &&
344 ( max == null || max.compareTo(value) >= 0 );
345 } catch(InvocationTargetException failed){
346 ex = failed.getCause();
347 } catch (Exception failed){
348 ex = failed;
349 }
350 return result;
351 }
352 }