1 16 package com.blandware.atleap.common.util; 17 18 import org.apache.commons.beanutils.ConversionException; 19 import org.apache.commons.beanutils.Converter; 20 import org.apache.commons.lang.StringUtils; 21 22 import java.text.DateFormat ; 23 import java.text.SimpleDateFormat ; 24 import java.util.Date ; 25 import java.util.Locale ; 26 27 28 43 public class CommonConverter implements Converter { 44 45 protected Locale locale; 46 protected DateFormat formatter; 47 48 51 public CommonConverter() { 52 this(Locale.getDefault()); 53 } 54 55 60 public CommonConverter(Locale locale) { 61 this.locale = locale; 62 this.formatter = new SimpleDateFormat (DateUtil.getDatePattern(locale), locale); 63 } 64 65 76 public Object convert(Class type, Object value) { 77 if ( value == null ) { 78 return null; 79 } else if ( type == Date .class ) { 80 return convertToDate(type, value); 81 } else if ( type == String .class ) { 82 return convertToString(type, value); 83 } else if ( type == Object .class ) { 84 return convertToObject(type, value); 85 } 86 87 throw new ConversionException("Could not convert " + 88 value.getClass().getName() + " to " + 89 type.getName()); 90 } 91 92 99 protected Object convertToDate(Class type, Object value) { 100 if ( value instanceof Date ) { 101 return value; 102 } 103 104 if ( value instanceof String ) { 105 try { 106 if ( StringUtils.isEmpty(value.toString()) ) { 107 return null; 108 } 109 110 return formatter.parse((String ) value); 111 } catch ( Exception pe ) { 112 throw new ConversionException("Error converting String to Date"); 113 } 114 } 115 116 throw new ConversionException("Could not convert " + 117 value.getClass().getName() + " to " + 118 type.getName()); 119 } 120 121 128 protected Object convertToString(Class type, Object value) { 129 if ( value instanceof Date ) { 130 try { 131 return formatter.format(value); 132 } catch ( Exception e ) { 133 throw new ConversionException("Error converting Date to String"); 134 } 135 } 136 137 return value.toString(); 138 } 139 140 147 protected Object convertToObject(Class type, Object value) { 148 return value; 149 } 150 151 } 152 | Popular Tags |