1 16 17 package org.springframework.beans.propertyeditors; 18 19 import java.beans.PropertyEditorSupport ; 20 21 import org.springframework.util.StringUtils; 22 23 40 public class CustomBooleanEditor extends PropertyEditorSupport { 41 42 public static final String VALUE_TRUE = "true"; 43 public static final String VALUE_FALSE = "false"; 44 45 public static final String VALUE_ON = "on"; 46 public static final String VALUE_OFF = "off"; 47 48 public static final String VALUE_YES = "yes"; 49 public static final String VALUE_NO = "no"; 50 51 public static final String VALUE_1 = "1"; 52 public static final String VALUE_0 = "0"; 53 54 55 private final String trueString; 56 57 private final String falseString; 58 59 private final boolean allowEmpty; 60 61 62 70 public CustomBooleanEditor(boolean allowEmpty) { 71 this(null, null, allowEmpty); 72 } 73 74 94 public CustomBooleanEditor(String trueString, String falseString, boolean allowEmpty) { 95 this.trueString = trueString; 96 this.falseString = falseString; 97 this.allowEmpty = allowEmpty; 98 } 99 100 public void setAsText(String text) throws IllegalArgumentException { 101 if (this.allowEmpty && !StringUtils.hasText(text)) { 102 setValue(null); 104 } 105 else if (this.trueString != null && text.equalsIgnoreCase(this.trueString)) { 106 setValue(Boolean.TRUE); 107 } 108 else if (this.falseString != null && text.equalsIgnoreCase(this.falseString)) { 109 setValue(Boolean.FALSE); 110 } 111 else if (this.trueString == null && 112 (text.equalsIgnoreCase(VALUE_TRUE) || text.equalsIgnoreCase(VALUE_ON) || 113 text.equalsIgnoreCase(VALUE_YES) || text.equals(VALUE_1))) { 114 setValue(Boolean.TRUE); 115 } 116 else if (this.falseString == null && 117 (text.equalsIgnoreCase(VALUE_FALSE) || text.equalsIgnoreCase(VALUE_OFF) || 118 text.equalsIgnoreCase(VALUE_NO) || text.equals(VALUE_0))) { 119 setValue(Boolean.FALSE); 120 } 121 else { 122 throw new IllegalArgumentException ("Invalid boolean value [" + text + "]"); 123 } 124 } 125 126 public String getAsText() { 127 if (Boolean.TRUE.equals(getValue())) { 128 return (this.trueString != null ? this.trueString : VALUE_TRUE); 129 } 130 else if (Boolean.FALSE.equals(getValue())) { 131 return (this.falseString != null ? this.falseString : VALUE_FALSE); 132 } 133 else { 134 return ""; 135 } 136 } 137 138 } 139 | Popular Tags |