01: /*
02: * Copyright 2002-2007 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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:
17: package org.springframework.beans.propertyeditors;
18:
19: import java.beans.PropertyEditorSupport;
20:
21: import org.springframework.util.StringUtils;
22:
23: /**
24: * Property editor that trims Strings.
25: *
26: * <p>Optionally allows transforming an empty string into a <code>null</code> value.
27: * Needs to be explictly registered, e.g. for command binding.
28: *
29: * @author Juergen Hoeller
30: * @see org.springframework.validation.DataBinder#registerCustomEditor
31: * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder
32: */
33: public class StringTrimmerEditor extends PropertyEditorSupport {
34:
35: private final String charsToDelete;
36:
37: private final boolean emptyAsNull;
38:
39: /**
40: * Create a new StringTrimmerEditor.
41: * @param emptyAsNull <code>true</code> if an empty String is to be
42: * transformed into <code>null</code>
43: */
44: public StringTrimmerEditor(boolean emptyAsNull) {
45: this .charsToDelete = null;
46: this .emptyAsNull = emptyAsNull;
47: }
48:
49: /**
50: * Create a new StringTrimmerEditor.
51: * @param charsToDelete a set of characters to delete, in addition to
52: * trimming an input String. Useful for deleting unwanted line breaks:
53: * e.g. "\r\n\f" will delete all new lines and line feeds in a String.
54: * @param emptyAsNull <code>true</code> if an empty String is to be
55: * transformed into <code>null</code>
56: */
57: public StringTrimmerEditor(String charsToDelete, boolean emptyAsNull) {
58: this .charsToDelete = charsToDelete;
59: this .emptyAsNull = emptyAsNull;
60: }
61:
62: public void setAsText(String text) {
63: if (text == null) {
64: setValue(null);
65: } else {
66: String value = text.trim();
67: if (this .charsToDelete != null) {
68: value = StringUtils
69: .deleteAny(value, this .charsToDelete);
70: }
71: if (this .emptyAsNull && "".equals(value)) {
72: setValue(null);
73: } else {
74: setValue(value);
75: }
76: }
77: }
78:
79: public String getAsText() {
80: Object value = getValue();
81: return (value != null ? value.toString() : "");
82: }
83:
84: }
|