PageRenderTime 243ms CodeModel.GetById 121ms app.highlight 4ms RepoModel.GetById 116ms app.codeStats 0ms

/src/main/java/com/google/ie/common/editor/StringEditor.java

http://thoughtsite.googlecode.com/
Java | 69 lines | 30 code | 8 blank | 31 comment | 7 complexity | 0ab6455965f68951f1d3035d80a8cdd5 MD5 | raw file
 1/* Copyright 2010 Google Inc.
 2 * 
 3 * Licensed under the Apache License, Version 2.0 (the "License");
 4 * you may not use this file except in compliance with the License.
 5 * You may obtain a copy of the License at
 6 * 
 7 *      http://www.apache.org/licenses/LICENSE-2.0
 8 * 
 9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS.
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License
14 */
15
16package com.google.ie.common.editor;
17
18import java.beans.PropertyEditorSupport;
19
20/**
21 * Property editor that trims Strings and replaces the carriage return with an
22 * empty string.
23 * 
24 * <p>
25 * Optionally allows transforming an empty string into a <code>null</code>
26 * value. Needs to be explictly registered, e.g. for command binding.
27 * 
28 * @author Sachneet
29 * 
30 */
31public class StringEditor extends PropertyEditorSupport {
32    private static final String REGEX_EXPRESSION = "[\r]";
33    private static final String EMPTY_STRING = "";
34    private boolean emptyAsNull;
35
36    /**
37     * Create a new instance.
38     * 
39     * @param emptyAsNull <code>true</code> if an empty String is to be
40     *        transformed into <code>null</code>
41     */
42    public StringEditor(boolean emptyAsNull) {
43        super();
44        this.emptyAsNull = emptyAsNull;
45    }
46
47    @Override
48    public void setAsText(String text) {
49        if (text == null) {
50            setValue(null);
51        } else {
52            String value = text.trim();
53            if (this.emptyAsNull && "".equals(value)) {
54                setValue(null);
55            } else {
56                String replacedString = text.replaceAll(REGEX_EXPRESSION, EMPTY_STRING);
57                setValue(replacedString);
58            }
59        }
60
61    }
62
63    @Override
64    public String getAsText() {
65        Object value = getValue();
66        return (value != null ? value.toString() : "");
67    }
68}
69