1
2
3
4
5
6
7
8
9
10
11 package org.csveed.bean.conversion;
12
13 import static org.csveed.bean.conversion.ConversionUtil.hasLength;
14
15
16
17
18 public class CustomBooleanConverter extends AbstractConverter<Boolean> {
19
20
21 public static final String VALUE_TRUE = "true";
22
23
24 public static final String VALUE_FALSE = "false";
25
26
27 public static final String VALUE_SHORT_TRUE = "T";
28
29
30 public static final String VALUE_SHORT_FALSE = "F";
31
32
33 public static final String VALUE_ON = "on";
34
35
36 public static final String VALUE_OFF = "off";
37
38
39 public static final String VALUE_YES = "yes";
40
41
42 public static final String VALUE_NO = "no";
43
44
45 public static final String VALUE_SHORT_YES = "Y";
46
47
48 public static final String VALUE_SHORT_NO = "N";
49
50
51 public static final String VALUE_1 = "1";
52
53
54 public static final String VALUE_0 = "0";
55
56
57 private final String trueString;
58
59
60 private final String falseString;
61
62
63 private final boolean allowEmpty;
64
65
66
67
68
69
70
71 public CustomBooleanConverter(boolean allowEmpty) {
72 this(null, null, allowEmpty);
73 }
74
75
76
77
78
79
80
81
82
83
84
85 public CustomBooleanConverter(String trueString, String falseString, boolean allowEmpty) {
86 super(Boolean.class);
87 this.trueString = trueString;
88 this.falseString = falseString;
89 this.allowEmpty = allowEmpty;
90 }
91
92 @Override
93 public Boolean fromString(String text) throws Exception {
94 String input = text != null ? text.trim() : null;
95 if (this.allowEmpty && !hasLength(input)) {
96 return null;
97 }
98 if (this.trueString != null && this.trueString.equalsIgnoreCase(input)) {
99 return Boolean.TRUE;
100 }
101 if (this.falseString != null && this.falseString.equalsIgnoreCase(input)) {
102 return Boolean.FALSE;
103 }
104 if (this.trueString == null && (VALUE_TRUE.equalsIgnoreCase(input) || VALUE_SHORT_TRUE.equalsIgnoreCase(input)
105 || VALUE_ON.equalsIgnoreCase(input) || VALUE_YES.equalsIgnoreCase(input)
106 || VALUE_SHORT_YES.equalsIgnoreCase(input) || VALUE_1.equals(input))) {
107 return Boolean.TRUE;
108 }
109 if (this.falseString == null
110 && (VALUE_FALSE.equalsIgnoreCase(input) || VALUE_SHORT_FALSE.equalsIgnoreCase(input)
111 || VALUE_OFF.equalsIgnoreCase(input) || VALUE_NO.equalsIgnoreCase(input)
112 || VALUE_SHORT_NO.equalsIgnoreCase(input) || VALUE_0.equals(input))) {
113 return Boolean.FALSE;
114 }
115 throw new IllegalArgumentException("Invalid boolean value [" + text + "]");
116 }
117
118 @Override
119 public String toString(Boolean value) throws Exception {
120 if (Boolean.TRUE.equals(value)) {
121 return this.trueString != null ? this.trueString : VALUE_TRUE;
122 }
123 if (Boolean.FALSE.equals(value)) {
124 return this.falseString != null ? this.falseString : VALUE_FALSE;
125 }
126 return "";
127 }
128
129 }