01: /*
02: * Copyright 2004-2007 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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.springframework.binding.format.support;
17:
18: import org.springframework.binding.format.InvalidFormatException;
19: import org.springframework.core.enums.LabeledEnum;
20: import org.springframework.core.enums.LabeledEnumResolver;
21: import org.springframework.core.enums.StaticLabeledEnumResolver;
22: import org.springframework.util.Assert;
23:
24: /**
25: * Converts from string to a <cod>LabeledEnum</code> instance and back.
26: *
27: * @author Keith Donald
28: */
29: public class LabeledEnumFormatter extends AbstractFormatter {
30:
31: private LabeledEnumResolver labeledEnumResolver = StaticLabeledEnumResolver
32: .instance();
33:
34: /**
35: * Default constructor.
36: */
37: public LabeledEnumFormatter() {
38: }
39:
40: /**
41: * Create a new LabeledEnum formatter.
42: * @param allowEmpty should this formatter allow empty input arguments?
43: */
44: public LabeledEnumFormatter(boolean allowEmpty) {
45: super (allowEmpty);
46: }
47:
48: /**
49: * Set the LabeledEnumResolver used. Defaults to {@link StaticLabeledEnumResolver}.
50: */
51: public void setLabeledEnumResolver(
52: LabeledEnumResolver labeledEnumResolver) {
53: Assert.notNull(labeledEnumResolver,
54: "The labeled enum resolver is required");
55: this .labeledEnumResolver = labeledEnumResolver;
56: }
57:
58: protected String doFormatValue(Object value) {
59: LabeledEnum labeledEnum = (LabeledEnum) value;
60: return labeledEnum.getLabel();
61: }
62:
63: protected Object doParseValue(String formattedString,
64: Class targetClass) throws IllegalArgumentException {
65: LabeledEnum labeledEnum = labeledEnumResolver
66: .getLabeledEnumByLabel(targetClass, formattedString);
67: if (!isAllowEmpty()) {
68: Assert
69: .notNull(
70: labeledEnum,
71: "The label '"
72: + formattedString
73: + "' did not map to a valid enum instance for type "
74: + targetClass);
75: Assert.isInstanceOf(targetClass, labeledEnum);
76: }
77: return labeledEnum;
78: }
79:
80: /**
81: * Convenience method to parse a LabeledEnum.
82: */
83: public LabeledEnum parseLabeledEnum(String formattedString,
84: Class enumClass) throws InvalidFormatException {
85: return (LabeledEnum) parseValue(formattedString, enumClass);
86: }
87: }
|