01: // Copyright 2007 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // Unless required by applicable law or agreed to in writing, software
10: // distributed under the License is distributed on an "AS IS" BASIS,
11: // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: // See the License for the specific language governing permissions and
13: // limitations under the License.
14:
15: package org.apache.tapestry.util;
16:
17: import static org.apache.tapestry.ioc.internal.util.CollectionFactory.newCaseInsensitiveMap;
18:
19: import java.util.Map;
20:
21: import org.apache.tapestry.ioc.internal.util.InternalUtils;
22: import org.apache.tapestry.ioc.services.Coercion;
23:
24: /**
25: * A {@link Coercion} for converting strings into an instance of a particular enumerated type. The
26: * {@link Enum#name() name} is used as the key to identify the enum instance, in a case-insensitive
27: * fashion.
28: *
29: * @param <T>
30: * the type of enumeration
31: */
32: public final class StringToEnumCoercion<T extends Enum> implements
33: Coercion<String, T> {
34: private final Class<T> _enumClass;
35:
36: private final Map<String, T> _stringToEnum = newCaseInsensitiveMap();
37:
38: public StringToEnumCoercion(Class<T> enumClass) {
39: this (enumClass, enumClass.getEnumConstants());
40: }
41:
42: public StringToEnumCoercion(Class<T> enumClass, T... values) {
43: _enumClass = enumClass;
44:
45: for (T value : values)
46: _stringToEnum.put(value.name(), value);
47: }
48:
49: public T coerce(String input) {
50: if (InternalUtils.isBlank(input))
51: return null;
52:
53: T result = _stringToEnum.get(input);
54:
55: if (result == null)
56: throw new RuntimeException(UtilMessages.missingEnumValue(
57: input, _enumClass, _stringToEnum.keySet()));
58:
59: return result;
60: }
61:
62: }
|