/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. package com.google.ie.common.editor;
  16. import java.beans.PropertyEditorSupport;
  17. /**
  18. * Property editor that trims Strings and replaces the carriage return with an
  19. * empty string.
  20. *
  21. * <p>
  22. * Optionally allows transforming an empty string into a <code>null</code>
  23. * value. Needs to be explictly registered, e.g. for command binding.
  24. *
  25. * @author Sachneet
  26. *
  27. */
  28. public class StringEditor extends PropertyEditorSupport {
  29. private static final String REGEX_EXPRESSION = "[\r]";
  30. private static final String EMPTY_STRING = "";
  31. private boolean emptyAsNull;
  32. /**
  33. * Create a new instance.
  34. *
  35. * @param emptyAsNull <code>true</code> if an empty String is to be
  36. * transformed into <code>null</code>
  37. */
  38. public StringEditor(boolean emptyAsNull) {
  39. super();
  40. this.emptyAsNull = emptyAsNull;
  41. }
  42. @Override
  43. public void setAsText(String text) {
  44. if (text == null) {
  45. setValue(null);
  46. } else {
  47. String value = text.trim();
  48. if (this.emptyAsNull && "".equals(value)) {
  49. setValue(null);
  50. } else {
  51. String replacedString = text.replaceAll(REGEX_EXPRESSION, EMPTY_STRING);
  52. setValue(replacedString);
  53. }
  54. }
  55. }
  56. @Override
  57. public String getAsText() {
  58. Object value = getValue();
  59. return (value != null ? value.toString() : "");
  60. }
  61. }