01: /*
02: * Copyright 2002-2006 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 instance.
41: * @param emptyAsNull <code>true</code> if an empty string is to be transformed into <code>null</code>
42: */
43: public StringTrimmerEditor(boolean emptyAsNull) {
44: this .charsToDelete = null;
45: this .emptyAsNull = emptyAsNull;
46: }
47:
48: /**
49: * Create a new StringTrimmerEditor instance.
50: * @param charsToDelete a set of characters to delete, in addition to
51: * trimming an input String. Useful for deleting unwanted line breaks.
52: * E.g. "\r\n\f" will delete all new lines and line feeds in a String.
53: * @param emptyAsNull <code>true</code> if an empty string is to be transformed into <code>null</code>
54: */
55: public StringTrimmerEditor(String charsToDelete, boolean emptyAsNull) {
56: this .charsToDelete = charsToDelete;
57: this .emptyAsNull = emptyAsNull;
58: }
59:
60: public void setAsText(String text) {
61: if (text == null) {
62: setValue(null);
63: } else {
64: String value = text.trim();
65: if (this .charsToDelete != null) {
66: value = StringUtils
67: .deleteAny(value, this .charsToDelete);
68: }
69: if (this .emptyAsNull && "".equals(value)) {
70: setValue(null);
71: } else {
72: setValue(value);
73: }
74: }
75: }
76:
77: public String getAsText() {
78: Object value = getValue();
79: return (value != null ? value.toString() : "");
80: }
81:
82: }
|