View Javadoc
1   package org.csveed.bean.conversion;
2   
3   import static org.csveed.bean.conversion.ConversionUtil.hasLength;
4   
5   public class CustomBooleanConverter extends AbstractConverter<Boolean> {
6   
7       public static final String VALUE_TRUE = "true";
8       public static final String VALUE_FALSE = "false";
9   
10      public static final String VALUE_ON = "on";
11      public static final String VALUE_OFF = "off";
12  
13      public static final String VALUE_YES = "yes";
14      public static final String VALUE_NO = "no";
15  
16      public static final String VALUE_1 = "1";
17      public static final String VALUE_0 = "0";
18  
19      private final String trueString;
20  
21      private final String falseString;
22  
23      private final boolean allowEmpty;
24  
25      public CustomBooleanConverter(boolean allowEmpty) {
26          this(null, null, allowEmpty);
27      }
28  
29      public CustomBooleanConverter(String trueString, String falseString, boolean allowEmpty) {
30          super(Boolean.class);
31          this.trueString = trueString;
32          this.falseString = falseString;
33          this.allowEmpty = allowEmpty;
34      }
35  
36      @Override
37      public Boolean fromString(String text) throws Exception {
38          String input = text != null ? text.trim() : null;
39          if (this.allowEmpty && !hasLength(input)) {
40              return null;
41          } else if (this.trueString != null && this.trueString.equalsIgnoreCase(input)) {
42              return Boolean.TRUE;
43          } else if (this.falseString != null && this.falseString.equalsIgnoreCase(input)) {
44              return Boolean.FALSE;
45          } else if (this.trueString == null &&
46                  (VALUE_TRUE.equalsIgnoreCase(input) || VALUE_ON.equalsIgnoreCase(input) ||
47                          VALUE_YES.equalsIgnoreCase(input) || VALUE_1.equals(input))) {
48              return Boolean.TRUE;
49          } else if (this.falseString == null &&
50                  (VALUE_FALSE.equalsIgnoreCase(input) || VALUE_OFF.equalsIgnoreCase(input) ||
51                          VALUE_NO.equalsIgnoreCase(input) || VALUE_0.equals(input))) {
52              return Boolean.FALSE;
53          } else {
54              throw new IllegalArgumentException("Invalid boolean value [" + text + "]");
55          }
56      }
57  
58      @Override
59      public String toString(Boolean value) throws Exception {
60          if (Boolean.TRUE.equals(value)) {
61              return this.trueString != null ? this.trueString : VALUE_TRUE;
62          } else if (Boolean.FALSE.equals(value)) {
63              return this.falseString != null ? this.falseString : VALUE_FALSE;
64          } else {
65              return "";
66          }
67      }
68  
69  }