Coverage Report - org.apache.commons.validator.routines.AbstractCalendarValidator
 
Classes in this File Line Coverage Branch Coverage Complexity
AbstractCalendarValidator
99%
102/103
91%
82/90
4.588
 
 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 java.text.DateFormatSymbols;
 20  
 import java.text.Format;
 21  
 import java.text.DateFormat;
 22  
 import java.text.SimpleDateFormat;
 23  
 import java.util.Calendar;
 24  
 import java.util.Locale;
 25  
 import java.util.TimeZone;
 26  
 
 27  
 /**
 28  
  * <p>Abstract class for Date/Time/Calendar validation.</p>
 29  
  *
 30  
  * <p>This is a <i>base</i> class for building Date / Time
 31  
  *    Validators using format parsing.</p>
 32  
  *
 33  
  * @version $Revision: 1739356 $
 34  
  * @since Validator 1.3.0
 35  
  */
 36  
 public abstract class AbstractCalendarValidator extends AbstractFormatValidator {
 37  
 
 38  
     private static final long serialVersionUID = -1410008585975827379L;
 39  
 
 40  
     private final int dateStyle;
 41  
 
 42  
     private final int timeStyle;
 43  
 
 44  
     /**
 45  
      * Construct an instance with the specified <i>strict</i>,
 46  
      * <i>time</i> and <i>date</i> style parameters.
 47  
      *
 48  
      * @param strict <code>true</code> if strict
 49  
      *        <code>Format</code> parsing should be used.
 50  
      * @param dateStyle the date style to use for Locale validation.
 51  
      * @param timeStyle the time style to use for Locale validation.
 52  
      */
 53  
     public AbstractCalendarValidator(boolean strict, int dateStyle, int timeStyle) {
 54  29
         super(strict);
 55  29
         this.dateStyle = dateStyle;
 56  29
         this.timeStyle = timeStyle;
 57  29
     }
 58  
 
 59  
     /**
 60  
      * <p>Validate using the specified <code>Locale</code>.
 61  
      *
 62  
      * @param value The value validation is being performed on.
 63  
      * @param pattern The pattern used to format the value.
 64  
      * @param locale The locale to use for the Format, defaults to the default
 65  
      * @return <code>true</code> if the value is valid.
 66  
      */
 67  
     @Override
 68  
     public boolean isValid(String value, String pattern, Locale locale) {
 69  134
         Object parsedValue = parse(value, pattern, locale, (TimeZone)null);
 70  134
         return (parsedValue == null ? false : true);
 71  
     }
 72  
 
 73  
     /**
 74  
      * <p>Format an object into a <code>String</code> using
 75  
      * the default Locale.</p>
 76  
      *
 77  
      * @param value The value validation is being performed on.
 78  
      * @param timeZone The Time Zone used to format the date,
 79  
      *  system default if null (unless value is a <code>Calendar</code>.
 80  
      * @return The value formatted as a <code>String</code>.
 81  
      */
 82  
     public String format(Object value, TimeZone timeZone) {
 83  1
         return format(value, (String)null, (Locale)null, timeZone);
 84  
     }
 85  
 
 86  
     /**
 87  
      * <p>Format an object into a <code>String</code> using
 88  
      * the specified pattern.</p>
 89  
      *
 90  
      * @param value The value validation is being performed on.
 91  
      * @param pattern The pattern used to format the value.
 92  
      * @param timeZone The Time Zone used to format the date,
 93  
      *  system default if null (unless value is a <code>Calendar</code>.
 94  
      * @return The value formatted as a <code>String</code>.
 95  
      */
 96  
     public String format(Object value, String pattern, TimeZone timeZone) {
 97  2
         return format(value, pattern, (Locale)null, timeZone);
 98  
     }
 99  
 
 100  
     /**
 101  
      * <p>Format an object into a <code>String</code> using
 102  
      * the specified Locale.</p>
 103  
      *
 104  
      * @param value The value validation is being performed on.
 105  
      * @param locale The locale to use for the Format.
 106  
      * @param timeZone The Time Zone used to format the date,
 107  
      *  system default if null (unless value is a <code>Calendar</code>.
 108  
      * @return The value formatted as a <code>String</code>.
 109  
      */
 110  
     public String format(Object value, Locale locale, TimeZone timeZone) {
 111  1
         return format(value, (String)null, locale, timeZone);
 112  
     }
 113  
 
 114  
     /**
 115  
      * <p>Format an object using the specified pattern and/or
 116  
      *    <code>Locale</code>.
 117  
      *
 118  
      * @param value The value validation is being performed on.
 119  
      * @param pattern The pattern used to format the value.
 120  
      * @param locale The locale to use for the Format.
 121  
      * @return The value formatted as a <code>String</code>.
 122  
      */
 123  
     @Override
 124  
     public String format(Object value, String pattern, Locale locale) {
 125  11
         return format(value, pattern, locale, (TimeZone)null);
 126  
     }
 127  
 
 128  
     /**
 129  
      * <p>Format an object using the specified pattern and/or
 130  
      *    <code>Locale</code>.
 131  
      *
 132  
      * @param value The value validation is being performed on.
 133  
      * @param pattern The pattern used to format the value.
 134  
      * @param locale The locale to use for the Format.
 135  
      * @param timeZone The Time Zone used to format the date,
 136  
      *  system default if null (unless value is a <code>Calendar</code>.
 137  
      * @return The value formatted as a <code>String</code>.
 138  
      */
 139  
     public String format(Object value, String pattern, Locale locale, TimeZone timeZone) {
 140  16
         DateFormat formatter = (DateFormat)getFormat(pattern, locale);
 141  16
         if (timeZone != null) {
 142  5
             formatter.setTimeZone(timeZone);
 143  11
         } else if (value instanceof Calendar) {
 144  8
             formatter.setTimeZone(((Calendar)value).getTimeZone());
 145  
         }
 146  16
         return format(value, formatter);
 147  
     }
 148  
 
 149  
     /**
 150  
      * <p>Format a value with the specified <code>DateFormat</code>.</p>
 151  
      *
 152  
      * @param value The value to be formatted.
 153  
      * @param formatter The Format to use.
 154  
      * @return The formatted value.
 155  
      */
 156  
     @Override
 157  
     protected String format(Object value, Format formatter) {
 158  16
         if (value == null) {
 159  1
             return null;
 160  15
         } else if (value instanceof Calendar) {
 161  13
             value = ((Calendar)value).getTime();
 162  
         }
 163  15
         return formatter.format(value);
 164  
     }
 165  
 
 166  
     /**
 167  
      * <p>Checks if the value is valid against a specified pattern.</p>
 168  
      *
 169  
      * @param value The value validation is being performed on.
 170  
      * @param pattern The pattern used to validate the value against, or the
 171  
      *        default for the <code>Locale</code> if <code>null</code>.
 172  
      * @param locale The locale to use for the date format, system default if null.
 173  
      * @param timeZone The Time Zone used to parse the date, system default if null.
 174  
      * @return The parsed value if valid or <code>null</code> if invalid.
 175  
      */
 176  
     protected Object parse(String value, String pattern, Locale locale, TimeZone timeZone) {
 177  
 
 178  282
         value = (value == null ? null : value.trim());
 179  282
         if (value == null || value.length() == 0) {
 180  0
             return null;
 181  
         }
 182  282
         DateFormat formatter = (DateFormat)getFormat(pattern, locale);
 183  282
         if (timeZone != null) {
 184  12
             formatter.setTimeZone(timeZone);
 185  
         }
 186  282
         return parse(value, formatter);
 187  
 
 188  
     }
 189  
 
 190  
     /**
 191  
      * <p>Process the parsed value, performing any further validation
 192  
      *    and type conversion required.</p>
 193  
      *
 194  
      * @param value The parsed object created.
 195  
      * @param formatter The Format used to parse the value with.
 196  
      * @return The parsed value converted to the appropriate type
 197  
      *         if valid or <code>null</code> if invalid.
 198  
      */
 199  
     @Override
 200  
     protected abstract Object processParsedValue(Object value, Format formatter);
 201  
 
 202  
     /**
 203  
      * <p>Returns a <code>DateFormat</code> for the specified <i>pattern</i>
 204  
      *    and/or <code>Locale</code>.</p>
 205  
      *
 206  
      * @param pattern The pattern used to validate the value against or
 207  
      *        <code>null</code> to use the default for the <code>Locale</code>.
 208  
      * @param locale The locale to use for the currency format, system default if null.
 209  
      * @return The <code>DateFormat</code> to created.
 210  
      */
 211  
     @Override
 212  
     protected Format getFormat(String pattern, Locale locale) {
 213  298
         DateFormat formatter = null;
 214  298
         boolean usePattern = (pattern != null && pattern.length() > 0);
 215  298
         if (!usePattern) {
 216  145
             formatter = (DateFormat)getFormat(locale);
 217  153
         } else if (locale == null) {
 218  139
             formatter = new SimpleDateFormat(pattern);
 219  
         } else {
 220  14
             DateFormatSymbols symbols = new DateFormatSymbols(locale);
 221  14
             formatter = new SimpleDateFormat(pattern, symbols);
 222  
         }
 223  298
         formatter.setLenient(false);
 224  298
         return formatter;
 225  
     }
 226  
 
 227  
     /**
 228  
      * <p>Returns a <code>DateFormat</code> for the specified Locale.</p>
 229  
      *
 230  
      * @param locale The locale a <code>DateFormat</code> is required for,
 231  
      *        system default if null.
 232  
      * @return The <code>DateFormat</code> to created.
 233  
      */
 234  
     protected Format getFormat(Locale locale) {
 235  
 
 236  145
         DateFormat formatter = null;
 237  145
         if (dateStyle >= 0 && timeStyle >= 0) {
 238  2
             if (locale == null) {
 239  1
                 formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle);
 240  
             } else {
 241  1
                 formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale);
 242  
             }
 243  143
         } else if (timeStyle >= 0) {
 244  41
             if (locale == null) {
 245  3
                 formatter = DateFormat.getTimeInstance(timeStyle);
 246  
             } else {
 247  38
                 formatter = DateFormat.getTimeInstance(timeStyle, locale);
 248  
             }
 249  
         } else {
 250  102
             int useDateStyle = dateStyle >= 0 ? dateStyle : DateFormat.SHORT;
 251  102
             if (locale == null) {
 252  13
                 formatter = DateFormat.getDateInstance(useDateStyle);
 253  
             } else {
 254  89
                 formatter = DateFormat.getDateInstance(useDateStyle, locale);
 255  
             }
 256  
         }
 257  145
         formatter.setLenient(false);
 258  145
         return formatter;
 259  
 
 260  
     }
 261  
 
 262  
     /**
 263  
      * <p>Compares a calendar value to another, indicating whether it is
 264  
      *    equal, less then or more than at a specified level.</p>
 265  
      *
 266  
      * @param value The Calendar value.
 267  
      * @param compare The <code>Calendar</code> to check the value against.
 268  
      * @param field The field <i>level</i> to compare to - e.g. specifying
 269  
      *        <code>Calendar.MONTH</code> will compare the year and month
 270  
      *        portions of the calendar.
 271  
      * @return Zero if the first value is equal to the second, -1
 272  
      *         if it is less than the second or +1 if it is greater than the second.
 273  
      */
 274  
     protected int compare(Calendar value, Calendar compare, int field) {
 275  
 
 276  44
         int result = 0;
 277  
 
 278  
         // Compare Year
 279  44
         result = calculateCompareResult(value, compare, Calendar.YEAR);
 280  44
         if (result != 0 || field == Calendar.YEAR) {
 281  6
             return result;
 282  
         }
 283  
 
 284  
         // Compare Week of Year
 285  38
         if (field == Calendar.WEEK_OF_YEAR) {
 286  10
             return calculateCompareResult(value, compare, Calendar.WEEK_OF_YEAR);
 287  
         }
 288  
 
 289  
         // Compare Day of the Year
 290  28
         if (field == Calendar.DAY_OF_YEAR) {
 291  1
             return calculateCompareResult(value, compare, Calendar.DAY_OF_YEAR);
 292  
         }
 293  
 
 294  
         // Compare Month
 295  27
         result = calculateCompareResult(value, compare, Calendar.MONTH);
 296  27
         if (result != 0 || field == Calendar.MONTH) {
 297  10
             return result;
 298  
         }
 299  
 
 300  
         // Compare Week of Month
 301  17
         if (field == Calendar.WEEK_OF_MONTH) {
 302  1
             return calculateCompareResult(value, compare, Calendar.WEEK_OF_MONTH);
 303  
         }
 304  
 
 305  
         // Compare Date
 306  16
         result = calculateCompareResult(value, compare, Calendar.DATE);
 307  16
         if (result != 0 || (field == Calendar.DATE ||
 308  
                           field == Calendar.DAY_OF_WEEK ||
 309  
                           field == Calendar.DAY_OF_WEEK_IN_MONTH)) {
 310  10
             return result;
 311  
         }
 312  
 
 313  
         // Compare Time fields
 314  6
         return compareTime(value, compare, field);
 315  
 
 316  
     }
 317  
 
 318  
     /**
 319  
      * <p>Compares a calendar time value to another, indicating whether it is
 320  
      *    equal, less then or more than at a specified level.</p>
 321  
      *
 322  
      * @param value The Calendar value.
 323  
      * @param compare The <code>Calendar</code> to check the value against.
 324  
      * @param field The field <i>level</i> to compare to - e.g. specifying
 325  
      *        <code>Calendar.MINUTE</code> will compare the hours and minutes
 326  
      *        portions of the calendar.
 327  
      * @return Zero if the first value is equal to the second, -1
 328  
      *         if it is less than the second or +1 if it is greater than the second.
 329  
      */
 330  
     protected int compareTime(Calendar value, Calendar compare, int field) {
 331  
 
 332  24
         int result = 0;
 333  
 
 334  
         // Compare Hour
 335  24
         result = calculateCompareResult(value, compare, Calendar.HOUR_OF_DAY);
 336  24
         if (result != 0 || (field == Calendar.HOUR || field == Calendar.HOUR_OF_DAY)) {
 337  7
             return result;
 338  
         }
 339  
 
 340  
         // Compare Minute
 341  17
         result = calculateCompareResult(value, compare, Calendar.MINUTE);
 342  17
         if (result != 0 || field == Calendar.MINUTE) {
 343  7
             return result;
 344  
         }
 345  
 
 346  
         // Compare Second
 347  10
         result = calculateCompareResult(value, compare, Calendar.SECOND);
 348  10
         if (result != 0 || field == Calendar.SECOND) {
 349  6
             return result;
 350  
         }
 351  
 
 352  
         // Compare Milliseconds
 353  4
         if (field == Calendar.MILLISECOND) {
 354  3
             return calculateCompareResult(value, compare, Calendar.MILLISECOND);
 355  
         }
 356  
 
 357  1
         throw new IllegalArgumentException("Invalid field: " + field);
 358  
 
 359  
     }
 360  
 
 361  
     /**
 362  
      * <p>Compares a calendar's quarter value to another, indicating whether it is
 363  
      *    equal, less then or more than the specified quarter.</p>
 364  
      *
 365  
      * @param value The Calendar value.
 366  
      * @param compare The <code>Calendar</code> to check the value against.
 367  
      * @param monthOfFirstQuarter The  month that the first quarter starts.
 368  
      * @return Zero if the first quarter is equal to the second, -1
 369  
      *         if it is less than the second or +1 if it is greater than the second.
 370  
      */
 371  
     protected int compareQuarters(Calendar value, Calendar compare, int monthOfFirstQuarter) {
 372  25
         int valueQuarter   = calculateQuarter(value, monthOfFirstQuarter);
 373  25
         int compareQuarter = calculateQuarter(compare, monthOfFirstQuarter);
 374  25
         if (valueQuarter < compareQuarter) {
 375  6
             return -1;
 376  19
         } else if (valueQuarter > compareQuarter) {
 377  9
             return 1;
 378  
         } else {
 379  10
             return 0;
 380  
         }
 381  
     }
 382  
 
 383  
     /**
 384  
      * <p>Calculate the quarter for the specified Calendar.</p>
 385  
      *
 386  
      * @param calendar The Calendar value.
 387  
      * @param monthOfFirstQuarter The  month that the first quarter starts.
 388  
      * @return The calculated quarter.
 389  
      */
 390  
     private int calculateQuarter(Calendar calendar, int monthOfFirstQuarter) {
 391  
         // Add Year
 392  50
         int year = calendar.get(Calendar.YEAR);
 393  
 
 394  50
         int month = (calendar.get(Calendar.MONTH) + 1);
 395  50
         int relativeMonth = (month >= monthOfFirstQuarter)
 396  
                           ? (month - monthOfFirstQuarter)
 397  
                           : (month + (12 - monthOfFirstQuarter)); // CHECKSTYLE IGNORE MagicNumber
 398  50
         int quarter = ((relativeMonth / 3) + 1); // CHECKSTYLE IGNORE MagicNumber
 399  
         // adjust the year if the quarter doesn't start in January
 400  50
         if (month < monthOfFirstQuarter) {
 401  1
             --year;
 402  
         }
 403  50
         return (year * 10) + quarter; // CHECKSTYLE IGNORE MagicNumber
 404  
     }
 405  
 
 406  
     /**
 407  
      * <p>Compares the field from two calendars indicating whether the field for the
 408  
      *    first calendar is equal to, less than or greater than the field from the
 409  
      *    second calendar.
 410  
      *
 411  
      * @param value The Calendar value.
 412  
      * @param compare The <code>Calendar</code> to check the value against.
 413  
      * @param field The field to compare for the calendars.
 414  
      * @return Zero if the first calendar's field is equal to the seconds, -1
 415  
      *         if it is less than the seconds or +1 if it is greater than the seconds.
 416  
      */
 417  
     private int calculateCompareResult(Calendar value, Calendar compare, int field) {
 418  153
         int difference = value.get(field) - compare.get(field);
 419  153
         if (difference < 0) {
 420  13
             return -1;
 421  140
         } else if (difference > 0) {
 422  17
             return 1;
 423  
         } else {
 424  123
             return 0;
 425  
         }
 426  
     }
 427  
 }