View Javadoc

1   /*
2    * $Id: DynaActionForm.java 421119 2006-07-12 04:49:11Z wsmoak $
3    *
4    * Copyright 2000-2004 The Apache Software Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.struts.action;
19  
20  import org.apache.commons.beanutils.ConversionException;
21  import org.apache.commons.beanutils.DynaBean;
22  import org.apache.commons.beanutils.DynaClass;
23  import org.apache.commons.beanutils.DynaProperty;
24  import org.apache.struts.config.FormBeanConfig;
25  import org.apache.struts.config.FormPropertyConfig;
26  
27  import javax.servlet.ServletRequest;
28  import javax.servlet.http.HttpServletRequest;
29  
30  import java.lang.reflect.Array;
31  
32  import java.util.HashMap;
33  import java.util.Iterator;
34  import java.util.List;
35  import java.util.Map;
36  import java.util.StringTokenizer;
37  
38  /***
39   * <p>Specialized subclass of <code>ActionForm</code> that allows the creation
40   * of form beans with dynamic sets of properties, without requiring the
41   * developer to create a Java class for each type of form bean.</p>
42   *
43   * <p><strong>USAGE NOTE</strong> - Since Struts 1.1, the <code>reset</code>
44   * method no longer initializes property values to those specified in
45   * <code>&lt;form-property&gt;</code> elements in the Struts module
46   * configuration file.  If you wish to utilize that behavior, the simplest
47   * solution is to subclass <code>DynaActionForm</code> and call the
48   * <code>initialize</code> method inside it.</p>
49   *
50   * @version $Rev: 421119 $ $Date: 2005-11-12 11:52:08 -0500 (Sat, 12 Nov 2005)
51   *          $
52   * @since Struts 1.1
53   */
54  public class DynaActionForm extends ActionForm implements DynaBean {
55      // ----------------------------------------------------- Instance Variables
56  
57      /***
58       * <p>The <code>DynaActionFormClass</code> with which we are associated.
59       * </p>
60       */
61      protected DynaActionFormClass dynaClass = null;
62  
63      /***
64       * <p>The set of property values for this <code>DynaActionForm</code>,
65       * keyed by property name.</p>
66       */
67      protected HashMap dynaValues = new HashMap();
68  
69      // ----------------------------------------------------- ActionForm Methods
70  
71      /***
72       * <p>Initialize all bean properties to their initial values, as specified
73       * in the {@link FormPropertyConfig} elements associated with the
74       * definition of this <code>DynaActionForm</code>.</p>
75       *
76       * @param mapping The mapping used to select this instance
77       */
78      public void initialize(ActionMapping mapping) {
79          String name = mapping.getName();
80  
81          if (name == null) {
82              return;
83          }
84  
85          FormBeanConfig config =
86              mapping.getModuleConfig().findFormBeanConfig(name);
87  
88          if (config == null) {
89              return;
90          }
91  
92          initialize(config);
93      }
94  
95      /***
96       * <p>Initialize the specified form bean.</p>
97       *
98       * @param config The configuration for the form bean to initialize.
99       */
100     public void initialize(FormBeanConfig config) {
101         FormPropertyConfig[] props = config.findFormPropertyConfigs();
102 
103         for (int i = 0; i < props.length; i++) {
104             set(props[i].getName(), props[i].initial());
105         }
106     }
107 
108     // :FIXME: Is there any point in retaining these reset methods
109     // since they now simply replicate the superclass behavior?
110 
111     /***
112      * <p>Reset bean properties to their default state, as needed. This method
113      * is called before the properties are repopulated by the controller.</p>
114      *
115      * <p>The default implementation attempts to forward to the HTTP version
116      * of this method.</p>
117      *
118      * @param mapping The mapping used to select this instance
119      * @param request The servlet request we are processing
120      */
121     public void reset(ActionMapping mapping, ServletRequest request) {
122         super.reset(mapping, request);
123     }
124 
125     /***
126      * <p>Reset the properties to their <code>initial</code> value if their
127      * <code>reset</code> configuration is set to true or if
128      * <code>reset</code> is set to a list of HTTP request methods that
129      * includes the method of given <code>request</code> object.</p>
130      *
131      * @param mapping The mapping used to select this instance
132      * @param request The servlet request we are processing
133      */
134     public void reset(ActionMapping mapping, HttpServletRequest request) {
135         String name = getDynaClass().getName();
136 
137         if (name == null) {
138             return;
139         }
140 
141         FormBeanConfig config =
142             mapping.getModuleConfig().findFormBeanConfig(name);
143 
144         if (config == null) {
145             return;
146         }
147 
148         // look for properties we should reset
149         FormPropertyConfig[] props = config.findFormPropertyConfigs();
150 
151         for (int i = 0; i < props.length; i++) {
152             String resetValue = props[i].getReset();
153 
154             // skip this property if there's no reset value
155             if ((resetValue == null) || (resetValue.length() <= 0)) {
156                 continue;
157             }
158 
159             boolean reset = Boolean.valueOf(resetValue).booleanValue();
160 
161             if (!reset) {
162                 // check for the request method
163                 // use a StringTokenizer with the default delimiters + a comma
164                 StringTokenizer st =
165                     new StringTokenizer(resetValue, ", \t\n\r\f");
166 
167                 while (st.hasMoreTokens()) {
168                     String token = st.nextToken();
169 
170                     if (token.equalsIgnoreCase(request.getMethod())) {
171                         reset = true;
172 
173                         break;
174                     }
175                 }
176             }
177 
178             if (reset) {
179                 set(props[i].getName(), props[i].initial());
180             }
181         }
182     }
183 
184     // ------------------------------------------------------- DynaBean Methods
185 
186     /***
187      * <p>Indicates if the specified mapped property contain a value for the
188      * specified key value.</p>
189      *
190      * @param name Name of the property to check
191      * @param key  Name of the key to check
192      * @return <code>true</code> if the specified mapped property contains a
193      *         value for the specified key value; <code>true</code>
194      *         otherwise.
195      * @throws NullPointerException     if there is no property of the
196      *                                  specified name
197      * @throws IllegalArgumentException if there is no mapped property of the
198      *                                  specified name
199      */
200     public boolean contains(String name, String key) {
201         Object value = dynaValues.get(name);
202 
203         if (value == null) {
204             throw new NullPointerException("No mapped value for '" + name + "("
205                 + key + ")'");
206         } else if (value instanceof Map) {
207             return (((Map) value).containsKey(key));
208         } else {
209             throw new IllegalArgumentException("Non-mapped property for '"
210                 + name + "(" + key + ")'");
211         }
212     }
213 
214     /***
215      * <p>Return the value of a simple property with the specified name.</p>
216      *
217      * @param name Name of the property whose value is to be retrieved
218      * @return The value of a simple property with the specified name.
219      * @throws IllegalArgumentException if there is no property of the
220      *                                  specified name
221      * @throws NullPointerException     if the type specified for the property
222      *                                  is invalid
223      */
224     public Object get(String name) {
225         // Return any non-null value for the specified property
226         Object value = dynaValues.get(name);
227 
228         if (value != null) {
229             return (value);
230         }
231 
232         // Return a null value for a non-primitive property
233         Class type = getDynaProperty(name).getType();
234 
235         if (type == null) {
236             throw new NullPointerException("The type for property " + name
237                 + " is invalid");
238         }
239 
240         if (!type.isPrimitive()) {
241             return (value);
242         }
243 
244         // Manufacture default values for primitive properties
245         if (type == Boolean.TYPE) {
246             return (Boolean.FALSE);
247         } else if (type == Byte.TYPE) {
248             return (new Byte((byte) 0));
249         } else if (type == Character.TYPE) {
250             return (new Character((char) 0));
251         } else if (type == Double.TYPE) {
252             return (new Double(0.0));
253         } else if (type == Float.TYPE) {
254             return (new Float((float) 0.0));
255         } else if (type == Integer.TYPE) {
256             return (new Integer(0));
257         } else if (type == Long.TYPE) {
258             return (new Long(0));
259         } else if (type == Short.TYPE) {
260             return (new Short((short) 0));
261         } else {
262             return (null);
263         }
264     }
265 
266     /***
267      * <p>Return the value of an indexed property with the specified name.
268      * </p>
269      *
270      * @param name  Name of the property whose value is to be retrieved
271      * @param index Index of the value to be retrieved
272      * @return The value of an indexed property with the specified name.
273      * @throws IllegalArgumentException if there is no property of the
274      *                                  specified name
275      * @throws IllegalArgumentException if the specified property exists, but
276      *                                  is not indexed
277      * @throws NullPointerException     if no array or List has been
278      *                                  initialized for this property
279      */
280     public Object get(String name, int index) {
281         Object value = dynaValues.get(name);
282 
283         if (value == null) {
284             throw new NullPointerException("No indexed value for '" + name
285                 + "[" + index + "]'");
286         } else if (value.getClass().isArray()) {
287             return (Array.get(value, index));
288         } else if (value instanceof List) {
289             return ((List) value).get(index);
290         } else {
291             throw new IllegalArgumentException("Non-indexed property for '"
292                 + name + "[" + index + "]'");
293         }
294     }
295 
296     /***
297      * <p>Return the value of a mapped property with the specified name, or
298      * <code>null</code> if there is no value for the specified key. </p>
299      *
300      * @param name Name of the property whose value is to be retrieved
301      * @param key  Key of the value to be retrieved
302      * @return The value of a mapped property with the specified name, or
303      *         <code>null</code> if there is no value for the specified key.
304      * @throws NullPointerException     if there is no property of the
305      *                                  specified name
306      * @throws IllegalArgumentException if the specified property exists, but
307      *                                  is not mapped
308      */
309     public Object get(String name, String key) {
310         Object value = dynaValues.get(name);
311 
312         if (value == null) {
313             throw new NullPointerException("No mapped value for '" + name + "("
314                 + key + ")'");
315         } else if (value instanceof Map) {
316             return (((Map) value).get(key));
317         } else {
318             throw new IllegalArgumentException("Non-mapped property for '"
319                 + name + "(" + key + ")'");
320         }
321     }
322 
323     /***
324      * <p>Return the value of a <code>String</code> property with the
325      * specified name. This is equivalent to calling <code>(String)
326      * dynaForm.get(name)</code>.</p>
327      *
328      * @param name Name of the property whose value is to be retrieved.
329      * @return The value of a <code>String</code> property with the specified
330      *         name.
331      * @throws IllegalArgumentException if there is no property of the
332      *                                  specified name
333      * @throws NullPointerException     if the type specified for the property
334      *                                  is invalid
335      * @throws ClassCastException       if the property is not a String.
336      * @since Struts 1.2
337      */
338     public String getString(String name) {
339         return (String) this.get(name);
340     }
341 
342     /***
343      * <p>Return the value of a <code>String[]</code> property with the
344      * specified name. This is equivalent to calling <code>(String[])
345      * dynaForm.get(name)</code>.</p>
346      *
347      * @param name Name of the property whose value is to be retrieved.
348      * @return The value of a <code>String[]</code> property with the
349      *         specified name.
350      * @throws IllegalArgumentException if there is no property of the
351      *                                  specified name
352      * @throws NullPointerException     if the type specified for the property
353      *                                  is invalid
354      * @throws ClassCastException       if the property is not a String[].
355      * @since Struts 1.2
356      */
357     public String[] getStrings(String name) {
358         return (String[]) this.get(name);
359     }
360 
361     /***
362      * <p>Return the <code>DynaClass</code> instance that describes the set of
363      * properties available for this <code>DynaBean</code>.</p>
364      *
365      * @return The <code>DynaClass</code> instance that describes the set of
366      *         properties available for this <code>DynaBean</code>.
367      */
368     public DynaClass getDynaClass() {
369         return (this.dynaClass);
370     }
371 
372     /***
373      * <p>Returns the <code>Map</code> containing the property values. This is
374      * done mostly to facilitate accessing the <code>DynaActionForm</code>
375      * through JavaBeans accessors, in order to use the JavaServer Pages
376      * Standard Tag Library (JSTL).</p>
377      *
378      * <p>For instance, the normal JSTL EL syntax for accessing an
379      * <code>ActionForm</code> would be something like this:
380      * <pre>
381      *  ${formbean.prop}</pre>
382      * The JSTL EL syntax for accessing a <code>DynaActionForm</code> looks
383      * something like this (because of the presence of this
384      * <code>getMap()</code> method):
385      * <pre>
386      *  ${dynabean.map.prop}</pre>
387      * </p>
388      *
389      * @return The <code>Map</code> containing the property values.
390      */
391     public Map getMap() {
392         return (dynaValues);
393     }
394 
395     /***
396      * <p>Remove any existing value for the specified key on the specified
397      * mapped property.</p>
398      *
399      * @param name Name of the property for which a value is to be removed
400      * @param key  Key of the value to be removed
401      * @throws NullPointerException     if there is no property of the
402      *                                  specified name
403      * @throws IllegalArgumentException if there is no mapped property of the
404      *                                  specified name
405      */
406     public void remove(String name, String key) {
407         Object value = dynaValues.get(name);
408 
409         if (value == null) {
410             throw new NullPointerException("No mapped value for '" + name + "("
411                 + key + ")'");
412         } else if (value instanceof Map) {
413             ((Map) value).remove(key);
414         } else {
415             throw new IllegalArgumentException("Non-mapped property for '"
416                 + name + "(" + key + ")'");
417         }
418     }
419 
420     /***
421      * <p>Set the value of a simple property with the specified name.</p>
422      *
423      * @param name  Name of the property whose value is to be set
424      * @param value Value to which this property is to be set
425      * @throws ConversionException      if the specified value cannot be
426      *                                  converted to the type required for
427      *                                  this property
428      * @throws IllegalArgumentException if there is no property of the
429      *                                  specified name
430      * @throws NullPointerException     if the type specified for the property
431      *                                  is invalid
432      * @throws NullPointerException     if an attempt is made to set a
433      *                                  primitive property to null
434      */
435     public void set(String name, Object value) {
436         DynaProperty descriptor = getDynaProperty(name);
437 
438         if (descriptor.getType() == null) {
439             throw new NullPointerException("The type for property " + name
440                 + " is invalid");
441         }
442 
443         if (value == null) {
444             if (descriptor.getType().isPrimitive()) {
445                 throw new NullPointerException("Primitive value for '" + name
446                     + "'");
447             }
448         } else if (!isDynaAssignable(descriptor.getType(), value.getClass())) {
449             throw new ConversionException("Cannot assign value of type '"
450                 + value.getClass().getName() + "' to property '" + name
451                 + "' of type '" + descriptor.getType().getName() + "'");
452         }
453 
454         dynaValues.put(name, value);
455     }
456 
457     /***
458      * <p>Set the value of an indexed property with the specified name.</p>
459      *
460      * @param name  Name of the property whose value is to be set
461      * @param index Index of the property to be set
462      * @param value Value to which this property is to be set
463      * @throws ConversionException       if the specified value cannot be
464      *                                   converted to the type required for
465      *                                   this property
466      * @throws NullPointerException      if there is no property of the
467      *                                   specified name
468      * @throws IllegalArgumentException  if the specified property exists, but
469      *                                   is not indexed
470      * @throws IndexOutOfBoundsException if the specified index is outside the
471      *                                   range of the underlying property
472      */
473     public void set(String name, int index, Object value) {
474         Object prop = dynaValues.get(name);
475 
476         if (prop == null) {
477             throw new NullPointerException("No indexed value for '" + name
478                 + "[" + index + "]'");
479         } else if (prop.getClass().isArray()) {
480             Array.set(prop, index, value);
481         } else if (prop instanceof List) {
482             try {
483                 ((List) prop).set(index, value);
484             } catch (ClassCastException e) {
485                 throw new ConversionException(e.getMessage());
486             }
487         } else {
488             throw new IllegalArgumentException("Non-indexed property for '"
489                 + name + "[" + index + "]'");
490         }
491     }
492 
493     /***
494      * <p>Set the value of a mapped property with the specified name.</p>
495      *
496      * @param name  Name of the property whose value is to be set
497      * @param key   Key of the property to be set
498      * @param value Value to which this property is to be set
499      * @throws NullPointerException     if there is no property of the
500      *                                  specified name
501      * @throws IllegalArgumentException if the specified property exists, but
502      *                                  is not mapped
503      */
504     public void set(String name, String key, Object value) {
505         Object prop = dynaValues.get(name);
506 
507         if (prop == null) {
508             throw new NullPointerException("No mapped value for '" + name + "("
509                 + key + ")'");
510         } else if (prop instanceof Map) {
511             ((Map) prop).put(key, value);
512         } else {
513             throw new IllegalArgumentException("Non-mapped property for '"
514                 + name + "(" + key + ")'");
515         }
516     }
517 
518     // --------------------------------------------------------- Public Methods
519 
520     /***
521      * <p>Render a String representation of this object.</p>
522      *
523      * @return A string representation of this object.
524      */
525     public String toString() {
526         StringBuffer sb = new StringBuffer("DynaActionForm[dynaClass=");
527         DynaClass dynaClass = getDynaClass();
528 
529         if (dynaClass == null) {
530             return sb.append("null]").toString();
531         }
532 
533         sb.append(dynaClass.getName());
534 
535         DynaProperty[] props = dynaClass.getDynaProperties();
536 
537         if (props == null) {
538             props = new DynaProperty[0];
539         }
540 
541         for (int i = 0; i < props.length; i++) {
542             sb.append(',');
543             sb.append(props[i].getName());
544             sb.append('=');
545 
546             Object value = get(props[i].getName());
547 
548             if (value == null) {
549                 sb.append("<NULL>");
550             } else if (value.getClass().isArray()) {
551                 int n = Array.getLength(value);
552 
553                 sb.append("{");
554 
555                 for (int j = 0; j < n; j++) {
556                     if (j > 0) {
557                         sb.append(',');
558                     }
559 
560                     sb.append(Array.get(value, j));
561                 }
562 
563                 sb.append("}");
564             } else if (value instanceof List) {
565                 int n = ((List) value).size();
566 
567                 sb.append("{");
568 
569                 for (int j = 0; j < n; j++) {
570                     if (j > 0) {
571                         sb.append(',');
572                     }
573 
574                     sb.append(((List) value).get(j));
575                 }
576 
577                 sb.append("}");
578             } else if (value instanceof Map) {
579                 int n = 0;
580                 Iterator keys = ((Map) value).keySet().iterator();
581 
582                 sb.append("{");
583 
584                 while (keys.hasNext()) {
585                     if (n > 0) {
586                         sb.append(',');
587                     }
588 
589                     n++;
590 
591                     Object key = keys.next();
592 
593                     sb.append(key);
594                     sb.append('=');
595                     sb.append(((Map) value).get(key));
596                 }
597 
598                 sb.append("}");
599             } else {
600                 sb.append(value);
601             }
602         }
603 
604         sb.append("]");
605 
606         return (sb.toString());
607     }
608 
609     // -------------------------------------------------------- Package Methods
610 
611     /***
612      * <p>Set the <code>DynaActionFormClass</code> instance with which we are
613      * associated.</p>
614      *
615      * @param dynaClass The DynaActionFormClass instance for this bean
616      */
617     void setDynaActionFormClass(DynaActionFormClass dynaClass) {
618         this.dynaClass = dynaClass;
619     }
620 
621     // ------------------------------------------------------ Protected Methods
622 
623     /***
624      * <p>Return the property descriptor for the specified property name.</p>
625      *
626      * @param name Name of the property for which to retrieve the descriptor
627      * @return The property descriptor for the specified property name.
628      * @throws IllegalArgumentException if this is not a valid property name
629      *                                  for our DynaClass
630      */
631     protected DynaProperty getDynaProperty(String name) {
632         DynaProperty descriptor = getDynaClass().getDynaProperty(name);
633 
634         if (descriptor == null) {
635             throw new IllegalArgumentException("Invalid property name '" + name
636                 + "'");
637         }
638 
639         return (descriptor);
640     }
641 
642     /***
643      * <p>Indicates if an object of the source class is assignable to the
644      * destination class.</p>
645      *
646      * @param dest   Destination class
647      * @param source Source class
648      * @return <code>true</code> if the source is assignable to the
649      *         destination; <code>false</code> otherwise.
650      */
651     protected boolean isDynaAssignable(Class dest, Class source) {
652         if (dest.isAssignableFrom(source)
653             || ((dest == Boolean.TYPE) && (source == Boolean.class))
654             || ((dest == Byte.TYPE) && (source == Byte.class))
655             || ((dest == Character.TYPE) && (source == Character.class))
656             || ((dest == Double.TYPE) && (source == Double.class))
657             || ((dest == Float.TYPE) && (source == Float.class))
658             || ((dest == Integer.TYPE) && (source == Integer.class))
659             || ((dest == Long.TYPE) && (source == Long.class))
660             || ((dest == Short.TYPE) && (source == Short.class))) {
661             return (true);
662         } else {
663             return (false);
664         }
665     }
666 }