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: 909006 $ $Date: 2010-02-11 09:46:51 -0500 (Thu, 11 Feb 2010) $
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     protected void setUp() throws Exception {
110         super.setUp();
111     }
112 
113     /**
114      * Tear down
115      * @throws Exception
116      */
117     protected void tearDown() throws Exception {
118         super.tearDown();
119         validator = null;
120     }
121 
122     /**
123      * Test Valid Dates with "pattern" validation
124      */
125     public void testPatternValid() {
126         for (int i = 0; i < patternValid.length; i++) {
127             String text = i + " value=[" +patternValid[i]+"] failed ";
128             Object date = validator.parse(patternValid[i], "yy-MM-dd", null, null);
129             assertNotNull("validateObj() " + text + date,  date);
130             assertTrue("isValid() " + text,  validator.isValid(patternValid[i], "yy-MM-dd"));
131             if (date instanceof Calendar) {
132                 date = ((Calendar)date).getTime();
133             }
134             assertEquals("compare " + text, patternExpect[i], date);
135         }
136     }
137 
138     /**
139      * Test Invalid Dates with "pattern" validation
140      */
141     public void testPatternInvalid() {
142         for (int i = 0; i < patternInvalid.length; i++) {
143             String text = i + " value=[" +patternInvalid[i]+"] passed ";
144             Object date = validator.parse(patternInvalid[i], "yy-MM-dd", null, null);
145             assertNull("validateObj() " + text + date,  date);
146             assertFalse("isValid() " + text,  validator.isValid(patternInvalid[i], "yy-MM-dd"));
147         }
148     }
149 
150     /**
151      * Test Valid Dates with "locale" validation
152      */
153     public void testLocaleValid() {
154         for (int i = 0; i < localeValid.length; i++) {
155             String text = i + " value=[" +localeValid[i]+"] failed ";
156             Object date = validator.parse(localeValid[i], null, Locale.US, null);
157             assertNotNull("validateObj() " + text + date,  date);
158             assertTrue("isValid() " + text,  validator.isValid(localeValid[i], Locale.US));
159             if (date instanceof Calendar) {
160                 date = ((Calendar)date).getTime();
161             }
162             assertEquals("compare " + text, patternExpect[i], date);
163         }
164     }
165 
166     /**
167      * Test Invalid Dates with "locale" validation
168      */
169     public void testLocaleInvalid() {
170         for (int i = 0; i < localeInvalid.length; i++) {
171             String text = i + " value=[" +localeInvalid[i]+"] passed ";
172             Object date = validator.parse(localeInvalid[i], null, Locale.US, null);
173             assertNull("validateObj() " + text + date,  date);
174             assertFalse("isValid() " + text,  validator.isValid(localeInvalid[i], Locale.US));
175         }
176     }
177 
178     /**
179      * Test Invalid Dates with "locale" validation
180      */
181     public void testFormat() {
182 
183         // Create a Date or Calendar
184         Object test = validator.parse("2005-11-28", "yyyy-MM-dd", null, null);
185         assertNotNull("Test Date ", test);
186         assertEquals("Format pattern", "28.11.05", validator.format(test, "dd.MM.yy"));
187         assertEquals("Format locale",  "11/28/05", validator.format(test, Locale.US));
188     }
189 
190     /**
191      * Test validator serialization.
192      */
193     public void testSerialization() {
194         // Serialize the check digit routine
195         ByteArrayOutputStream baos = new ByteArrayOutputStream();
196         try {
197             ObjectOutputStream oos = new ObjectOutputStream(baos);
198             oos.writeObject(validator);
199             oos.flush();
200             oos.close();
201         } catch (Exception e) {
202             fail(validator.getClass().getName() + " error during serialization: " + e);
203         }
204 
205         // Deserialize the test object
206         Object result = null;
207         try {
208             ByteArrayInputStream bais =
209                 new ByteArrayInputStream(baos.toByteArray());
210             ObjectInputStream ois = new ObjectInputStream(bais);
211             result = ois.readObject();
212             bais.close();
213         } catch (Exception e) {
214             fail(validator.getClass().getName() + " error during deserialization: " + e);
215         }
216         assertNotNull(result);
217     }
218 
219     /**
220      * Create a calendar instance for a specified time zone, date and time.
221      * 
222      * @param zone The time zone
223      * @param date The date in yyyyMMdd format
224      * @param time the time in HH:mm:ss format
225      * @return the new Calendar instance.
226      */
227     protected static Calendar createCalendar(TimeZone zone, int date, int time) {
228         Calendar calendar = zone == null ? Calendar.getInstance()
229                                          : Calendar.getInstance(zone);
230         int year = ((date / 10000) * 10000);
231         int mth  = ((date / 100) * 100) - year;
232         int day = date - (year + mth);
233         int hour = ((time / 10000) * 10000);
234         int min  = ((time / 100) * 100) - hour;
235         int sec  = time - (hour + min);
236         calendar.set(Calendar.YEAR,  (year / 10000));
237         calendar.set(Calendar.MONTH, ((mth / 100) - 1));
238         calendar.set(Calendar.DATE,  day);
239         calendar.set(Calendar.HOUR_OF_DAY,  (hour / 10000));
240         calendar.set(Calendar.MINUTE, (min / 100));
241         calendar.set(Calendar.SECOND,  sec);
242         calendar.set(Calendar.MILLISECOND,  0);
243         return calendar;
244     }
245 
246     /**
247      * Create a date instance for a specified time zone, date and time.
248      * 
249      * @param zone The time zone
250      * @param date The date in yyyyMMdd format
251      * @param time the time in HH:mm:ss format
252      * @return the new Date instance.
253      */
254     protected static Date createDate(TimeZone zone, int date, int time) {
255         Calendar calendar = createCalendar(zone, date, time);
256         return calendar.getTime();
257     }
258 
259 }