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