1 16 17 package org.springframework.core.enums; 18 19 import java.util.Collections ; 20 import java.util.HashMap ; 21 import java.util.Iterator ; 22 import java.util.Map ; 23 import java.util.Set ; 24 import java.util.TreeSet ; 25 26 import org.apache.commons.logging.Log; 27 import org.apache.commons.logging.LogFactory; 28 29 import org.springframework.util.Assert; 30 import org.springframework.util.CachingMapDecorator; 31 32 44 public abstract class AbstractCachingLabeledEnumResolver implements LabeledEnumResolver { 45 46 protected transient final Log logger = LogFactory.getLog(getClass()); 47 48 49 private CachingMapDecorator labeledEnumCache = new CachingMapDecorator() { 50 protected Object create(Object key) { 51 Set typeEnums = findLabeledEnums((Class ) key); 52 if (typeEnums == null || typeEnums.isEmpty()) { 53 throw new IllegalArgumentException ( 54 "Unsupported labeled enumeration type '" + key + "': " 55 + "make sure you've properly defined this enumeration: " 56 + "if it's static, are the class and its fields public/static/final?"); 57 } 58 Map typeEnumMap = new HashMap (typeEnums.size()); 59 for (Iterator it = typeEnums.iterator(); it.hasNext();) { 60 LabeledEnum labeledEnum = (LabeledEnum) it.next(); 61 typeEnumMap.put(labeledEnum.getCode(), labeledEnum); 62 } 63 return Collections.unmodifiableMap(typeEnumMap); 64 } 65 }; 66 67 68 public Set getLabeledEnumSet(Class type) throws IllegalArgumentException { 69 return new TreeSet (getLabeledEnumMap(type).values()); 70 } 71 72 public Map getLabeledEnumMap(Class type) throws IllegalArgumentException { 73 Assert.notNull(type, "No type specified"); 74 return (Map ) this.labeledEnumCache.get(type); 75 } 76 77 public LabeledEnum getLabeledEnumByCode(Class type, Comparable code) throws IllegalArgumentException { 78 Assert.notNull(code, "No enum code specified"); 79 Map typeEnums = getLabeledEnumMap(type); 80 LabeledEnum codedEnum = (LabeledEnum) typeEnums.get(code); 81 if (codedEnum == null) { 82 throw new IllegalArgumentException ( 83 "No enumeration with code '" + code + "'" + " of type [" + type.getName() 84 + "] exists: this is likely a configuration error; " 85 + "make sure the code value matches a valid instance's code property"); 86 } 87 return codedEnum; 88 } 89 90 public LabeledEnum getLabeledEnumByLabel(Class type, String label) throws IllegalArgumentException { 91 Map typeEnums = getLabeledEnumMap(type); 92 Iterator it = typeEnums.values().iterator(); 93 while (it.hasNext()) { 94 LabeledEnum value = (LabeledEnum) it.next(); 95 if (value.getLabel().equalsIgnoreCase(label)) { 96 return value; 97 } 98 } 99 throw new IllegalArgumentException ( 100 "No enumeration with label '" + label + "' of type [" + type 101 + "] exists: this is likely a configuration error; " 102 + "make sure the label string matches a valid instance's label property"); 103 } 104 105 106 113 protected abstract Set findLabeledEnums(Class type); 114 115 } 116 | Popular Tags |