001 package edu.nrao.sss.webapp.faces.converter; 002 003 import javax.faces.convert.Converter; 004 import javax.faces.convert.ConverterException; 005 import javax.faces.context.FacesContext; 006 import javax.faces.component.UIComponent; 007 import javax.faces.application.FacesMessage; 008 009 import org.apache.log4j.Logger; 010 011 /** 012 * This class allows JSF to automatically convert Enums to and from 013 * Strings. 014 */ 015 public class EnumConverter implements Converter 016 { 017 private Logger log = Logger.getLogger(EnumConverter.class); 018 019 private Class<? extends Enum> c = null; 020 021 public EnumConverter(Class<? extends Enum> c) 022 { 023 setEnumClass(c); 024 } 025 026 public EnumConverter() {} 027 028 public Class getEnumClass() 029 { 030 return this.c; 031 } 032 033 public void setEnumClass(Class<? extends Enum> c) 034 { 035 if (c == null) 036 throw new IllegalArgumentException("Argument can not be null!"); 037 038 this.c = c; 039 } 040 041 @SuppressWarnings("unchecked") 042 public Object getAsObject(FacesContext context, UIComponent component, String value) 043 { 044 try 045 { 046 return Enum.valueOf(this.c, value); 047 } 048 catch (Exception e) 049 { 050 throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_WARN, "", "Value '" + value + "' is not a valid option for " + this.c.getName()), e); 051 } 052 } 053 054 public String getAsString(FacesContext context, UIComponent component, Object value) 055 { 056 if (value == null) 057 return ""; 058 059 if (value instanceof String) 060 return (String)value; 061 062 else if (c.isInstance(value)) 063 { 064 return ((Enum)value).name(); 065 } 066 067 else 068 { 069 String msg = "Cannot convert objects of type: " + value.getClass() + 070 "\n\tfor component: " + component.getClientId(FacesContext.getCurrentInstance()) + 071 "\n\tusing converter: " + this.getClass() + "." + 072 "\n\tOnly objects of type: " + c + " can be converted."; 073 074 log.debug(msg); 075 throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_WARN, "", msg)); 076 } 077 } 078 }