Coverage Report - org.apache.tapestry5.util.StringToEnumCoercion
 
Classes in this File Line Coverage Branch Coverage Complexity
StringToEnumCoercion
100%
16/16
100%
6/6
0
 
 1  
 // Copyright 2007, 2008 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.tapestry5.util;
 16  
 
 17  
 import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
 18  
 import org.apache.tapestry5.ioc.internal.util.InternalUtils;
 19  
 import org.apache.tapestry5.ioc.services.Coercion;
 20  
 
 21  
 import java.util.Map;
 22  
 
 23  
 /**
 24  
  * A {@link org.apache.tapestry5.ioc.services.Coercion} for converting strings into an instance of a particular
 25  
  * enumerated type. The {@link Enum#name() name} is used as the key to identify the enum instance, in a case-insensitive
 26  
  * fashion.
 27  
  *
 28  
  * @param <T> the type of enumeration
 29  
  */
 30  66
 public final class StringToEnumCoercion<T extends Enum> implements Coercion<String, T>
 31  
 {
 32  
     private final Class<T> enumClass;
 33  
 
 34  246
     private final Map<String, T> stringToEnum = CollectionFactory.newCaseInsensitiveMap();
 35  
 
 36  
     public StringToEnumCoercion(Class<T> enumClass)
 37  
     {
 38  246
         this(enumClass, enumClass.getEnumConstants());
 39  246
     }
 40  
 
 41  
     public StringToEnumCoercion(Class<T> enumClass, T... values)
 42  246
     {
 43  246
         this.enumClass = enumClass;
 44  
 
 45  984
         for (T value : values)
 46  738
             stringToEnum.put(value.name(), value);
 47  246
     }
 48  
 
 49  
     public T coerce(String input)
 50  
     {
 51  74
         if (InternalUtils.isBlank(input))
 52  2
             return null;
 53  
 
 54  72
         T result = stringToEnum.get(input);
 55  
 
 56  72
         if (result == null)
 57  2
             throw new RuntimeException(PublicUtilMessages.missingEnumValue(
 58  
                     input,
 59  
                     enumClass,
 60  
                     stringToEnum.keySet()));
 61  
 
 62  70
         return result;
 63  
     }
 64  
 
 65  
 
 66  
     public static <T extends Enum> StringToEnumCoercion<T> create(Class<T> enumClass)
 67  
     {
 68  240
         return new StringToEnumCoercion<T>(enumClass);
 69  
     }
 70  
 
 71  
 }