View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    * 
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.portals.bridges.frameworks.spring.validation;
18  
19  import java.lang.reflect.InvocationTargetException;
20  import java.text.MessageFormat;
21  import java.util.Collection;
22  import java.util.Iterator;
23  import java.util.Locale;
24  import java.util.Map;
25  import java.util.ResourceBundle;
26  
27  import org.apache.commons.beanutils.DynaBean;
28  import org.apache.commons.beanutils.PropertyUtils;
29  import org.apache.commons.validator.Arg;
30  import org.apache.commons.validator.Field;
31  import org.apache.commons.validator.Form;
32  import org.apache.commons.validator.GenericTypeValidator;
33  import org.apache.commons.validator.GenericValidator;
34  import org.apache.commons.validator.ValidatorAction;
35  import org.apache.commons.validator.ValidatorResources;
36  import org.apache.commons.validator.ValidatorResult;
37  import org.apache.commons.validator.ValidatorResults;
38  
39  /***
40   * ValidationSupport
41   * 
42   * @author <a href="mailto:taylor@apache.org">David Sean Taylor </a>
43   * @version $Id: ValidationSupport.java 517068 2007-03-12 01:44:37Z ate $
44   */
45  public class ValidationSupport
46  {
47  
48      public static String getValueAsString(Object bean, String property)
49      {
50          Object value = null;
51  
52          if (bean instanceof Map)
53          {
54              value = ((Map) bean).get(property);
55          }
56          else if (bean instanceof DynaBean)
57          {
58              value = ((DynaBean) bean).get(property);
59          }
60          else
61          {
62              try
63              {
64                  value = PropertyUtils.getProperty(bean, property);
65  
66              }
67              catch (IllegalAccessException e)
68              {
69                  //log.error(e.getMessage(), e);
70              }
71              catch (InvocationTargetException e)
72              {
73                  //log.error(e.getMessage(), e);
74              }
75              catch (NoSuchMethodException e)
76              {
77                  //log.error(e.getMessage(), e);
78              }
79          }
80  
81          if (value == null) { return null; }
82  
83          if (value instanceof String[])
84          {
85              return ((String[]) value).length > 0 ? value.toString() : "";
86  
87          }
88          else if (value instanceof Collection)
89          {
90              return ((Collection) value).isEmpty() ? "" : value.toString();
91  
92          }
93          else
94          {
95              return value.toString();
96          }
97      }
98  
99      /***
100      * Checks if the field is required.
101      * 
102      * @return boolean If the field isn't <code>null</code> and has a length
103      *         greater than zero, <code>true</code> is returned. Otherwise
104      *         <code>false</code>.
105      */
106     public static boolean validateRequired(Object bean, ValidatorAction va, Field field, Map errors,
107             ResourceBundle bundle)
108     {
109         String value = getValueAsString(bean, field.getProperty());
110         boolean valid = !GenericValidator.isBlankOrNull(value);
111         if (!valid)
112         {
113             if (bundle == null)
114             {
115                 errors.put(field.getKey(), "Field " + field.getKey() + " is a required field.");
116             }
117             else
118             {
119                 String displayName = bundle.getString(field.getArg(0).getKey());
120                 if (displayName == null)
121                 {
122                     displayName = field.getKey();
123                 }
124                 Object[] args =
125                 { displayName};
126 
127                 String message = bundle.getString(va.getMsg());
128                 if (message == null)
129                 {
130                     message = "Field {0} is a required field.";
131                 }
132                 errors.put(field.getKey(), MessageFormat.format(message, args));
133             }
134         }
135         return valid;
136     }
137 
138     public static boolean validateRange(Object bean, ValidatorAction va, Field field, Map errors, ResourceBundle bundle) 
139     {        
140         int value = 0;
141         String result = getValueAsString(bean, field.getProperty());
142         if (result != null)
143         {
144             Integer intValue = GenericTypeValidator.formatInt(result);
145             if (intValue != null)
146             {    
147                 value = intValue.intValue();
148             }
149         }
150         
151        String minResult = field.getVarValue("min");
152        if (minResult == null)
153        {
154            minResult = "0";
155        }
156        String maxResult = field.getVarValue("max");
157        if (maxResult == null)
158        {
159            maxResult = "0";
160        }
161        int min = GenericTypeValidator.formatInt(minResult).intValue();
162        int max = GenericTypeValidator.formatInt(maxResult).intValue();
163        
164        boolean valid = GenericValidator.isInRange(value, min, max);
165        if (!valid)
166        {
167            if (bundle == null)
168            {
169                errors.put(field.getKey(), "Field " + field.getKey() + " is out of range: [" + min + "- " + max + "]");
170            }
171            else
172            {
173                String displayName = bundle.getString(field.getArg(0).getKey());
174                if (displayName == null)
175                {
176                    displayName = field.getKey();
177                }
178                Object[] args =
179                { displayName, minResult, maxResult};
180 
181                String message = bundle.getString(va.getMsg());
182                if (message == null)
183                {
184                    message = "Field {0} is out of range: [{1} - {2}]";
185                }
186                errors.put(field.getKey(), MessageFormat.format(message, args));
187            }
188        }
189        return valid;
190     }   
191 
192     public static boolean validateDoubleRange(Object bean, ValidatorAction va, Field field, Map errors, ResourceBundle bundle)
193     {
194         double value = 0;
195         String result = getValueAsString(bean, field.getProperty());
196         if (result != null)
197         {
198             Double doubleValue = GenericTypeValidator.formatDouble(result);
199             if (doubleValue != null)
200             {    
201                 value = doubleValue.doubleValue();
202             }
203         }
204         String minResult = field.getVarValue("min");
205         if (minResult == null)
206         {
207             minResult = "0";
208         }
209         String maxResult = field.getVarValue("max");
210         if (maxResult == null)
211         {
212             maxResult = "0";
213         }
214 
215         double min = GenericTypeValidator.formatDouble(minResult).doubleValue();
216         double max = GenericTypeValidator.formatDouble(maxResult).doubleValue();
217         boolean valid = GenericValidator.isInRange(value, min, max);
218         if (!valid)
219         {
220             if (bundle == null)
221             {
222                 errors.put(field.getKey(), "Field " + field.getKey() + " is out of range: [" + min + "- " + max + "]");
223             }
224             else
225             {
226                 String displayName = bundle.getString(field.getArg(0).getKey());
227                 if (displayName == null)
228                 {
229                     displayName = field.getKey();
230                 }
231                 Object[] args =
232                 { displayName, minResult, maxResult};
233 
234                 String message = bundle.getString(va.getMsg());
235                 if (message == null)
236                 {
237                     message = "Field {0} is out of range: [{1} - {2}]";
238                 }
239                 errors.put(field.getKey(), MessageFormat.format(message, args));
240             }
241         }
242         return valid;
243     }
244 
245     public static boolean validateMask(Object bean, ValidatorAction va, Field field, Map errors, ResourceBundle bundle)
246     {
247         String value = getValueAsString(bean, field.getProperty());
248         
249         String mask = field.getVarValue("mask");
250         if (mask == null)
251         {
252             return true; // no mask provide, let it pass
253         }
254 
255         if (GenericValidator.isBlankOrNull(value))
256         {
257             return true; // this is how struts handles it
258         }
259         
260         boolean valid = GenericValidator.matchRegexp(value, mask);
261         if (!valid)
262         {
263             if (bundle == null)
264             {
265                 errors.put(field.getKey(), "Field " + field.getKey() + " failed to match validation pattern: " +  mask);
266             }
267             else
268             {
269                 String displayName = bundle.getString(field.getArg(0).getKey());
270                 if (displayName == null)
271                 {
272                     displayName = field.getKey();
273                 }
274                 Object[] args =
275                 { displayName, mask};
276 
277                 String message = bundle.getString(va.getMsg());
278                 if (message == null)
279                 {
280                     message = "Field {0} failed to match validation pattern: {2}";
281                 }
282                 errors.put(field.getKey(), MessageFormat.format(message, args));
283             }
284         }        
285         return valid;
286     }
287 
288     public static boolean validateMaxLength(Object bean, ValidatorAction va, Field field, Map errors, ResourceBundle bundle)
289     {
290         String value = getValueAsString(bean, field.getProperty());
291         
292         int max = Integer.parseInt(field.getVarValue("maxlength"));
293 
294         if (GenericValidator.isBlankOrNull(value))
295         {
296             return true; 
297         }
298         
299         boolean valid = GenericValidator.maxLength(value, max);        
300         if (!valid)
301         {
302             if (bundle == null)
303             {
304                 errors.put(field.getKey(), "Field " + field.getKey() + " surpasses maximum length: " +  max);
305             }
306             else
307             {
308                 String displayName = bundle.getString(field.getArg(0).getKey());
309                 if (displayName == null)
310                 {
311                     displayName = field.getKey();
312                 }
313                 Object[] args =
314                 { displayName, new Integer(max)};
315 
316                 String message = bundle.getString(va.getMsg());
317                 if (message == null)
318                 {
319                     message = "Field {0} surpasses maximum length {1}";                    
320                 }
321                 errors.put(field.getKey(), MessageFormat.format(message, args));
322             }
323         }        
324         return valid;
325     }
326     
327     public static void printResults(Object bean, ValidatorResults results, ValidatorResources resources, String formName)
328     {
329 
330         boolean success = true;
331 
332         // Start by getting the form for the current locale and Bean.
333         Form form = resources.getForm(Locale.getDefault(), formName);
334 
335         System.out.println("\n\nValidating:");
336         System.out.println(bean);
337 
338         // Iterate over each of the properties of the Bean which had messages.
339         Iterator propertyNames = results.getPropertyNames().iterator();
340         while (propertyNames.hasNext())
341         {
342             String propertyName = (String) propertyNames.next();
343 
344             // Get the Field associated with that property in the Form
345             Field field = form.getField(propertyName);
346 
347             // Look up the formatted name of the field from the Field arg0
348             String prettyFieldName = propertyName; //apps.getString(field.getArg(0).getKey());
349 
350             // Get the result of validating the property.
351             ValidatorResult result = results.getValidatorResult(propertyName);
352 
353             // Get all the actions run against the property, and iterate over
354             // their names.
355             Map actionMap = result.getActionMap();
356             Iterator keys = actionMap.keySet().iterator();
357             while (keys.hasNext())
358             {
359                 String actName = (String) keys.next();
360 
361                 // Get the Action for that name.
362                 ValidatorAction action = resources.getValidatorAction(actName);
363 
364                 // If the result is valid, print PASSED, otherwise print FAILED
365                 System.out.println(propertyName + "[" + actName + "] ("
366                         + (result.isValid(actName) ? "PASSED" : "FAILED") + ")");
367 
368                 //If the result failed, format the Action's message against the
369                 // formatted field name
370                 if (!result.isValid(actName))
371                 {
372                     success = false;
373                     String message = "invalid field"; // apps.getString(action.getMsg());
374                     if (actName.equals("doubleRange"))
375                     {
376                         Arg f1 = field.getArg(1);
377                         Arg f2 = field.getArg(2);
378                         Arg f0 = field.getArg(0);
379                         Object[] args =
380                         { prettyFieldName, field.getVar("min").getValue(), field.getVar("max").getValue()};
381                         System.out.println("     Error message will be: " + MessageFormat.format(message, args));
382                     }
383                     else
384                     {
385                         Object[] args =
386                         { prettyFieldName};
387                         System.out.println("     Error message will be: " + MessageFormat.format(message, args));
388                     }
389 
390                 }
391             }
392         }
393         if (success)
394         {
395             System.out.println("FORM VALIDATION PASSED");
396         }
397         else
398         {
399             System.out.println("FORM VALIDATION FAILED");
400         }
401 
402     }
403 
404 }