commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From bay...@apache.org
Subject cvs commit: jakarta-commons/lang/src/test/org/apache/commons/lang CalendarUtilsTest.java LangTestSuite.java
Date Mon, 16 Dec 2002 21:55:20 GMT
bayard      2002/12/16 13:55:20

  Modified:    lang/src/test/org/apache/commons/lang LangTestSuite.java
  Added:       lang/src/java/org/apache/commons/lang CalendarUtils.java
               lang/src/test/org/apache/commons/lang CalendarUtilsTest.java
  Log:
  CalendarUtils from the sandbox, for merger with DateUtils. Or parallel living.
  
  Revision  Changes    Path
  1.1                  jakarta-commons/lang/src/java/org/apache/commons/lang/CalendarUtils.java
  
  Index: CalendarUtils.java
  ===================================================================
  package org.apache.commons.lang;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2002 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowlegement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Commons", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import java.text.*;
  import java.util.*;
  
  /**
   * A suite of utilities surrounding the use of the Calendar and Date object.
   *
   * @author <a href="mailto:sergek@lokitech.com">Serge Knystautas</a>
   */
  public class CalendarUtils {
  
      /**
       * This is half a month, so this represents whether a date is in the top
       * or bottom half of the month.
       */
      public final static int SEMI_MONTH = 1001;
  
      private static final int[][] fields = {
              {Calendar.MILLISECOND},
              {Calendar.SECOND},
              {Calendar.MINUTE},
              {Calendar.HOUR_OF_DAY, Calendar.HOUR},
              {Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM /* Calendar.DAY_OF_YEAR,
Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */},
              {Calendar.MONTH, CalendarUtils.SEMI_MONTH},
              {Calendar.YEAR},
              {Calendar.ERA}};
  
      private static DateFormat[] dateFormats = {
          //3/31/92 10:00:07 PST
          new SimpleDateFormat("M/dd/yy h:mm:ss z"),
          //January 23, 1987 10:05pm
          new SimpleDateFormat("MMM d, yyyy h:mm a"),
          //22:00 GMT
          new SimpleDateFormat("h:mm z")};
  
      /**
       * A week range, starting on Sunday.
       */
      public final static int RANGE_WEEK_SUNDAY = 1;
  
      /**
       * A week range, starting on Monday.
       */
      public final static int RANGE_WEEK_MONDAY = 2;
  
      /**
       * A week range, starting on the day focused.
       */
      public final static int RANGE_WEEK_RELATIVE = 3;
  
      /**
       * A week range, centered around the day focused.
       */
      public final static int RANGE_WEEK_CENTER = 4;
  
      /**
       * A month range, the week starting on Sunday.
       */
      public final static int RANGE_MONTH_SUNDAY = 5;
  
      /**
       * A month range, the week starting on Monday.
       */
      public final static int RANGE_MONTH_MONDAY = 6;
  
      /**
       * See the other round method.  Works with a Date object.
       */
      public static Date round(Date val, int field) {
          GregorianCalendar gval = new GregorianCalendar();
          gval.setTime(val);
          modify(gval, field, true);
          return gval.getTime();
      }
  
      /**
       * Round this date, leaving the field specified as the most significant
       * field.  For example, if you had the datetime of 28 Mar 2002
       * 13:45:01.231, if this was passed with HOUR, it would return 28 Mar
       * 2002 14:00:00.000.  If this was passed with MONTH, it would return
       * 1 April 2002 0:00:00.000.
       */
      public static Calendar round(Calendar val, int field) {
          Calendar rounded = (Calendar) val.clone();
          modify(rounded, field, true);
          return rounded;
      }
  
      /**
       * See the other round method.  Works with an Object, trying to
       * use it as either a Date or Calendar.
       */
      public static Date round(Object val, int field) {
          if (val instanceof Date) {
              return round((Date) val, field);
          } else if (val instanceof Calendar) {
              return round((Calendar) val, field).getTime();
          } else {
              throw new ClassCastException("Could not round " + val);
          }
      }
  
      /**
       * See the other trunc method.  Works with a Date.
       */
      public static Date trunc(Date val, int field) {
          GregorianCalendar gval = new GregorianCalendar();
          gval.setTime(val);
          modify(gval, field, false);
          return gval.getTime();
      }
  
      /**
       * Truncate this date, leaving the field specified as the most significant
       * field.  For example, if you had the datetime of 28 Mar 2002
       * 13:45:01.231, if you passed with HOUR, it would return 28 Mar
       * 2002 13:00:00.000.  If this was passed with MONTH, it would return
       * 1 Mar 2002 0:00:00.000.
       */
      public static Calendar trunc(Calendar val, int field) {
          Calendar truncated = (Calendar) val.clone();
          modify(truncated, field, false);
          return truncated;
      }
  
      /**
       * See the other trunc method.  Works with an Object, trying to
       * use it as either a Date or Calendar.
       */
      public static Date trunc(Object val, int field) {
          if (val instanceof Date) {
              return trunc((Date) val, field);
          } else if (val instanceof Calendar) {
              return trunc((Calendar) val, field).getTime();
          } else {
              throw new ClassCastException("Could not trunc " + val);
          }
      }
  
      private static void modify(Calendar val, int field, boolean round) {
          boolean roundUp = false;
          for (int i = 0; i < fields.length; i++) {
              for (int j = 0; j < fields[i].length; j++) {
                  if (fields[i][j] == field) {
                      //This is our field... we stop looping
                      if (round && roundUp) {
                          if (field == CalendarUtils.SEMI_MONTH) {
                              //This is a special case that's hard to generalize
                              //If the date is 1, we round up to 16, otherwise
                              //  we subtract 15 days and add 1 month
                              if (val.get(Calendar.DATE) == 1) {
                                  val.add(Calendar.DATE, 15);
                              } else {
                                  val.add(Calendar.DATE, -15);
                                  val.add(Calendar.MONTH, 1);
                              }
                          } else {
                              //We need at add one to this field since the
                              //  last number causes us to round up
                              val.add(fields[i][0], 1);
                          }
                      }
                      return;
                  }
              }
              //We have various fields that are not easy roundings
              int offset = 0;
              boolean offsetSet = false;
              //These are special types of fields that require different rounding rules
              switch (field) {
                  case CalendarUtils.SEMI_MONTH:
                      if (fields[i][0] == Calendar.DATE) {
                          //If we're going to drop the DATE field's value,
                          //  we want to do this our own way.
                          //We need to subtrace 1 since the date has a minimum of 1
                          offset = val.get(Calendar.DATE) - 1;
                          //If we're above 15 days adjustment, that means we're in the
                          //  bottom half of the month and should stay accordingly.
                          if (offset >= 15) {
                              offset -= 15;
                          }
                          //Record whether we're in the top or bottom half of that range
                          roundUp = offset > 7;
                          offsetSet = true;
                      }
                      break;
                  case Calendar.AM_PM:
                      if (fields[i][0] == Calendar.HOUR) {
                          //If we're going to drop the HOUR field's value,
                          //  we want to do this our own way.
                          offset = val.get(Calendar.HOUR);
                          if (offset >= 12) {
                              offset -= 12;
                          }
                          roundUp = offset > 6;
                          offsetSet = true;
                      }
                      break;
              }
              if (!offsetSet) {
                  int min = val.getActualMinimum(fields[i][0]);
                  int max = val.getActualMaximum(fields[i][0]);
                  //Calculate the offset from the minimum allowed value
                  offset = val.get(fields[i][0]) - min;
                  //Set roundUp if this is more than half way between the minimum and maximum
                  roundUp = offset > ((max - min) / 2);
              }
              //We need to remove this field
              val.add(fields[i][0], -offset);
          }
          throw new RuntimeException("We do not support that field.");
  
      }
  
      /**
       * Parses strings the way that CVS supports it... very human readable
       */
      public static Calendar parse(String original) {
          return parse(original, Locale.getDefault());
      }
  
      /**
       * Parses strings the way that CVS supports it... very human readable
       */
      public static Calendar parse(String original, Locale locale) {
          //Get the symbol names
          DateFormatSymbols symbols = new DateFormatSymbols(locale);
  
          //Prep the string to parse
          String value = original.toLowerCase().trim();
  
          //Get the current date/time
          Calendar now = Calendar.getInstance();
          if (value.endsWith(" ago")) {
              //If this was a date that was "ago" the current time...
              //Strip out the ' ago' part
              value = value.substring(0, value.length() - 4);
  
              //Split the value and unit
              int start = value.indexOf(" ");
              if (start < 0) {
                  throw new RuntimeException("Could not find space in between value and unit");
              }
              String unit = value.substring(start + 1);
              value = value.substring(0, start);
              //We support "a week", so we need to parse the value as "a"
              int val = 0;
              if (value.equals("a") || value.equals("an")) {
                  val = 1;
              } else {
                  val = Integer.parseInt(value);
              }
  
              //Determine the unit
              if (unit.equals("milliseconds") || unit.equals("millisecond")) {
                  now.add(Calendar.MILLISECOND, -val);
              } else if (unit.equals("seconds") || unit.equals("second")) {
                  now.add(Calendar.SECOND, -val);
              } else if (unit.equals("minutes") || unit.equals("minute")) {
                  now.add(Calendar.MINUTE, -val);
              } else if (unit.equals("hours") || unit.equals("hour")) {
                  now.add(Calendar.HOUR, -val);
              } else if (unit.equals("days") || unit.equals("day")) {
                  now.add(Calendar.DATE, -val);
              } else if (unit.equals("weeks") || unit.equals("week")) {
                  now.add(Calendar.DATE, -val * 7);
              } else if (unit.equals("fortnights") || unit.equals("fortnight")) {
                  now.add(Calendar.DATE, -val * 14);
              } else if (unit.equals("months") || unit.equals("month")) {
                  now.add(Calendar.MONTH, -val);
              } else if (unit.equals("years") || unit.equals("year")) {
                  now.add(Calendar.YEAR, -val);
              } else {
                  throw new RuntimeException("We do not understand that many units ago");
              }
              return now;
          } else if (value.startsWith("last ")) {
              //If this was the last time a certain field was met
              //Strip out the 'last ' part
              value = value.substring(5);
              //Get the current date/time
              String[] strings = symbols.getWeekdays();
              for (int i = 0; i < strings.length; i++) {
                  if (value.equalsIgnoreCase(strings[i])) {
                      //How many days after Sunday
                      int daysAgo = now.get(Calendar.DAY_OF_WEEK) - i;
                      if (daysAgo <= 0) {
                          daysAgo += 7;
                      }
                      now.add(Calendar.DATE, -daysAgo);
                      return now;
                  }
              }
              strings = symbols.getMonths();
              for (int i = 0; i < strings.length; i++) {
                  if (value.equalsIgnoreCase(strings[i])) {
                      //How many days after January
                      int monthsAgo = now.get(Calendar.MONTH) - i;
                      if (monthsAgo <= 0) {
                          monthsAgo += 12;
                      }
                      now.add(Calendar.MONTH, -monthsAgo);
                      return now;
                  }
              }
              if (value.equals("week")) {
                  now.add(Calendar.DATE, -7);
                  return now;
              }
          } else if (value.equals("yesterday")) {
              now.add(Calendar.DATE, -1);
              return now;
          } else if (value.equals("tomorrow")) {
              now.add(Calendar.DATE, 1);
              return now;
          }
          //Try to parse the date a number of different ways
          for (int i = 0; i < dateFormats.length; i++) {
              try {
                  Date datetime = dateFormats[i].parse(original);
                  Calendar cal = Calendar.getInstance();
                  cal.setTime(datetime);
                  return cal;
              } catch (ParseException pe) {
                  //we ignore this and just keep trying
              }
          }
  
          throw new RuntimeException("Unable to parse '" + original + "'.");
      }
  
      /**
       * This constructs an Iterator that will start and stop over a date
       * range based on the focused date and the range style.  For instance,
       * passing Thursday, July 4, 2002 and a RANGE_MONTH_SUNDAY will return
       * an Iterator that starts with Sunday, June 30, 2002 and ends with
       * Saturday, August 3, 2002.
       */
      public static Iterator getCalendarIterator(Calendar focus, int rangeStyle) {
          Calendar start = null;
          Calendar end = null;
          int startCutoff = Calendar.SUNDAY;
          int endCutoff = Calendar.SATURDAY;
          switch (rangeStyle) {
              case RANGE_MONTH_SUNDAY:
              case RANGE_MONTH_MONDAY:
                  //Set start to the first of the month
                  start = trunc(focus, Calendar.MONTH);
                  //Set end to the last of the month
                  end = (Calendar) start.clone();
                  end.add(Calendar.MONTH, 1);
                  end.add(Calendar.DATE, -1);
                  //Loop start back to the previous sunday or monday
                  if (rangeStyle == RANGE_MONTH_MONDAY) {
                      startCutoff = Calendar.MONDAY;
                      endCutoff = Calendar.SUNDAY;
                  }
                  break;
              case RANGE_WEEK_SUNDAY:
              case RANGE_WEEK_MONDAY:
              case RANGE_WEEK_RELATIVE:
              case RANGE_WEEK_CENTER:
                  //Set start and end to the current date
                  start = trunc(focus, Calendar.DATE);
                  end = trunc(focus, Calendar.DATE);
                  switch (rangeStyle) {
                      case RANGE_WEEK_SUNDAY:
                          //already set by default
                          break;
                      case RANGE_WEEK_MONDAY:
                          startCutoff = Calendar.MONDAY;
                          endCutoff = Calendar.SUNDAY;
                          break;
                      case RANGE_WEEK_RELATIVE:
                          startCutoff = focus.get(Calendar.DAY_OF_WEEK);
                          endCutoff = startCutoff - 1;
                          break;
                      case RANGE_WEEK_CENTER:
                          startCutoff = focus.get(Calendar.DAY_OF_WEEK) - 3;
                          endCutoff = focus.get(Calendar.DAY_OF_WEEK) + 3;
                          break;
                  }
                  break;
              default:
                  throw new RuntimeException("The range style " + rangeStyle + " is not valid.");
          }
          if (startCutoff < Calendar.SUNDAY) {
              startCutoff += 7;
          }
          if (endCutoff > Calendar.SATURDAY) {
              endCutoff -= 7;
          }
          while (start.get(Calendar.DAY_OF_WEEK) != startCutoff) {
              start.add(Calendar.DATE, -1);
          }
          while (end.get(Calendar.DAY_OF_WEEK) != endCutoff) {
              end.add(Calendar.DATE, 1);
          }
          final Calendar startFinal = start;
          final Calendar endFinal = end;
          Iterator it = new Iterator() {
              Calendar spot = null;
              {
                  spot = startFinal;
                  spot.add(Calendar.DATE, -1);
              }
  
              public boolean hasNext() {
                  return spot.before(endFinal);
              }
  
              public Object next() {
                  if (spot.equals(endFinal)) {
                      throw new NoSuchElementException();
                  }
                  spot.add(Calendar.DATE, 1);
                  return spot.clone();
              }
  
              public void remove() {
                  throw new UnsupportedOperationException();
              }
          };
          return it;
      }
  
      /**
       * See the other getCalendarIterator.  Works with a Date.
       */
      public static Iterator getCalendarIterator(Date focus, int rangeStyle) {
          GregorianCalendar gval = new GregorianCalendar();
          gval.setTime(focus);
          return getCalendarIterator(gval, rangeStyle);
      }
  
      /**
       * See the other getCalendarIterator.  Works with an Object, trying
       * to use it as a Date or Calendar.
       */
      public static Iterator getCalendarIterator(Object focus, int rangeStyle) {
          if (focus instanceof Date) {
              return getCalendarIterator((Date) focus, rangeStyle);
          } else if (focus instanceof Calendar) {
              return getCalendarIterator((Calendar) focus, rangeStyle);
          } else {
              throw new ClassCastException("Could not iterate based on " + focus);
          }
      }
  
  }
  
  
  
  1.10      +2 -1      jakarta-commons/lang/src/test/org/apache/commons/lang/LangTestSuite.java
  
  Index: LangTestSuite.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons/lang/src/test/org/apache/commons/lang/LangTestSuite.java,v
  retrieving revision 1.9
  retrieving revision 1.10
  diff -u -r1.9 -r1.10
  --- LangTestSuite.java	16 Dec 2002 21:48:41 -0000	1.9
  +++ LangTestSuite.java	16 Dec 2002 21:55:20 -0000	1.10
  @@ -88,6 +88,7 @@
           suite.setName("Commons-Lang Tests");
           suite.addTest(ArrayUtilsTest.suite());
           suite.addTest(BooleanUtilsTest.suite());
  +        suite.addTest(CalendarUtilsTest.suite());
           suite.addTest(CharSetUtilsTest.suite());
           suite.addTest(ClassUtilsTest.suite());
           suite.addTest(DateUtilsTest.suite());
  
  
  
  1.1                  jakarta-commons/lang/src/test/org/apache/commons/lang/CalendarUtilsTest.java
  
  Index: CalendarUtilsTest.java
  ===================================================================
  package org.apache.commons.lang;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2002 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution, if
   *    any, must include the following acknowlegement:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowlegement may appear in the software itself,
   *    if and wherever such third-party acknowlegements normally appear.
   *
   * 4. The names "The Jakarta Project", "Commons", and "Apache Software
   *    Foundation" must not be used to endorse or promote products derived
   *    from this software without prior written permission. For written
   *    permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache"
   *    nor may "Apache" appear in their names without prior written
   *    permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import java.text.DateFormat;
  import java.util.*;
  
  import junit.framework.AssertionFailedError;
  import junit.framework.Test;
  import junit.framework.TestCase;
  import junit.framework.TestSuite;
  import junit.textui.TestRunner;
  
  /**
   * Unit tests {@link org.apache.commons.lang.CalendarUtils}.
   *
   * @author <a href="mailto:sergek@lokitech.com">Serge Knystautas</a>
   */
  public class CalendarUtilsTest extends TestCase {
      DateFormat parser = null;
      Date date1 = null;
      Date date2 = null;
  
      public CalendarUtilsTest(String name) {
          super(name);
      }
  
      public static void main(String[] args) {
          TestRunner.run(suite());
      }
  
      public static Test suite() {
      	TestSuite suite = new TestSuite(CalendarUtilsTest.class);
      	suite.setName("CalendarUtilsTest Tests");
          return suite;
      }
  
      protected void setUp() throws Exception {
          super.setUp();
  
          parser = new java.text.SimpleDateFormat("MMM dd, yyyy H:mm:ss.SSS");
  
          date1 = parser.parse("February 12, 2002 12:34:56.789");
          date2 = parser.parse("November 18, 2001 1:23:11.321");
      }
  
      protected void tearDown() throws Exception {
          super.tearDown();
      }
  
      //-----------------------------------------------------------------------
  
  
      /**
       * Tests various values with the round method
       */
      public void testRound() throws Exception {
          assertEquals("round year-1 failed",
                  new Date("2002 January 1"),
                  CalendarUtils.round(date1, Calendar.YEAR));
          assertEquals("round year-2 failed",
                  new Date("2002 January 1"),
                  CalendarUtils.round(date2, Calendar.YEAR));
          assertEquals("round month-1 failed",
                  new Date("2002 February 1"),
                  CalendarUtils.round(date1, Calendar.MONTH));
          assertEquals("round month-2 failed",
                  new Date("2001 December 1"),
                  CalendarUtils.round(date2, Calendar.MONTH));
          assertEquals("round semimonth-1 failed",
                  new Date("2002 February 16"),
                  CalendarUtils.round(date1, CalendarUtils.SEMI_MONTH));
          assertEquals("round semimonth-2 failed",
                  new Date("2001 November 16"),
                  CalendarUtils.round(date2, CalendarUtils.SEMI_MONTH));
          assertEquals("round date-1 failed",
                  new Date("2002 February 13"),
                  CalendarUtils.round(date1, Calendar.DATE));
          assertEquals("round date-2 failed",
                  new Date("2001 November 18"),
                  CalendarUtils.round(date2, Calendar.DATE));
          assertEquals("round hour-1 failed",
                  parser.parse("February 12, 2002 13:00:00.000"),
                  CalendarUtils.round(date1, Calendar.HOUR));
          assertEquals("round hour-2 failed",
                  parser.parse("November 18, 2001 1:00:00.000"),
                  CalendarUtils.round(date2, Calendar.HOUR));
          assertEquals("round minute-1 failed",
                  parser.parse("February 12, 2002 12:35:00.000"),
                  CalendarUtils.round(date1, Calendar.MINUTE));
          assertEquals("round minute-2 failed",
                  parser.parse("November 18, 2001 1:23:00.000"),
                  CalendarUtils.round(date2, Calendar.MINUTE));
          assertEquals("round second-1 failed",
                  parser.parse("February 12, 2002 12:34:57.000"),
                  CalendarUtils.round(date1, Calendar.SECOND));
          assertEquals("round second-2 failed",
                  parser.parse("November 18, 2001 1:23:11.000"),
                  CalendarUtils.round(date2, Calendar.SECOND));
      }
  
      /**
       * Tests various values with the trunc method
       */
      public void testTrunc() throws Exception {
          assertEquals("trunc year-1 failed",
                  new Date("2002 January 1"),
                  CalendarUtils.trunc(date1, Calendar.YEAR));
          assertEquals("trunc year-2 failed",
                  new Date("2001 January 1"),
                  CalendarUtils.trunc(date2, Calendar.YEAR));
          assertEquals("trunc month-1 failed",
                  new Date("2002 February 1"),
                  CalendarUtils.trunc(date1, Calendar.MONTH));
          assertEquals("trunc month-2 failed",
                  new Date("2001 November 1"),
                  CalendarUtils.trunc(date2, Calendar.MONTH));
          assertEquals("trunc semimonth-1 failed",
                  new Date("2002 February 1"),
                  CalendarUtils.trunc(date1, CalendarUtils.SEMI_MONTH));
          assertEquals("trunc semimonth-2 failed",
                  new Date("2001 November 16"),
                  CalendarUtils.trunc(date2, CalendarUtils.SEMI_MONTH));
          assertEquals("trunc date-1 failed",
                  new Date("2002 February 12"),
                  CalendarUtils.trunc(date1, Calendar.DATE));
          assertEquals("trunc date-2 failed",
                  new Date("2001 November 18"),
                  CalendarUtils.trunc(date2, Calendar.DATE));
          assertEquals("trunc hour-1 failed",
                  parser.parse("February 12, 2002 12:00:00.000"),
                  CalendarUtils.trunc(date1, Calendar.HOUR));
          assertEquals("trunc hour-2 failed",
                  parser.parse("November 18, 2001 1:00:00.000"),
                  CalendarUtils.trunc(date2, Calendar.HOUR));
          assertEquals("trunc minute-1 failed",
                  parser.parse("February 12, 2002 12:34:00.000"),
                  CalendarUtils.trunc(date1, Calendar.MINUTE));
          assertEquals("trunc minute-2 failed",
                  parser.parse("November 18, 2001 1:23:00.000"),
                  CalendarUtils.trunc(date2, Calendar.MINUTE));
          assertEquals("trunc second-1 failed",
                  parser.parse("February 12, 2002 12:34:56.000"),
                  CalendarUtils.trunc(date1, Calendar.SECOND));
          assertEquals("trunc second-2 failed",
                  parser.parse("November 18, 2001 1:23:11.000"),
                  CalendarUtils.trunc(date2, Calendar.SECOND));
  
      }
  
      /**
       * Tests the parse method, which is supposed to handle various strings
       * as flexibly as CVS supports.
       */
      public void testParse() throws Exception {
          //This is difficult to test since the "now" used in the
          //  parse function cannot be controlled.  We could possibly control
          //  it by trying before and after and making sure the value we expect
          //  is between the two values calculated.
          //For now we're just using the custom assertEquals that takes a delta
  
          Calendar now = null;
  
          now = Calendar.getInstance();
          now.add(Calendar.MINUTE, -1);
          assertEquals("parse 1 minute ago",
                  now, CalendarUtils.parse("1 minute ago"), 50);
          now = Calendar.getInstance();
          now.add(Calendar.MINUTE, -8);
          assertEquals("parse 8 minutes ago",
                  now, CalendarUtils.parse("8 minutes ago"), 50);
  
          now = Calendar.getInstance();
          now.add(Calendar.DATE, -1);
          assertEquals("parse yesterday",
                  now, CalendarUtils.parse("yesterday"), 50);
  
          now = Calendar.getInstance();
          now.add(Calendar.DATE, 1);
          assertEquals("parse tomorrow",
                  now, CalendarUtils.parse("tomorrow"), 50);
  
          now = Calendar.getInstance();
          //Sunday would be 1, Saturday would be 7, so we walk back up to 6 days.
          if (now.get(Calendar.DATE) == 1) {
              //If Sunday already, we go back a full week
              now.add(Calendar.DATE, -7);
          } else {
              now.add(Calendar.DATE, 1 - now.get(Calendar.DAY_OF_WEEK));
          }
          assertEquals("parse last Sunday",
                  now, CalendarUtils.parse("last Sunday"), 50);
  
          now = Calendar.getInstance();
          now.add(Calendar.DATE, -7);
          assertEquals("parse last week",
                  now, CalendarUtils.parse("last week"), 50);
  
          now = Calendar.getInstance();
          //January would be 0, December would be 11, so we walk back up to 11 months
          if (now.get(Calendar.MONTH) == 0) {
              //If January already, we go back a full year
              now.add(Calendar.MONTH, -12);
          } else {
              now.add(Calendar.MONTH, 0 - now.get(Calendar.MONTH));
          }
          assertEquals("parse last January",
                  now, CalendarUtils.parse("last January"), 50);
      }
  
      /**
       * Tests the calendar iterator for week ranges
       */
      public void testWeekIterator() throws Exception {
          Calendar now = Calendar.getInstance();
          Calendar today = CalendarUtils.trunc(now, Calendar.DATE);
          Calendar sunday = CalendarUtils.trunc(now, Calendar.DATE);
          sunday.add(Calendar.DATE, 1 - sunday.get(Calendar.DAY_OF_WEEK));
          Calendar monday = CalendarUtils.trunc(now, Calendar.DATE);
          if (monday.get(Calendar.DATE) == 1) {
              //This is sunday... roll back 6 days
              monday.add(Calendar.DATE, -6);
          } else {
              monday.add(Calendar.DATE, 2 - monday.get(Calendar.DAY_OF_WEEK));
          }
          Calendar centered = CalendarUtils.trunc(now, Calendar.DATE);
          centered.add(Calendar.DATE, -3);
  
          Iterator it = CalendarUtils.getCalendarIterator(now, CalendarUtils.RANGE_WEEK_SUNDAY);
          assertWeekIterator(it, sunday);
          it = CalendarUtils.getCalendarIterator(now, CalendarUtils.RANGE_WEEK_MONDAY);
          assertWeekIterator(it, monday);
          it = CalendarUtils.getCalendarIterator(now, CalendarUtils.RANGE_WEEK_RELATIVE);
          assertWeekIterator(it, today);
          it = CalendarUtils.getCalendarIterator(now, CalendarUtils.RANGE_WEEK_CENTER);
          assertWeekIterator(it, centered);
      }
  
      /**
       * Tests the calendar iterator for month-based ranges
       */
      public void testMonthIterator() throws Exception {
          Iterator it = CalendarUtils.getCalendarIterator(date1, CalendarUtils.RANGE_MONTH_SUNDAY);
          assertWeekIterator(it,
                  new Date("January 27, 2002"),
                  new Date("March 2, 2002"));
  
          it = CalendarUtils.getCalendarIterator(date1, CalendarUtils.RANGE_MONTH_MONDAY);
          assertWeekIterator(it,
                  new Date("January 28, 2002"),
                  new Date("March 3, 2002"));
  
          it = CalendarUtils.getCalendarIterator(date2, CalendarUtils.RANGE_MONTH_SUNDAY);
          assertWeekIterator(it,
                  new Date("October 28, 2001"),
                  new Date("December 1, 2001"));
  
          it = CalendarUtils.getCalendarIterator(date2, CalendarUtils.RANGE_MONTH_MONDAY);
          assertWeekIterator(it,
                  new Date("October 29, 2001"),
                  new Date("December 2, 2001"));
      }
  
      /**
       * This checks that this is a 7 element iterator of Calendar objects
       * that are dates (no time), and exactly 1 day spaced after each other.
       */
      private static void assertWeekIterator(Iterator it, Calendar start) {
          Calendar end = (Calendar) start.clone();
          end.add(Calendar.DATE, 6);
  
          assertWeekIterator(it, start, end);
      }
  
      /**
       * Convenience method for when working with Date objects
       */
      private static void assertWeekIterator(Iterator it, Date start, Date end) {
          Calendar calStart = Calendar.getInstance();
          calStart.setTime(start);
          Calendar calEnd = Calendar.getInstance();
          calEnd.setTime(end);
  
          assertWeekIterator(it, calStart, calEnd);
      }
  
      /**
       * This checks that this is a 7 divisble iterator of Calendar objects
       * that are dates (no time), and exactly 1 day spaced after each other
       * (in addition to the proper start and stop dates)
       */
      private static void assertWeekIterator(Iterator it, Calendar start, Calendar end) {
          Calendar cal = (Calendar) it.next();
          assertEquals("", start, cal, 0);
          Calendar last = null;
          int count = 1;
          while (it.hasNext()) {
              //Check this is just a date (no time component)
              assertEquals("", cal, CalendarUtils.trunc(cal, Calendar.DATE), 0);
  
              last = cal;
              cal = (Calendar) it.next();
              count++;
  
              //Check that this is one day more than the last date
              last.add(Calendar.DATE, 1);
              assertEquals("", last, cal, 0);
          }
          if (count % 7 != 0) {
              throw new AssertionFailedError("There were " + count + " days in this iterator");
          }
          assertEquals("", end, cal, 0);
      }
  
      /**
       * Used to check that Calendar objects are close enough
       * delta is in milliseconds
       */
      public static void assertEquals(String message, Calendar cal1, Calendar cal2, long delta)
{
          if (Math.abs(cal1.getTime().getTime() - cal2.getTime().getTime()) > delta) {
              throw new AssertionFailedError(
                      message + " expected " + cal1.getTime() + " but got " + cal2.getTime());
          }
      }
  }
  
  
  
  

--
To unsubscribe, e-mail:   <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>


Mime
View raw message