1
2
3
4
5
6
7 package org.mule.config.spring.editors;
8
9 import java.beans.PropertyEditorSupport;
10 import java.text.DateFormat;
11 import java.text.ParseException;
12 import java.util.Date;
13
14 import org.springframework.util.StringUtils;
15
16
17
18
19 public class DatePropertyEditor extends PropertyEditorSupport
20 {
21
22 private DateFormat dateFormat;
23
24 private DateFormat shortDateFormat;
25
26 private final boolean allowEmpty;
27
28 private final int exactDateLength;
29
30
31
32
33
34
35
36
37
38
39
40
41 public DatePropertyEditor(DateFormat longDateFormat, DateFormat shortDateFormat, boolean allowEmpty) {
42 this.dateFormat = longDateFormat;
43 this.shortDateFormat = shortDateFormat;
44 this.allowEmpty = allowEmpty;
45 this.exactDateLength = -1;
46 }
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 public DatePropertyEditor(DateFormat longDateFormat, boolean allowEmpty, int exactDateLength) {
64 this.dateFormat = longDateFormat;
65 this.allowEmpty = allowEmpty;
66 this.exactDateLength = exactDateLength;
67 }
68
69
70
71
72
73 @Override
74 public void setAsText(String text) throws IllegalArgumentException {
75 if (this.allowEmpty && !StringUtils.hasText(text)) {
76
77 setValue(null);
78 }
79 else if(text.equals("now"))
80 {
81 setValue(new Date());
82 }
83 else if (this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
84 throw new IllegalArgumentException(
85 "Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
86 }
87 else {
88 try {
89 if(shortDateFormat!=null && text.length() <=10) {
90 setValue(this.shortDateFormat.parse(text));
91 } else {
92 setValue(this.dateFormat.parse(text));
93 }
94 }
95 catch (ParseException ex) {
96 throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
97 }
98 }
99 }
100
101
102
103
104 @Override
105 public String getAsText() {
106 Date value = (Date) getValue();
107 return (value != null ? this.dateFormat.format(value) : "");
108 }
109 }