View Javadoc

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