KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > binding > format > support > LabeledEnumFormatter


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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  * @author Keith Donald
27  */

28 public class LabeledEnumFormatter extends AbstractFormatter {
29
30     private LabeledEnumResolver labeledEnumResolver = StaticLabeledEnumResolver.instance();
31
32     public LabeledEnumFormatter() {
33     }
34
35     public LabeledEnumFormatter(boolean allowEmpty) {
36         super(allowEmpty);
37     }
38
39     public void setLabeledEnumResolver(LabeledEnumResolver labeledEnumResolver) {
40         Assert.notNull(labeledEnumResolver, "The labeled enum resolver is required");
41         this.labeledEnumResolver = labeledEnumResolver;
42     }
43
44     protected String JavaDoc doFormatValue(Object JavaDoc value) {
45         LabeledEnum labeledEnum = (LabeledEnum)value;
46         return labeledEnum.getLabel();
47     }
48
49     protected Object JavaDoc doParseValue(String JavaDoc formattedString, Class JavaDoc targetClass) throws IllegalArgumentException JavaDoc {
50         LabeledEnum labeledEnum = labeledEnumResolver.getLabeledEnumByLabel(targetClass, formattedString);
51         if (!isAllowEmpty()) {
52             Assert.notNull(labeledEnum, "The label '" + formattedString
53                     + "' did not map to a valid enum instance for type " + targetClass);
54             Assert.isInstanceOf(targetClass, labeledEnum);
55         }
56         return labeledEnum;
57     }
58
59     public LabeledEnum parseLabeledEnum(String JavaDoc formattedString, Class JavaDoc enumClass) throws InvalidFormatException {
60         return (LabeledEnum)parseValue(formattedString, enumClass);
61     }
62 }
Popular Tags