1 16 package org.springframework.binding.convert.support; 17 18 import org.springframework.binding.convert.ConversionContext; 19 import org.springframework.util.StringUtils; 20 21 26 public class TextToBoolean extends AbstractConverter { 27 28 private static final String VALUE_TRUE = "true"; 29 30 private static final String VALUE_FALSE = "false"; 31 32 private static final String VALUE_ON = "on"; 33 34 private static final String VALUE_OFF = "off"; 35 36 private static final String VALUE_YES = "yes"; 37 38 private static final String VALUE_NO = "no"; 39 40 private static final String VALUE_1 = "1"; 41 42 private static final String VALUE_0 = "0"; 43 44 private String trueString; 45 46 private String falseString; 47 48 public TextToBoolean() { 49 50 } 51 52 public TextToBoolean(String trueString, String falseString) { 53 this.trueString = trueString; 54 this.falseString = falseString; 55 } 56 57 public Class [] getSourceClasses() { 58 return new Class [] { String .class }; 59 } 60 61 public Class [] getTargetClasses() { 62 return new Class [] { Boolean .class }; 63 } 64 65 protected Object doConvert(Object source, Class targetClass, ConversionContext context) throws Exception { 66 String text = (String )source; 67 if (!StringUtils.hasText(text)) { 68 return null; 69 } 70 else if (this.trueString != null && text.equalsIgnoreCase(this.trueString)) { 71 return Boolean.TRUE; 72 } 73 else if (this.falseString != null && text.equalsIgnoreCase(this.falseString)) { 74 return Boolean.FALSE; 75 } 76 else if (this.trueString == null 77 && (text.equalsIgnoreCase(VALUE_TRUE) || text.equalsIgnoreCase(VALUE_ON) 78 || text.equalsIgnoreCase(VALUE_YES) || text.equals(VALUE_1))) { 79 return Boolean.TRUE; 80 } 81 else if (this.falseString == null 82 && (text.equalsIgnoreCase(VALUE_FALSE) || text.equalsIgnoreCase(VALUE_OFF) 83 || text.equalsIgnoreCase(VALUE_NO) || text.equals(VALUE_0))) { 84 return Boolean.FALSE; 85 } 86 else { 87 throw new IllegalArgumentException ("Invalid boolean value [" + text + "]"); 88 } 89 } 90 } | Popular Tags |