1 16 package org.springframework.binding.format.support; 17 18 import java.text.ParseException ; 19 20 import org.springframework.binding.format.Formatter; 21 import org.springframework.binding.format.InvalidFormatException; 22 import org.springframework.util.Assert; 23 import org.springframework.util.StringUtils; 24 25 30 public abstract class AbstractFormatter implements Formatter { 31 32 35 private boolean allowEmpty = true; 36 37 40 protected AbstractFormatter() { 41 } 42 43 47 protected AbstractFormatter(boolean allowEmpty) { 48 this.allowEmpty = allowEmpty; 49 } 50 51 public final String formatValue(Object value) { 52 if (allowEmpty && isEmpty(value)) { 53 return getEmptyFormattedValue(); 54 } 55 Assert.isTrue(!isEmpty(value), "Object to format cannot be empty"); 56 return doFormatValue(value); 57 } 58 59 65 protected abstract String doFormatValue(Object value); 66 67 protected String getEmptyFormattedValue() { 68 return ""; 69 } 70 71 77 public final Object parseValue(String formattedString, Class targetClass) throws InvalidFormatException { 78 try { 79 if (allowEmpty && isEmpty(formattedString)) { 80 return getEmptyValue(); 81 } 82 return doParseValue(formattedString, targetClass); 83 } 84 catch (ParseException ex) { 85 throw new InvalidFormatException(formattedString, getExpectedFormat(targetClass), ex); 86 } 87 } 88 89 protected Object getEmptyValue() { 90 return null; 91 } 92 93 protected String getExpectedFormat(Class targetClass) { 94 return null; 95 } 96 97 protected abstract Object doParseValue(String formattedString, Class targetClass) throws InvalidFormatException, 98 ParseException ; 99 100 protected boolean isEmpty(Object o) { 101 if (o == null) { 102 return true; 103 } 104 else if (o instanceof String ) { 105 return !StringUtils.hasText((String )o); 106 } 107 else { 108 return false; 109 } 110 } 111 112 public boolean isAllowEmpty() { 113 return allowEmpty; 114 } 115 } | Popular Tags |