01: package org.vraptor.converter.basic;
02:
03: import org.vraptor.LogicRequest;
04: import org.vraptor.converter.ConversionException;
05: import org.vraptor.converter.Converter;
06:
07: /**
08: * Basic String to Enumeration converter. If the value begins with a number uses
09: * it as the ordinal position, otherwise uses it as its name. Uses the error key
10: * invalid_value if unable to parse its information.
11: *
12: * @author Guilherme Silveira
13: */
14: public class EnumConverter implements Converter {
15:
16: private static final Class<?>[] SUPPORTED_TYPES = new Class[] { Enum.class };
17:
18: @SuppressWarnings("unchecked")
19: public Object convert(String value, Class<?> type,
20: LogicRequest context) throws ConversionException {
21: if (value == null || value.equals("")) {
22: return null;
23: }
24: Class<? extends Enum> enumType = (Class<? extends Enum>) type;
25: if (Character.isDigit(value.charAt(0))) {
26: return resolveByOrdinal(value, type, enumType);
27: } else {
28: return resolveByName(value, type, enumType);
29: }
30: }
31:
32: public Class<?>[] getSupportedTypes() {
33: return SUPPORTED_TYPES;
34: }
35:
36: /**
37: * @param value
38: * @param type
39: * @param enumType
40: * @return
41: * @throws ConversionException
42: */
43: @SuppressWarnings("unchecked")
44: private Object resolveByName(String value, Class<?> type,
45: Class<? extends Enum> enumType) throws ConversionException {
46: try {
47: return Enum.valueOf(enumType, value);
48: } catch (IllegalArgumentException e) {
49: throw new ConversionException("invalid_value",
50: "Invalid enumeration value for type "
51: + type.getName() + " value " + value);
52: }
53: }
54:
55: /**
56: * @param value
57: * @param type
58: * @param enumType
59: * @return
60: * @throws ConversionException
61: */
62: private Object resolveByOrdinal(String value, Class<?> type,
63: Class<? extends Enum> enumType) throws ConversionException {
64: try {
65: int ordinal = Integer.parseInt(value);
66: if (ordinal >= enumType.getEnumConstants().length) {
67: throw new ConversionException("invalid_value",
68: "Invalid enumeration value for type "
69: + type.getName() + " value " + value);
70: }
71: return enumType.getEnumConstants()[ordinal];
72: } catch (NumberFormatException e) {
73: throw new ConversionException("invalid_value",
74: "Invalid enumeration value for type "
75: + type.getName() + " value " + value);
76: }
77: }
78:
79: }
|