1 /**
2 * Copyright 2005-2016 The Kuali Foundation
3 *
4 * Licensed under the Educational Community License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.opensource.org/licenses/ecl2.php
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.kuali.rice.krad.web.bind;
17
18 import java.beans.PropertyEditorSupport;
19 import java.io.Serializable;
20
21 /**
22 * PropertyEditor for booleans supports y/n which the spring version does not
23 *
24 * @author Kuali Rice Team (rice.collab@kuali.org)
25 */
26 public class UifBooleanEditor extends PropertyEditorSupport implements Serializable {
27 private static final long serialVersionUID = -6333792216543862346L;
28
29 private static final String TRUE_VALUES = "/true/yes/y/on/1/";
30 private static final String FALSE_VALUES = "/false/no/n/off/0/";
31
32 private static final String TRUE_VALUE = "true";
33 private static final String FALSE_VALUE = "false";
34
35 /**
36 * Gets the property value as a string suitable for presentation
37 * to a human to edit
38 *
39 * @return The property value as a string suitable for presentation
40 * to a human to edit.
41 * <p> Returns String "true" or "false".
42 * <p> Returns "null" is the value can't be expressed as a string.
43 * <p> If a non-null value is returned, then the PropertyEditor should
44 * be prepared to parse that string back in setAsText().
45 */
46 @Override
47 public String getAsText() {
48 if(this.getValue() == null) {
49 return "";
50 }
51 else if(((Boolean)this.getValue()).booleanValue()) {
52 return TRUE_VALUE;
53 }
54 else {
55 return FALSE_VALUE;
56 }
57 }
58
59 /**
60 * Sets the property value by parsing a given String
61 *
62 * <p>
63 * The text is compared against the configured acceptable string values for
64 * boolean true and false
65 * </p>
66 *
67 * @param text The string to be parsed.
68 * @throws IllegalArgumentException if text does not contain either true or false
69 */
70 @Override
71 public void setAsText(String text) throws IllegalArgumentException {
72 String input = null;
73
74 if(text != null) {
75 StringBuilder builder = new StringBuilder();
76 builder.append("/").append(text.toLowerCase()).append("/");
77 input = builder.toString();
78
79 if(TRUE_VALUES.contains(input)) {
80 this.setValue(Boolean.TRUE);
81 }
82 else if(FALSE_VALUES.contains(input)) {
83 this.setValue(Boolean.FALSE);
84 }
85 else {
86 input = null;
87 }
88 }
89
90 if(input == null) {
91 throw new IllegalArgumentException("Invalid boolean input: " + text);
92 }
93 }
94
95 }