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.io.ByteArrayInputStream;
22  import java.io.ByteArrayOutputStream;
23  import java.io.ObjectInputStream;
24  import java.io.ObjectOutputStream;
25  import java.util.Date;
26  import java.util.Calendar;
27  import java.util.Locale;
28  import java.util.TimeZone;
29  
30  /**
31   * Base Calendar Test Case.
32   * 
33   * @version $Revision$
34   */
35  public abstract class AbstractCalendarValidatorTest extends TestCase {
36  
37      protected AbstractCalendarValidator validator;
38  
39      protected static final TimeZone GMT = TimeZone.getTimeZone("GMT"); // 0 offset
40      protected static final TimeZone EST = TimeZone.getTimeZone("EST"); // - 5 hours
41      protected static final TimeZone EET = TimeZone.getTimeZone("EET"); // + 2 hours
42      protected static final TimeZone UTC = TimeZone.getTimeZone("UTC"); // + 2 hours
43  
44      protected String[] patternValid = new String[] {
45                         "2005-01-01" 
46                        ,"2005-12-31"
47                        ,"2004-02-29"    // valid leap
48                        ,"2005-04-30" 
49                        ,"05-12-31"
50                        ,"2005-1-1"
51                        ,"05-1-1"};
52      protected String[] localeValid = new String[] {
53                         "01/01/2005" 
54                        ,"12/31/2005"
55                        ,"02/29/2004"    // valid leap
56                        ,"04/30/2005" 
57                        ,"12/31/05"
58                        ,"1/1/2005"
59                        ,"1/1/05"};
60      protected Date[] patternExpect = new Date[] {
61                        createDate(null, 20050101, 0)
62                       ,createDate(null, 20051231, 0)
63                       ,createDate(null, 20040229, 0)
64                       ,createDate(null, 20050430, 0)
65                       ,createDate(null, 20051231, 0)
66                       ,createDate(null, 20050101, 0)
67                       ,createDate(null, 20050101, 0)};
68      protected String[] patternInvalid = new String[] {
69                           "2005-00-01"  // zero month
70                          ,"2005-01-00"  // zero day 
71                          ,"2005-13-03"  // month invalid
72                          ,"2005-04-31"  // invalid day 
73                          ,"2005-03-32"  // invalid day 
74                          ,"2005-02-29"  // invalid leap
75                          ,"200X-01-01"  // invalid char
76                          ,"2005-0X-01"  // invalid char
77                          ,"2005-01-0X"  // invalid char
78                          ,"01/01/2005"  // invalid pattern
79                          ,"2005-01"     // invalid pattern
80                          ,"2005--01"    // invalid pattern
81                          ,"2005-01-"};  // invalid pattern
82      protected String[] localeInvalid = new String[] {
83                           "01/00/2005"  // zero month
84                          ,"00/01/2005"  // zero day 
85                          ,"13/01/2005"  // month invalid
86                          ,"04/31/2005"  // invalid day 
87                          ,"03/32/2005"  // invalid day 
88                          ,"02/29/2005"  // invalid leap
89                          ,"01/01/200X"  // invalid char
90                          ,"01/0X/2005"  // invalid char
91                          ,"0X/01/2005"  // invalid char
92                          ,"01-01-2005"  // invalid pattern
93                          ,"01/2005"     // invalid pattern
94         // --------      ,"/01/2005"    ---- passes on some JDK
95                          ,"01//2005"};  // invalid pattern
96  
97      /**
98       * Constructor
99       * @param name test name
100      */
101     public AbstractCalendarValidatorTest(String name) {
102         super(name);
103     }
104 
105     /**
106      * Set Up.
107      * @throws Exception
108      */
109     @Override
110     protected void setUp() throws Exception {
111         super.setUp();
112     }
113 
114     /**
115      * Tear down
116      * @throws Exception
117      */
118     @Override
119     protected void tearDown() throws Exception {
120         super.tearDown();
121         validator = null;
122     }
123 
124     /**
125      * Test Valid Dates with "pattern" validation
126      */
127     public void testPatternValid() {
128         for (int i = 0; i < patternValid.length; i++) {
129             String text = i + " value=[" +patternValid[i]+"] failed ";
130             Object date = validator.parse(patternValid[i], "yy-MM-dd", null, null);
131             assertNotNull("validateObj() " + text + date,  date);
132             assertTrue("isValid() " + text,  validator.isValid(patternValid[i], "yy-MM-dd"));
133             if (date instanceof Calendar) {
134                 date = ((Calendar)date).getTime();
135             }
136             assertEquals("compare " + text, patternExpect[i], date);
137         }
138     }
139 
140     /**
141      * Test Invalid Dates with "pattern" validation
142      */
143     public void testPatternInvalid() {
144         for (int i = 0; i < patternInvalid.length; i++) {
145             String text = i + " value=[" +patternInvalid[i]+"] passed ";
146             Object date = validator.parse(patternInvalid[i], "yy-MM-dd", null, null);
147             assertNull("validateObj() " + text + date,  date);
148             assertFalse("isValid() " + text,  validator.isValid(patternInvalid[i], "yy-MM-dd"));
149         }
150     }
151 
152     /**
153      * Test Valid Dates with "locale" validation
154      */
155     public void testLocaleValid() {
156         for (int i = 0; i < localeValid.length; i++) {
157             String text = i + " value=[" +localeValid[i]+"] failed ";
158             Object date = validator.parse(localeValid[i], null, Locale.US, null);
159             assertNotNull("validateObj() " + text + date,  date);
160             assertTrue("isValid() " + text,  validator.isValid(localeValid[i], Locale.US));
161             if (date instanceof Calendar) {
162                 date = ((Calendar)date).getTime();
163             }
164             assertEquals("compare " + text, patternExpect[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.parse(localeInvalid[i], null, Locale.US, null);
175             assertNull("validateObj() " + text + date,  date);
176             assertFalse("isValid() " + text,  validator.isValid(localeInvalid[i], Locale.US));
177         }
178     }
179 
180     /**
181      * Test Invalid Dates with "locale" validation
182      */
183     public void testFormat() {
184 
185         // Create a Date or Calendar
186         Object test = validator.parse("2005-11-28", "yyyy-MM-dd", null, null);
187         assertNotNull("Test Date ", test);
188         assertEquals("Format pattern", "28.11.05", validator.format(test, "dd.MM.yy"));
189         assertEquals("Format locale",  "11/28/05", validator.format(test, Locale.US));
190     }
191 
192     /**
193      * Test validator serialization.
194      */
195     public void testSerialization() {
196         // Serialize the check digit routine
197         ByteArrayOutputStream baos = new ByteArrayOutputStream();
198         try {
199             ObjectOutputStream oos = new ObjectOutputStream(baos);
200             oos.writeObject(validator);
201             oos.flush();
202             oos.close();
203         } catch (Exception e) {
204             fail(validator.getClass().getName() + " error during serialization: " + e);
205         }
206 
207         // Deserialize the test object
208         Object result = null;
209         try {
210             ByteArrayInputStream bais =
211                 new ByteArrayInputStream(baos.toByteArray());
212             ObjectInputStream ois = new ObjectInputStream(bais);
213             result = ois.readObject();
214             bais.close();
215         } catch (Exception e) {
216             fail(validator.getClass().getName() + " error during deserialization: " + e);
217         }
218         assertNotNull(result);
219     }
220 
221     /**
222      * Create a calendar instance for a specified time zone, date and time.
223      * 
224      * @param zone The time zone
225      * @param date The date in yyyyMMdd format
226      * @param time the time in HH:mm:ss format
227      * @return the new Calendar instance.
228      */
229     protected static Calendar createCalendar(TimeZone zone, int date, int time) {
230         Calendar calendar = zone == null ? Calendar.getInstance()
231                                          : Calendar.getInstance(zone);
232         int year = ((date / 10000) * 10000);
233         int mth  = ((date / 100) * 100) - year;
234         int day = date - (year + mth);
235         int hour = ((time / 10000) * 10000);
236         int min  = ((time / 100) * 100) - hour;
237         int sec  = time - (hour + min);
238         calendar.set(Calendar.YEAR,  (year / 10000));
239         calendar.set(Calendar.MONTH, ((mth / 100) - 1));
240         calendar.set(Calendar.DATE,  day);
241         calendar.set(Calendar.HOUR_OF_DAY,  (hour / 10000));
242         calendar.set(Calendar.MINUTE, (min / 100));
243         calendar.set(Calendar.SECOND,  sec);
244         calendar.set(Calendar.MILLISECOND,  0);
245         return calendar;
246     }
247 
248     /**
249      * Create a date instance for a specified time zone, date and time.
250      * 
251      * @param zone The time zone
252      * @param date The date in yyyyMMdd format
253      * @param time the time in HH:mm:ss format
254      * @return the new Date instance.
255      */
256     protected static Date createDate(TimeZone zone, int date, int time) {
257         Calendar calendar = createCalendar(zone, date, time);
258         return calendar.getTime();
259     }
260 
261 }