1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.seasar.cubby.validator.validators;
17
18 import static org.seasar.cubby.internal.util.LogMessages.format;
19
20 import java.text.DateFormat;
21 import java.text.ParsePosition;
22 import java.text.SimpleDateFormat;
23 import java.util.Date;
24
25 import org.seasar.cubby.action.MessageInfo;
26 import org.seasar.cubby.controller.FormatPattern;
27 import org.seasar.cubby.internal.util.StringUtils;
28 import org.seasar.cubby.spi.ContainerProvider;
29 import org.seasar.cubby.spi.ProviderFactory;
30 import org.seasar.cubby.spi.container.Container;
31 import org.seasar.cubby.validator.ScalarFieldValidator;
32 import org.seasar.cubby.validator.ValidationContext;
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61 public class DateFormatValidator implements ScalarFieldValidator {
62
63
64
65
66 private final String messageKey;
67
68
69
70
71 private final String pattern;
72
73
74
75
76 public DateFormatValidator() {
77 this(null);
78 }
79
80
81
82
83
84
85
86 public DateFormatValidator(final String pattern) {
87 this(pattern, "valid.dateFormat");
88 }
89
90
91
92
93
94
95
96
97
98 public DateFormatValidator(final String pattern, final String messageKey) {
99 this.pattern = pattern;
100 this.messageKey = messageKey;
101 }
102
103
104
105
106 public void validate(final ValidationContext context, final Object value) {
107 if (value == null) {
108 return;
109 }
110 if (value instanceof String) {
111 final String stringValue = (String) value;
112 if (StringUtils.isEmpty((String) value)) {
113 return;
114 }
115 try {
116 final DateFormat dateFormat = createDateFormat(context, value);
117 final ParsePosition parsePosition = new ParsePosition(0);
118 final Date date = dateFormat.parse(stringValue, parsePosition);
119 if (date != null
120 && parsePosition.getIndex() == stringValue.length()) {
121 return;
122 }
123 } catch (final Exception e) {
124 }
125 }
126
127 final MessageInfo messageInfo = new MessageInfo();
128 messageInfo.setKey(this.messageKey);
129 context.addMessageInfo(messageInfo);
130 }
131
132
133
134
135
136
137
138
139
140
141 private DateFormat createDateFormat(final ValidationContext context,
142 final Object value) {
143 final SimpleDateFormat dateFormat = new SimpleDateFormat();
144 final String pattern;
145 if (StringUtils.isEmpty(this.pattern)) {
146 final Container container = ProviderFactory.get(
147 ContainerProvider.class).getContainer();
148 final FormatPattern formatPattern = container
149 .lookup(FormatPattern.class);
150 if (formatPattern == null) {
151 throw new IllegalStateException(format("ECUB0301", this, value));
152 }
153 pattern = formatPattern.getDatePattern();
154 } else {
155 pattern = this.pattern;
156 }
157 dateFormat.applyPattern(pattern);
158 dateFormat.setLenient(false);
159 return dateFormat;
160 }
161
162 }