View Javadoc

1   /*
2    * Copyright 2009-2010 Steve Chaloner
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 be.objectify.led.factory.object;
17  
18  import org.slf4j.Logger;
19  import org.slf4j.LoggerFactory;
20  
21  /**
22   * Object factory for Enums.
23   *
24   * @author Steve Chaloner
25   */
26  public class EnumFactory extends AbstractObjectFactory<Enum>
27  {
28      private static final Logger LOGGER = LoggerFactory.getLogger(EnumFactory.class);
29  
30      private final Class<? extends Enum> clazz;
31  
32      public EnumFactory(Class<? extends Enum> clazz)
33      {
34          this.clazz = clazz;
35      }
36  
37      /**
38       * {@inheritDoc}
39       */
40      public Enum createObject(String propertyName,
41                               String propertyValue)
42      {
43          Enum value = null;
44  
45          if (propertyValue != null)
46          {
47              propertyValue = propertyValue.trim();
48              try
49              {
50                  value = getValue(clazz,
51                                   propertyValue);
52              }
53              catch (IllegalArgumentException e)
54              {
55                  LOGGER.error(String.format("Unable to parse %s to enum of type [%s]",
56                                             propertyValue,
57                                             clazz),
58                               e);
59              }
60          }
61          return value;
62      }
63  
64      /**
65       * {@inheritDoc}
66       */
67      public Class<Enum> getBoundClass()
68      {
69          return Enum.class;
70      }
71  
72      private Enum getValue(Class<? extends Enum> clazz,
73                            String value) throws IllegalArgumentException
74      {
75          Enum e;
76          try
77          {
78              e = Enum.valueOf(clazz,
79                               value);
80          }
81          catch (IllegalArgumentException e1)
82          {
83              try
84              {
85                  e = Enum.valueOf(clazz,
86                                   value.toUpperCase());
87              }
88              catch (IllegalArgumentException e2)
89              {
90                  e = Enum.valueOf(clazz,
91                                   value.toLowerCase());
92              }
93          }
94  
95          return e;
96      }
97  }