View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.validator.routines;
18  
19  import junit.framework.TestCase;
20  
21  import java.util.Date;
22  import java.util.Calendar;
23  import java.util.Locale;
24  import java.util.TimeZone;
25  
26  /**
27   * Test Case for TimeValidator.
28   * 
29   * @version $Revision$
30   */
31  public class TimeValidatorTest extends TestCase {
32  
33      protected static final TimeZone GMT = TimeZone.getTimeZone("GMT"); // 0 offset
34      protected static final TimeZone EST = TimeZone.getTimeZone("EST"); // - 5 hours
35  
36      protected TimeValidator validator;
37  
38      protected String[] patternValid = new String[] {
39                         "23-59-59" 
40                        ,"00-00-00"
41                        ,"00-00-01"
42                        ,"0-0-0" 
43                        ,"1-12-1"
44                        ,"10-49-18"
45                        ,"16-23-46"};
46      protected Date[] patternExpect = new Date[] {
47                         createDate(null, 235959, 0)
48                        ,createDate(null, 0, 0)
49                        ,createDate(null, 1, 0)
50                        ,createDate(null, 0, 0)
51                        ,createDate(null, 11201, 0)
52                        ,createDate(null, 104918, 0)
53                        ,createDate(null, 162346, 0)};
54      protected String[] localeValid = new String[] {
55                        "23:59" 
56                       ,"00:00"
57                       ,"00:01"
58                       ,"0:0" 
59                       ,"1:12"
60                       ,"10:49"
61                       ,"16:23"};
62      protected Date[] localeExpect = new Date[] {
63                        createDate(null, 235900, 0)
64                       ,createDate(null, 0, 0)
65                       ,createDate(null, 100, 0)
66                       ,createDate(null, 0, 0)
67                       ,createDate(null, 11200, 0)
68                       ,createDate(null, 104900, 0)
69                       ,createDate(null, 162300, 0)};
70      protected String[] patternInvalid = new String[] {
71                           "24-00-00"  // midnight
72                          ,"24-00-01"  // past midnight
73                          ,"25-02-03"  // invalid hour 
74                          ,"10-61-31"  // invalid minute
75                          ,"10-01-61"  // invalid second
76                          ,"05:02-29"  // invalid sep 
77                          ,"0X-01:01"  // invalid sep
78                          ,"05-0X-01"  // invalid char
79                          ,"10-01-0X"  // invalid char
80                          ,"01:01:05"  // invalid pattern
81                          ,"10-10"     // invalid pattern
82                          ,"10--10"    // invalid pattern
83                          ,"10-10-"};  // invalid pattern
84      protected String[] localeInvalid = new String[] {
85                           "24:00"  // midnight
86                          ,"24:00"  // past midnight
87                          ,"25:02"  // invalid hour 
88                          ,"10:61"  // invalid minute
89                          ,"05-02"  // invalid sep 
90                          ,"0X:01"  // invalid sep
91                          ,"05:0X"  // invalid char
92                          ,"01-01"  // invalid pattern
93                          ,"10:"     // invalid pattern
94                          ,"10::1"    // invalid pattern
95                          ,"10:1:"};  // invalid pattern
96  
97      private Locale origDefault;
98      private TimeZone defaultZone;
99  
100     /**
101      * Constructor
102      * @param name test name
103      */
104     public TimeValidatorTest(String name) {
105         super(name);
106     }
107 
108     @Override
109     protected void setUp() throws Exception {
110         super.setUp();
111         validator = new TimeValidator();
112         defaultZone = TimeZone.getDefault();
113         origDefault = Locale.getDefault();
114     }
115 
116     /**
117      * Tear down
118      * @throws Exception
119      */
120     @Override
121     protected void tearDown() throws Exception {
122         super.tearDown();
123         validator = null;
124         Locale.setDefault(origDefault);
125         TimeZone.setDefault(defaultZone);
126     }
127 
128     /**
129      * Test Valid Dates with "pattern" validation
130      */
131     public void testPatternValid() {
132         for (int i = 0; i < patternValid.length; i++) {
133             String text = i + " value=[" +patternValid[i]+"] failed ";
134             Calendar calendar = validator.validate(patternValid[i], "HH-mm-ss");
135             assertNotNull("validateObj() " + text,  calendar);
136             Date date = calendar.getTime();
137             assertTrue("isValid() " + text,  validator.isValid(patternValid[i], "HH-mm-ss"));
138             assertEquals("compare " + text, patternExpect[i], date);
139         }
140     }
141 
142     /**
143      * Test Invalid Dates with "pattern" validation
144      */
145     public void testPatternInvalid() {
146         for (int i = 0; i < patternInvalid.length; i++) {
147             String text = i + " value=[" +patternInvalid[i]+"] passed ";
148             Object date = validator.validate(patternInvalid[i], "HH-mm-ss");
149             assertNull("validate() " + text + date,  date);
150             assertFalse("isValid() " + text,  validator.isValid(patternInvalid[i], "HH-mm-ss"));
151         }
152     }
153 
154     /**
155      * Test Valid Dates with "locale" validation
156      */
157     public void testLocaleValid() {
158         for (int i = 0; i < localeValid.length; i++) {
159             String text = i + " value=[" +localeValid[i]+"] failed ";
160             Calendar calendar = validator.validate(localeValid[i], Locale.UK);
161             assertNotNull("validate() " + text,  calendar);
162             Date date = calendar.getTime();
163             assertTrue("isValid() " + text,  validator.isValid(localeValid[i], Locale.UK));
164             assertEquals("compare " + text, localeExpect[i], date);
165         }
166     }
167 
168     /**
169      * Test Invalid Dates with "locale" validation
170      */
171     public void testLocaleInvalid() {
172         for (int i = 0; i < localeInvalid.length; i++) {
173             String text = i + " value=[" +localeInvalid[i]+"] passed ";
174             Object date = validator.validate(localeInvalid[i], Locale.US);
175             assertNull("validate() " + text + date,  date);
176             assertFalse("isValid() " + text,  validator.isValid(localeInvalid[i], Locale.UK));
177         }
178     }
179 
180     /**
181      * Test time zone methods.
182      */
183     public void testTimeZone() {
184         // Set the default Locale & TimeZone
185         Locale.setDefault(Locale.UK);
186         TimeZone.setDefault(GMT);
187 
188         Calendar result = null;
189 
190         // Default Locale, Default TimeZone
191         result = validator.validate("18:01");
192         assertNotNull("default result", result);
193         assertEquals("default zone",  GMT, result.getTimeZone());
194         assertEquals("default hour",   18, result.get(Calendar.HOUR_OF_DAY));
195         assertEquals("default minute", 01, result.get(Calendar.MINUTE));
196         result = null;
197 
198         // Default Locale, diff TimeZone
199         result = validator.validate("16:49", EST);
200         assertNotNull("zone result", result);
201         assertEquals("zone zone",  EST, result.getTimeZone());
202         assertEquals("zone hour",   16, result.get(Calendar.HOUR_OF_DAY));
203         assertEquals("zone minute", 49, result.get(Calendar.MINUTE));
204         result = null;
205 
206         // Pattern, diff TimeZone
207         result = validator.validate("14-34", "HH-mm", EST);
208         assertNotNull("pattern result", result);
209         assertEquals("pattern zone",  EST, result.getTimeZone());
210         assertEquals("pattern hour",   14, result.get(Calendar.HOUR_OF_DAY));
211         assertEquals("pattern minute", 34, result.get(Calendar.MINUTE));
212         result = null;
213 
214         // Locale, diff TimeZone
215         result = validator.validate("7:18 PM", Locale.US, EST);
216         assertNotNull("locale result", result);
217         assertEquals("locale zone",  EST, result.getTimeZone());
218         assertEquals("locale hour",   19, result.get(Calendar.HOUR_OF_DAY));
219         assertEquals("locale minute", 18, result.get(Calendar.MINUTE));
220         result = null;
221 
222         // Locale & Pattern, diff TimeZone
223         result = validator.validate("31/Dez/05 21-05", "dd/MMM/yy HH-mm", Locale.GERMAN, EST);
224         assertNotNull("pattern result", result);
225         assertEquals("pattern zone",  EST, result.getTimeZone());
226         assertEquals("pattern day",  2005, result.get(Calendar.YEAR));
227         assertEquals("pattern day",    11, result.get(Calendar.MONTH)); // months are 0-11
228         assertEquals("pattern day",    31, result.get(Calendar.DATE));
229         assertEquals("pattern hour",   21, result.get(Calendar.HOUR_OF_DAY));
230         assertEquals("pattern minute", 05, result.get(Calendar.MINUTE));
231         result = null;
232 
233         // Locale & Pattern, default TimeZone
234         result = validator.validate("31/Dez/05 21-05", "dd/MMM/yy HH-mm", Locale.GERMAN);
235         assertNotNull("pattern result", result);
236         assertEquals("pattern zone",  GMT, result.getTimeZone());
237         assertEquals("pattern day",  2005, result.get(Calendar.YEAR));
238         assertEquals("pattern day",    11, result.get(Calendar.MONTH)); // months are 0-11
239         assertEquals("pattern day",    31, result.get(Calendar.DATE));
240         assertEquals("pattern hour",   21, result.get(Calendar.HOUR_OF_DAY));
241         assertEquals("pattern minute", 05, result.get(Calendar.MINUTE));
242         result = null;
243 
244     }
245 
246     /**
247      * Test Invalid Dates with "locale" validation
248      */
249     public void testFormat() {
250         // Set the default Locale
251         Locale.setDefault(Locale.UK);
252 
253         Object test = TimeValidator.getInstance().validate("16:49:23", "HH:mm:ss");
254         assertNotNull("Test Date ", test);
255         assertEquals("Format pattern", "16-49-23", validator.format(test, "HH-mm-ss"));
256         assertEquals("Format locale",  "4:49 PM",  validator.format(test, Locale.US));
257         assertEquals("Format default", "16:49",  validator.format(test));
258 
259     }
260 
261     /**
262      * Test compare date methods
263      */
264     public void testCompare() {
265         int testTime = 154523;
266         int min = 100;
267         int hour = 10000;
268 
269         Calendar milliGreater = createTime(GMT, testTime, 500); // > milli sec
270         Calendar value        = createTime(GMT, testTime, 400); // test value
271         Calendar milliLess    = createTime(GMT, testTime, 300); // < milli sec
272 
273         Calendar secGreater   = createTime(GMT, testTime + 1, 100);   // +1 sec
274         Calendar secLess      = createTime(GMT, testTime - 1, 100);   // -1 sec
275 
276         Calendar minGreater   = createTime(GMT, testTime + min, 100);   // +1 min
277         Calendar minLess      = createTime(GMT, testTime - min, 100);   // -1 min
278 
279         Calendar hourGreater  = createTime(GMT, testTime + hour, 100);   // +1 hour
280         Calendar hourLess     = createTime(GMT, testTime - hour, 100);   // -1 hour
281 
282         assertEquals("mili LT", -1, validator.compareTime(value, milliGreater)); // > milli
283         assertEquals("mili EQ", 0,  validator.compareTime(value, value));        // same time
284         assertEquals("mili GT", 1,  validator.compareTime(value, milliLess));    // < milli
285 
286         assertEquals("secs LT", -1, validator.compareSeconds(value, secGreater));   // +1 sec
287         assertEquals("secs =1", 0,  validator.compareSeconds(value, milliGreater)); // > milli
288         assertEquals("secs =2", 0,  validator.compareSeconds(value, value));        // same time
289         assertEquals("secs =3", 0,  validator.compareSeconds(value, milliLess));    // < milli
290         assertEquals("secs GT", 1,  validator.compareSeconds(value, secLess));      // -1 sec
291 
292         assertEquals("mins LT", -1, validator.compareMinutes(value, minGreater));   // +1 min
293         assertEquals("mins =1", 0,  validator.compareMinutes(value, secGreater));   // +1 sec
294         assertEquals("mins =2", 0,  validator.compareMinutes(value, value));        // same time
295         assertEquals("mins =3", 0,  validator.compareMinutes(value, secLess));      // -1 sec
296         assertEquals("mins GT", 1,  validator.compareMinutes(value, minLess));      // -1 min
297 
298         assertEquals("hour LT", -1, validator.compareHours(value, hourGreater));   // +1 hour
299         assertEquals("hour =1", 0,  validator.compareHours(value, minGreater));   // +1 min
300         assertEquals("hour =2", 0,  validator.compareHours(value, value));        // same time
301         assertEquals("hour =3", 0,  validator.compareHours(value, minLess));      // -1 min
302         assertEquals("hour GT", 1,  validator.compareHours(value, hourLess));      // -1 hour
303 
304     }
305 
306     /**
307      * Create a calendar instance for a specified time zone, date and time.
308      * 
309      * @param zone The time zone
310      * @param time the time in HH:mm:ss format
311      * @param millisecond the milliseconds
312      * @return the new Calendar instance.
313      */
314     protected static Calendar createTime(TimeZone zone, int time, int millisecond) {
315         Calendar calendar = zone == null ? Calendar.getInstance()
316                                          : Calendar.getInstance(zone);
317         int hour = ((time / 10000) * 10000);
318         int min  = ((time / 100) * 100) - hour;
319         int sec  = time - (hour + min);
320         calendar.set(Calendar.YEAR,  1970);
321         calendar.set(Calendar.MONTH, 0);
322         calendar.set(Calendar.DATE,  1);
323         calendar.set(Calendar.HOUR_OF_DAY,  (hour / 10000));
324         calendar.set(Calendar.MINUTE, (min / 100));
325         calendar.set(Calendar.SECOND,  sec);
326         calendar.set(Calendar.MILLISECOND,  millisecond);
327         return calendar;
328     }
329 
330     /**
331      * Create a date instance for a specified time zone, date and time.
332      * 
333      * @param zone The time zone
334      * @param time the time in HH:mm:ss format
335      * @param millisecond the milliseconds
336      * @return the new Date instance.
337      */
338     protected static Date createDate(TimeZone zone, int time, int millisecond) {
339         Calendar calendar = createTime(zone, time, millisecond);
340         return calendar.getTime();
341     }
342 }