Source code: org/apache/hivemind/schema/rules/EnumerationTranslator.java
1 // Copyright 2004, 2005 The Apache Software Foundation
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // 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.hivemind.schema.rules;
16
17 import java.lang.reflect.Field;
18 import java.util.Map;
19
20 import org.apache.hivemind.ApplicationRuntimeException;
21 import org.apache.hivemind.HiveMind;
22 import org.apache.hivemind.Location;
23 import org.apache.hivemind.internal.Module;
24 import org.apache.hivemind.schema.Translator;
25
26 /**
27 * Used to translate a set of strings to one of a number of constant values.
28 * Each input string is matched against the name of a public static field
29 * of a class. The name of the class, and the mappings, are provided
30 * in the initializer.
31 *
32 * @author Howard Lewis Ship
33 */
34 public class EnumerationTranslator implements Translator
35 {
36 private Map _mappings;
37 private String _className;
38 private Class _class;
39
40 /**
41 * Initialized the translator; the intitializer is the name of the class, a comma,
42 * and a series of key=value mappings from the input values to the names
43 * of the public static fields of the class.
44 */
45 public EnumerationTranslator(String initializer)
46 {
47 int commax = initializer.indexOf(',');
48
49 _className = initializer.substring(0, commax);
50
51 _mappings = RuleUtils.convertInitializer(initializer.substring(commax + 1));
52 }
53
54 private synchronized Class getClass(Module contributingModule)
55 {
56 if (_class == null)
57 _class = contributingModule.resolveType(_className);
58
59 return _class;
60 }
61
62 public Object translate(
63 Module contributingModule,
64 Class propertyType,
65 String inputValue,
66 Location location)
67 {
68 if (HiveMind.isBlank(inputValue))
69 return null;
70
71 Class c = getClass(contributingModule);
72
73 String fieldName = (String) _mappings.get(inputValue);
74
75 if (fieldName == null)
76 throw new ApplicationRuntimeException(
77 RulesMessages.enumNotRecognized(inputValue),
78 location,
79 null);
80
81 try
82 {
83 Field f = c.getField(fieldName);
84
85 return f.get(null);
86 }
87 catch (Exception ex)
88 {
89 throw new ApplicationRuntimeException(
90 RulesMessages.enumError(c, fieldName, ex),
91 location,
92 ex);
93 }
94 }
95
96 }