001 package org.trails.component;
002
003 import java.util.Arrays;
004 import java.util.List;
005
006 import org.trails.exception.TrailsRuntimeException;
007
008 /**
009 * Implementation of a property model that works off of native
010 * java enum types.
011
012 * <p>
013 * The main diference with Tapestry's EnumPropertySelectionModel is that "allowNone" and the property used to get the
014 * label values (labelProperty) are both configurable.
015 * </p>
016
017 * <p>
018 * The enum label/values are all translated by calling the method indicated by "labelProperty"
019 * By default labelProperty = "toString()", so it may be a good idea to provide a toString() method in your Enums if the
020 * types aren't what you would prefer to display.
021 * </p>
022 */
023 public class EnumPropertySelectionModel extends AbstractPropertySelectionModel
024 {
025 private Class type;
026
027 public EnumPropertySelectionModel(Class type)
028 {
029 this(type, false);
030 }
031
032 public EnumPropertySelectionModel(Enum[] set)
033 {
034 this(Arrays.asList(set), false);
035 }
036
037 public EnumPropertySelectionModel(Enum[] set, boolean allowNone)
038 {
039 this(Arrays.asList(set), allowNone);
040 }
041
042 public EnumPropertySelectionModel(List instances, boolean allowNone)
043 {
044 super(instances, allowNone);
045 }
046
047 public EnumPropertySelectionModel(Class type, boolean allowNone)
048 {
049 super(Arrays.asList(type.getEnumConstants()), allowNone);
050 this.type = type;
051 }
052
053 public EnumPropertySelectionModel(Class type, String labelProperty, boolean allowNone)
054 {
055 this(type, allowNone);
056 setLabelProperty(labelProperty);
057 }
058
059 /*
060 * (non-Javadoc)
061 *
062 * @see org.apache.tapestry.form.IPropertySelectionModel#getValue(int)
063 */
064 public String getValue(int index)
065 {
066 try
067 {
068 if (allowNone && index == 0)
069 {
070 return DEFAULT_NONE_VALUE;
071 } else
072 {
073 return instances.get(index).toString();
074 }
075 } catch (Exception e)
076 {
077 throw new TrailsRuntimeException(e, type);
078 }
079 }
080
081 /*
082 * (non-Javadoc)
083 *
084 * @see org.apache.tapestry.form.IPropertySelectionModel#translateValue(java.lang.String)
085 */
086 public Object translateValue(String value)
087 {
088 if (allowNone)
089 {
090 if (value.equals(DEFAULT_NONE_VALUE))
091 return null;
092 }
093 for (Object enumElement : instances)
094 {
095 if (enumElement != null && enumElement.toString().equals(value))
096 {
097 return enumElement;
098 }
099 }
100 return null;
101 }
102 }