geronimo-scm mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From jdil...@apache.org
Subject svn commit: r571559 [1/2] - in /geronimo/sandbox/gshell/trunk: ./ gshell-cli/src/main/java/org/apache/geronimo/gshell/cli/ gshell-commands/gshell-standard-commands/src/main/java/org/apache/geronimo/gshell/commands/standard/ gshell-common/ gshell-common...
Date Fri, 31 Aug 2007 20:22:42 GMT
Author: jdillon
Date: Fri Aug 31 13:22:41 2007
New Revision: 571559

URL: http://svn.apache.org/viewvc?rev=571559&view=rev
Log:
Drop commons-lang like a rock, we only used to for StopWatch and some bits from StringUtils.
So duplicate the StopWatch related code and use the StringUtils from plexus-utils instead
Drop the diet version of commons-lang

Added:
    geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DateUtils.java   (with props)
    geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DurationFormatUtils.java   (with props)
    geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/StopWatch.java   (with props)
Removed:
    geronimo/sandbox/gshell/trunk/gshell-diet/gshell-diet-commons-lang/
Modified:
    geronimo/sandbox/gshell/trunk/gshell-cli/src/main/java/org/apache/geronimo/gshell/cli/Main.java
    geronimo/sandbox/gshell/trunk/gshell-commands/gshell-standard-commands/src/main/java/org/apache/geronimo/gshell/commands/standard/CatCommand.java
    geronimo/sandbox/gshell/trunk/gshell-common/pom.xml
    geronimo/sandbox/gshell/trunk/gshell-core/pom.xml
    geronimo/sandbox/gshell/trunk/gshell-core/src/main/java/org/apache/geronimo/gshell/Shell.java
    geronimo/sandbox/gshell/trunk/gshell-diet/pom.xml
    geronimo/sandbox/gshell/trunk/pom.xml

Modified: geronimo/sandbox/gshell/trunk/gshell-cli/src/main/java/org/apache/geronimo/gshell/cli/Main.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gshell/trunk/gshell-cli/src/main/java/org/apache/geronimo/gshell/cli/Main.java?rev=571559&r1=571558&r2=571559&view=diff
==============================================================================
--- geronimo/sandbox/gshell/trunk/gshell-cli/src/main/java/org/apache/geronimo/gshell/cli/Main.java (original)
+++ geronimo/sandbox/gshell/trunk/gshell-cli/src/main/java/org/apache/geronimo/gshell/cli/Main.java Fri Aug 31 13:22:41 2007
@@ -22,7 +22,7 @@
 import java.util.List;
 
 import jline.Terminal;
-import org.apache.commons.lang.time.StopWatch;
+import org.apache.geronimo.gshell.common.StopWatch;
 import org.apache.geronimo.gshell.InteractiveShell;
 import org.apache.geronimo.gshell.Shell;
 import org.apache.geronimo.gshell.clp.Argument;

Modified: geronimo/sandbox/gshell/trunk/gshell-commands/gshell-standard-commands/src/main/java/org/apache/geronimo/gshell/commands/standard/CatCommand.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gshell/trunk/gshell-commands/gshell-standard-commands/src/main/java/org/apache/geronimo/gshell/commands/standard/CatCommand.java?rev=571559&r1=571558&r2=571559&view=diff
==============================================================================
--- geronimo/sandbox/gshell/trunk/gshell-commands/gshell-standard-commands/src/main/java/org/apache/geronimo/gshell/commands/standard/CatCommand.java (original)
+++ geronimo/sandbox/gshell/trunk/gshell-commands/gshell-standard-commands/src/main/java/org/apache/geronimo/gshell/commands/standard/CatCommand.java Fri Aug 31 13:22:41 2007
@@ -23,17 +23,18 @@
 import java.io.File;
 import java.io.FileReader;
 import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.IOException;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.List;
 
-import org.apache.commons.lang.StringUtils;
-
 import org.apache.geronimo.gshell.clp.Argument;
 import org.apache.geronimo.gshell.clp.Option;
 import org.apache.geronimo.gshell.command.Command;
 import org.apache.geronimo.gshell.command.CommandSupport;
 import org.apache.geronimo.gshell.console.IO;
+import org.codehaus.plexus.util.StringUtils;
 
 /**
  * Concatenate and print files and/or URLs.
@@ -60,21 +61,18 @@
     protected Object doExecute() throws Exception {
         IO io = getIO();
 
-        for (String filename : args) {
-            BufferedReader reader;
+        //
+        // Support "-" if length is one, and read from io.in
+        // This will help test command pipelines.
+        //
+        if (args.size() == 1 && "-".equals(args.get(0))) {
+            log.info("Printing STDIN");
+            cat(new BufferedReader(io.in), io);
+        }
+        else {
+            for (String filename : args) {
+                BufferedReader reader;
 
-            // FIXME:
-            /*
-            //
-            // Support "-" if length is one, and read from io.in
-            // This will help test command pipelines.
-            //
-            if (files.length == 1 && "-".equals(files[0])) {
-                log.info("Printing STDIN");
-                reader = new BufferedReader(io.in);
-            }
-            else {
-            */
                 // First try a URL
                 try {
                     URL url = new URL(filename);
@@ -87,23 +85,27 @@
                     log.info("Printing file: " + file);
                     reader = new BufferedReader(new FileReader(file));
                 }
-            /*}*/
 
-            String line;
-            int lineno = 1;
+                cat(reader, io);
 
-            while ((line = reader.readLine()) != null) {
-                if (displayLineNumbers) {
-                    String gutter = StringUtils.leftPad(String.valueOf(lineno++), 6);
-                    io.out.print(gutter);
-                    io.out.print("  ");
-                }
-                io.out.println(line);
+                reader.close();
             }
-
-            reader.close();
         }
 
         return Command.SUCCESS;
+    }
+
+    private void cat(final BufferedReader reader, final IO io) throws IOException {
+        String line;
+        int lineno = 1;
+
+        while ((line = reader.readLine()) != null) {
+            if (displayLineNumbers) {
+                String gutter = StringUtils.leftPad(String.valueOf(lineno++), 6);
+                io.out.print(gutter);
+                io.out.print("  ");
+            }
+            io.out.println(line);
+        }
     }
 }

Modified: geronimo/sandbox/gshell/trunk/gshell-common/pom.xml
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gshell/trunk/gshell-common/pom.xml?rev=571559&r1=571558&r2=571559&view=diff
==============================================================================
--- geronimo/sandbox/gshell/trunk/gshell-common/pom.xml (original)
+++ geronimo/sandbox/gshell/trunk/gshell-common/pom.xml Fri Aug 31 13:22:41 2007
@@ -40,7 +40,7 @@
     <dependencies>
         <dependency>
             <groupId>org.apache.geronimo.gshell</groupId>
-            <artifactId>gshell-diet-commons-lang</artifactId>
+            <artifactId>gshell-diet-plexus-utils</artifactId>
             <version>${pom.version}</version>
         </dependency>
         

Added: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DateUtils.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DateUtils.java?rev=571559&view=auto
==============================================================================
--- geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DateUtils.java (added)
+++ geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DateUtils.java Fri Aug 31 13:22:41 2007
@@ -0,0 +1,997 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.geronimo.gshell.common;
+
+//
+// NOTE: Copied and massaged from commons-lang 2.3
+//
+
+import java.text.ParseException;
+import java.text.ParsePosition;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.TimeZone;
+
+/**
+ * <p>A suite of utilities surrounding the use of the
+ * {@link java.util.Calendar} and {@link java.util.Date} object.</p>
+ *
+ * @author <a href="mailto:sergek@lokitech.com">Serge Knystautas</a>
+ * @author Stephen Colebourne
+ * @author Janek Bogucki
+ * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
+ * @author Phil Steitz
+ * @since 2.0
+ * @version $Id$
+ */
+public class DateUtils
+{
+    /**
+     * The UTC time zone  (often referred to as GMT).
+     */
+    public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
+    /**
+     * Number of milliseconds in a standard second.
+     * @since 2.1
+     */
+    public static final long MILLIS_PER_SECOND = 1000;
+    /**
+     * Number of milliseconds in a standard minute.
+     * @since 2.1
+     */
+    public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
+    /**
+     * Number of milliseconds in a standard hour.
+     * @since 2.1
+     */
+    public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
+    /**
+     * Number of milliseconds in a standard day.
+     * @since 2.1
+     */
+    public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
+
+    /**
+     * 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, DateUtils.SEMI_MONTH},
+            {Calendar.YEAR},
+            {Calendar.ERA}};
+
+    /**
+     * 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;
+
+    /**
+     * <p><code>DateUtils</code> instances should NOT be constructed in
+     * standard programming. Instead, the class should be used as
+     * <code>DateUtils.parse(str);</code>.</p>
+     *
+     * <p>This constructor is public to permit tools that require a JavaBean
+     * instance to operate.</p>
+     */
+    public DateUtils() {
+        super();
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * <p>Checks if two date objects are on the same day ignoring time.</p>
+     *
+     * <p>28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true.
+     * 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false.
+     * </p>
+     *
+     * @param date1  the first date, not altered, not null
+     * @param date2  the second date, not altered, not null
+     * @return true if they represent the same day
+     * @throws IllegalArgumentException if either date is <code>null</code>
+     * @since 2.1
+     */
+    public static boolean isSameDay(Date date1, Date date2) {
+        if (date1 == null || date2 == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        Calendar cal1 = Calendar.getInstance();
+        cal1.setTime(date1);
+        Calendar cal2 = Calendar.getInstance();
+        cal2.setTime(date2);
+        return isSameDay(cal1, cal2);
+    }
+
+    /**
+     * <p>Checks if two calendar objects are on the same day ignoring time.</p>
+     *
+     * <p>28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true.
+     * 28 Mar 2002 13:45 and 12 Mar 2002 13:45 would return false.
+     * </p>
+     *
+     * @param cal1  the first calendar, not altered, not null
+     * @param cal2  the second calendar, not altered, not null
+     * @return true if they represent the same day
+     * @throws IllegalArgumentException if either calendar is <code>null</code>
+     * @since 2.1
+     */
+    public static boolean isSameDay(Calendar cal1, Calendar cal2) {
+        if (cal1 == null || cal2 == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
+                cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
+                cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * <p>Checks if two date objects represent the same instant in time.</p>
+     *
+     * <p>This method compares the long millisecond time of the two objects.</p>
+     *
+     * @param date1  the first date, not altered, not null
+     * @param date2  the second date, not altered, not null
+     * @return true if they represent the same millisecond instant
+     * @throws IllegalArgumentException if either date is <code>null</code>
+     * @since 2.1
+     */
+    public static boolean isSameInstant(Date date1, Date date2) {
+        if (date1 == null || date2 == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        return date1.getTime() == date2.getTime();
+    }
+
+    /**
+     * <p>Checks if two calendar objects represent the same instant in time.</p>
+     *
+     * <p>This method compares the long millisecond time of the two objects.</p>
+     *
+     * @param cal1  the first calendar, not altered, not null
+     * @param cal2  the second calendar, not altered, not null
+     * @return true if they represent the same millisecond instant
+     * @throws IllegalArgumentException if either date is <code>null</code>
+     * @since 2.1
+     */
+    public static boolean isSameInstant(Calendar cal1, Calendar cal2) {
+        if (cal1 == null || cal2 == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        return cal1.getTime().getTime() == cal2.getTime().getTime();
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * <p>Checks if two calendar objects represent the same local time.</p>
+     *
+     * <p>This method compares the values of the fields of the two objects.
+     * In addition, both calendars must be the same of the same type.</p>
+     *
+     * @param cal1  the first calendar, not altered, not null
+     * @param cal2  the second calendar, not altered, not null
+     * @return true if they represent the same millisecond instant
+     * @throws IllegalArgumentException if either date is <code>null</code>
+     * @since 2.1
+     */
+    public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {
+        if (cal1 == null || cal2 == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) &&
+                cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) &&
+                cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) &&
+                cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) &&
+                cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
+                cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
+                cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
+                cal1.getClass() == cal2.getClass());
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * <p>Parses a string representing a date by trying a variety of different parsers.</p>
+     *
+     * <p>The parse will try each parse pattern in turn.
+     * A parse is only deemed sucessful if it parses the whole of the input string.
+     * If no parse patterns match, a ParseException is thrown.</p>
+     *
+     * @param str  the date to parse, not null
+     * @param parsePatterns  the date format patterns to use, see SimpleDateFormat, not null
+     * @return the parsed date
+     * @throws IllegalArgumentException if the date string or pattern array is null
+     * @throws ParseException if none of the date patterns were suitable
+     */
+    public static Date parseDate(String str, String[] parsePatterns) throws ParseException {
+        if (str == null || parsePatterns == null) {
+            throw new IllegalArgumentException("Date and Patterns must not be null");
+        }
+
+        SimpleDateFormat parser = null;
+        ParsePosition pos = new ParsePosition(0);
+        for (int i = 0; i < parsePatterns.length; i++) {
+            if (i == 0) {
+                parser = new SimpleDateFormat(parsePatterns[0]);
+            } else {
+                parser.applyPattern(parsePatterns[i]);
+            }
+            pos.setIndex(0);
+            Date date = parser.parse(str, pos);
+            if (date != null && pos.getIndex() == str.length()) {
+                return date;
+            }
+        }
+        throw new ParseException("Unable to parse the date: " + str, -1);
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * Adds a number of years to a date returning a new object.
+     * The original date object is unchanged.
+     *
+     * @param date  the date, not null
+     * @param amount  the amount to add, may be negative
+     * @return the new date object with the amount added
+     * @throws IllegalArgumentException if the date is null
+     */
+    public static Date addYears(Date date, int amount) {
+        return add(date, Calendar.YEAR, amount);
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * Adds a number of months to a date returning a new object.
+     * The original date object is unchanged.
+     *
+     * @param date  the date, not null
+     * @param amount  the amount to add, may be negative
+     * @return the new date object with the amount added
+     * @throws IllegalArgumentException if the date is null
+     */
+    public static Date addMonths(Date date, int amount) {
+        return add(date, Calendar.MONTH, amount);
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * Adds a number of weeks to a date returning a new object.
+     * The original date object is unchanged.
+     *
+     * @param date  the date, not null
+     * @param amount  the amount to add, may be negative
+     * @return the new date object with the amount added
+     * @throws IllegalArgumentException if the date is null
+     */
+    public static Date addWeeks(Date date, int amount) {
+        return add(date, Calendar.WEEK_OF_YEAR, amount);
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * Adds a number of days to a date returning a new object.
+     * The original date object is unchanged.
+     *
+     * @param date  the date, not null
+     * @param amount  the amount to add, may be negative
+     * @return the new date object with the amount added
+     * @throws IllegalArgumentException if the date is null
+     */
+    public static Date addDays(Date date, int amount) {
+        return add(date, Calendar.DAY_OF_MONTH, amount);
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * Adds a number of hours to a date returning a new object.
+     * The original date object is unchanged.
+     *
+     * @param date  the date, not null
+     * @param amount  the amount to add, may be negative
+     * @return the new date object with the amount added
+     * @throws IllegalArgumentException if the date is null
+     */
+    public static Date addHours(Date date, int amount) {
+        return add(date, Calendar.HOUR_OF_DAY, amount);
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * Adds a number of minutes to a date returning a new object.
+     * The original date object is unchanged.
+     *
+     * @param date  the date, not null
+     * @param amount  the amount to add, may be negative
+     * @return the new date object with the amount added
+     * @throws IllegalArgumentException if the date is null
+     */
+    public static Date addMinutes(Date date, int amount) {
+        return add(date, Calendar.MINUTE, amount);
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * Adds a number of seconds to a date returning a new object.
+     * The original date object is unchanged.
+     *
+     * @param date  the date, not null
+     * @param amount  the amount to add, may be negative
+     * @return the new date object with the amount added
+     * @throws IllegalArgumentException if the date is null
+     */
+    public static Date addSeconds(Date date, int amount) {
+        return add(date, Calendar.SECOND, amount);
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * Adds a number of milliseconds to a date returning a new object.
+     * The original date object is unchanged.
+     *
+     * @param date  the date, not null
+     * @param amount  the amount to add, may be negative
+     * @return the new date object with the amount added
+     * @throws IllegalArgumentException if the date is null
+     */
+    public static Date addMilliseconds(Date date, int amount) {
+        return add(date, Calendar.MILLISECOND, amount);
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * Adds to a date returning a new object.
+     * The original date object is unchanged.
+     *
+     * @param date  the date, not null
+     * @param calendarField  the calendar field to add to
+     * @param amount  the amount to add, may be negative
+     * @return the new date object with the amount added
+     * @throws IllegalArgumentException if the date is null
+     */
+    public static Date add(Date date, int calendarField, int amount) {
+        if (date == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        Calendar c = Calendar.getInstance();
+        c.setTime(date);
+        c.add(calendarField, amount);
+        return c.getTime();
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * <p>Round this date, leaving the field specified as the most
+     * significant field.</p>
+     *
+     * <p>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.</p>
+     *
+     * <p>For a date in a timezone that handles the change to daylight
+     * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows.
+     * Suppose daylight saving time begins at 02:00 on March 30. Rounding a
+     * date that crosses this time would produce the following values:
+     * <ul>
+     * <li>March 30, 2003 01:10 rounds to March 30, 2003 01:00</li>
+     * <li>March 30, 2003 01:40 rounds to March 30, 2003 03:00</li>
+     * <li>March 30, 2003 02:10 rounds to March 30, 2003 03:00</li>
+     * <li>March 30, 2003 02:40 rounds to March 30, 2003 04:00</li>
+     * </ul>
+     * </p>
+     *
+     * @param date  the date to work with
+     * @param field  the field from <code>Calendar</code>
+     *  or <code>SEMI_MONTH</code>
+     * @return the rounded date
+     * @throws IllegalArgumentException if the date is <code>null</code>
+     * @throws ArithmeticException if the year is over 280 million
+     */
+    public static Date round(Date date, int field) {
+        if (date == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        Calendar gval = Calendar.getInstance();
+        gval.setTime(date);
+        modify(gval, field, true);
+        return gval.getTime();
+    }
+
+    /**
+     * <p>Round this date, leaving the field specified as the most
+     * significant field.</p>
+     *
+     * <p>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.</p>
+     *
+     * <p>For a date in a timezone that handles the change to daylight
+     * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows.
+     * Suppose daylight saving time begins at 02:00 on March 30. Rounding a
+     * date that crosses this time would produce the following values:
+     * <ul>
+     * <li>March 30, 2003 01:10 rounds to March 30, 2003 01:00</li>
+     * <li>March 30, 2003 01:40 rounds to March 30, 2003 03:00</li>
+     * <li>March 30, 2003 02:10 rounds to March 30, 2003 03:00</li>
+     * <li>March 30, 2003 02:40 rounds to March 30, 2003 04:00</li>
+     * </ul>
+     * </p>
+     *
+     * @param date  the date to work with
+     * @param field  the field from <code>Calendar</code>
+     *  or <code>SEMI_MONTH</code>
+     * @return the rounded date (a different object)
+     * @throws IllegalArgumentException if the date is <code>null</code>
+     * @throws ArithmeticException if the year is over 280 million
+     */
+    public static Calendar round(Calendar date, int field) {
+        if (date == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        Calendar rounded = (Calendar) date.clone();
+        modify(rounded, field, true);
+        return rounded;
+    }
+
+    /**
+     * <p>Round this date, leaving the field specified as the most
+     * significant field.</p>
+     *
+     * <p>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.</p>
+     *
+     * <p>For a date in a timezone that handles the change to daylight
+     * saving time, rounding to Calendar.HOUR_OF_DAY will behave as follows.
+     * Suppose daylight saving time begins at 02:00 on March 30. Rounding a
+     * date that crosses this time would produce the following values:
+     * <ul>
+     * <li>March 30, 2003 01:10 rounds to March 30, 2003 01:00</li>
+     * <li>March 30, 2003 01:40 rounds to March 30, 2003 03:00</li>
+     * <li>March 30, 2003 02:10 rounds to March 30, 2003 03:00</li>
+     * <li>March 30, 2003 02:40 rounds to March 30, 2003 04:00</li>
+     * </ul>
+     * </p>
+     *
+     * @param date  the date to work with, either Date or Calendar
+     * @param field  the field from <code>Calendar</code>
+     *  or <code>SEMI_MONTH</code>
+     * @return the rounded date
+     * @throws IllegalArgumentException if the date is <code>null</code>
+     * @throws ClassCastException if the object type is not a <code>Date</code>
+     *  or <code>Calendar</code>
+     * @throws ArithmeticException if the year is over 280 million
+     */
+    public static Date round(Object date, int field) {
+        if (date == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        if (date instanceof Date) {
+            return round((Date) date, field);
+        } else if (date instanceof Calendar) {
+            return round((Calendar) date, field).getTime();
+        } else {
+            throw new ClassCastException("Could not round " + date);
+        }
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * <p>Truncate this date, leaving the field specified as the most
+     * significant field.</p>
+     *
+     * <p>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.</p>
+     *
+     * @param date  the date to work with
+     * @param field  the field from <code>Calendar</code>
+     *  or <code>SEMI_MONTH</code>
+     * @return the rounded date
+     * @throws IllegalArgumentException if the date is <code>null</code>
+     * @throws ArithmeticException if the year is over 280 million
+     */
+    public static Date truncate(Date date, int field) {
+        if (date == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        Calendar gval = Calendar.getInstance();
+        gval.setTime(date);
+        modify(gval, field, false);
+        return gval.getTime();
+    }
+
+    /**
+     * <p>Truncate this date, leaving the field specified as the most
+     * significant field.</p>
+     *
+     * <p>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.</p>
+     *
+     * @param date  the date to work with
+     * @param field  the field from <code>Calendar</code>
+     *  or <code>SEMI_MONTH</code>
+     * @return the rounded date (a different object)
+     * @throws IllegalArgumentException if the date is <code>null</code>
+     * @throws ArithmeticException if the year is over 280 million
+     */
+    public static Calendar truncate(Calendar date, int field) {
+        if (date == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        Calendar truncated = (Calendar) date.clone();
+        modify(truncated, field, false);
+        return truncated;
+    }
+
+    /**
+     * <p>Truncate this date, leaving the field specified as the most
+     * significant field.</p>
+     *
+     * <p>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.</p>
+     *
+     * @param date  the date to work with, either <code>Date</code>
+     *  or <code>Calendar</code>
+     * @param field  the field from <code>Calendar</code>
+     *  or <code>SEMI_MONTH</code>
+     * @return the rounded date
+     * @throws IllegalArgumentException if the date
+     *  is <code>null</code>
+     * @throws ClassCastException if the object type is not a
+     *  <code>Date</code> or <code>Calendar</code>
+     * @throws ArithmeticException if the year is over 280 million
+     */
+    public static Date truncate(Object date, int field) {
+        if (date == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        if (date instanceof Date) {
+            return truncate((Date) date, field);
+        } else if (date instanceof Calendar) {
+            return truncate((Calendar) date, field).getTime();
+        } else {
+            throw new ClassCastException("Could not truncate " + date);
+        }
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * <p>Internal calculation method.</p>
+     *
+     * @param val  the calendar
+     * @param field  the field constant
+     * @param round  true to round, false to truncate
+     * @throws ArithmeticException if the year is over 280 million
+     */
+    private static void modify(Calendar val, int field, boolean round) {
+        if (val.get(Calendar.YEAR) > 280000000) {
+            throw new ArithmeticException("Calendar value too large for accurate calculations");
+        }
+
+        if (field == Calendar.MILLISECOND) {
+            return;
+        }
+
+        // ----------------- Fix for LANG-59 ---------------------- START ---------------
+        // see http://issues.apache.org/jira/browse/LANG-59
+        //
+        // Manually truncate milliseconds, seconds and minutes, rather than using
+        // Calendar methods.
+
+        Date date = val.getTime();
+        long time = date.getTime();
+        boolean done = false;
+
+        // truncate milliseconds
+        int millisecs = val.get(Calendar.MILLISECOND);
+        if (!round || millisecs < 500) {
+            time = time - millisecs;
+            if (field == Calendar.SECOND) {
+                done = true;
+            }
+        }
+
+        // truncate seconds
+        int seconds = val.get(Calendar.SECOND);
+        if (!done && (!round || seconds < 30)) {
+            time = time - (seconds * 1000L);
+            if (field == Calendar.MINUTE) {
+                done = true;
+            }
+        }
+
+        // truncate minutes
+        int minutes = val.get(Calendar.MINUTE);
+        if (!done && (!round || minutes < 30)) {
+            time = time - (minutes * 60000L);
+        }
+
+        // reset time
+        if (date.getTime() != time) {
+            date.setTime(time);
+            val.setTime(date);
+        }
+        // ----------------- Fix for LANG-59 ----------------------- END ----------------
+
+        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 == DateUtils.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 DateUtils.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_OF_DAY) {
+                        //If we're going to drop the HOUR field's value,
+                        //  we want to do this our own way.
+                        offset = val.get(Calendar.HOUR_OF_DAY);
+                        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
+            if (offset != 0) {
+                val.set(fields[i][0], val.get(fields[i][0]) - offset);
+            }
+        }
+        throw new IllegalArgumentException("The field " + field + " is not supported");
+
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * <p>This constructs an <code>Iterator</code> over each day in a date
+     * range defined by a focus date and range style.</p>
+     *
+     * <p>For instance, passing Thursday, July 4, 2002 and a
+     * <code>RANGE_MONTH_SUNDAY</code> will return an <code>Iterator</code>
+     * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
+     * 2002, returning a Calendar instance for each intermediate day.</p>
+     *
+     * <p>This method provides an iterator that returns Calendar objects.
+     * The days are progressed using {@link Calendar#add(int, int)}.</p>
+     *
+     * @param focus  the date to work with, not null
+     * @param rangeStyle  the style constant to use. Must be one of
+     * {@link DateUtils#RANGE_MONTH_SUNDAY},
+     * {@link DateUtils#RANGE_MONTH_MONDAY},
+     * {@link DateUtils#RANGE_WEEK_SUNDAY},
+     * {@link DateUtils#RANGE_WEEK_MONDAY},
+     * {@link DateUtils#RANGE_WEEK_RELATIVE},
+     * {@link DateUtils#RANGE_WEEK_CENTER}
+     * @return the date iterator, which always returns Calendar instances
+     * @throws IllegalArgumentException if the date is <code>null</code>
+     * @throws IllegalArgumentException if the rangeStyle is invalid
+     */
+    public static Iterator iterator(Date focus, int rangeStyle) {
+        if (focus == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        Calendar gval = Calendar.getInstance();
+        gval.setTime(focus);
+        return iterator(gval, rangeStyle);
+    }
+
+    /**
+     * <p>This constructs an <code>Iterator</code> over each day in a date
+     * range defined by a focus date and range style.</p>
+     *
+     * <p>For instance, passing Thursday, July 4, 2002 and a
+     * <code>RANGE_MONTH_SUNDAY</code> will return an <code>Iterator</code>
+     * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
+     * 2002, returning a Calendar instance for each intermediate day.</p>
+     *
+     * <p>This method provides an iterator that returns Calendar objects.
+     * The days are progressed using {@link Calendar#add(int, int)}.</p>
+     *
+     * @param focus  the date to work with
+     * @param rangeStyle  the style constant to use. Must be one of
+     * {@link DateUtils#RANGE_MONTH_SUNDAY},
+     * {@link DateUtils#RANGE_MONTH_MONDAY},
+     * {@link DateUtils#RANGE_WEEK_SUNDAY},
+     * {@link DateUtils#RANGE_WEEK_MONDAY},
+     * {@link DateUtils#RANGE_WEEK_RELATIVE},
+     * {@link DateUtils#RANGE_WEEK_CENTER}
+     * @return the date iterator
+     * @throws IllegalArgumentException if the date is <code>null</code>
+     * @throws IllegalArgumentException if the rangeStyle is invalid
+     */
+    public static Iterator iterator(Calendar focus, int rangeStyle) {
+        if (focus == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        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 = truncate(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 = truncate(focus, Calendar.DATE);
+                end = truncate(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 IllegalArgumentException("The range style " + rangeStyle + " is not valid.");
+        }
+        if (startCutoff < Calendar.SUNDAY) {
+            startCutoff += 7;
+        }
+        if (startCutoff > Calendar.SATURDAY) {
+            startCutoff -= 7;
+        }
+        if (endCutoff < Calendar.SUNDAY) {
+            endCutoff += 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);
+        }
+        return new DateIterator(start, end);
+    }
+
+    /**
+     * <p>This constructs an <code>Iterator</code> over each day in a date
+     * range defined by a focus date and range style.</p>
+     *
+     * <p>For instance, passing Thursday, July 4, 2002 and a
+     * <code>RANGE_MONTH_SUNDAY</code> will return an <code>Iterator</code>
+     * that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
+     * 2002, returning a Calendar instance for each intermediate day.</p>
+     *
+     * @param focus  the date to work with, either
+     *  <code>Date</code> or <code>Calendar</code>
+     * @param rangeStyle  the style constant to use. Must be one of the range
+     * styles listed for the {@link #iterator(Calendar, int)} method.
+     * @return the date iterator
+     * @throws IllegalArgumentException if the date
+     *  is <code>null</code>
+     * @throws ClassCastException if the object type is
+     *  not a <code>Date</code> or <code>Calendar</code>
+     */
+    public static Iterator iterator(Object focus, int rangeStyle) {
+        if (focus == null) {
+            throw new IllegalArgumentException("The date must not be null");
+        }
+        if (focus instanceof Date) {
+            return iterator((Date) focus, rangeStyle);
+        } else if (focus instanceof Calendar) {
+            return iterator((Calendar) focus, rangeStyle);
+        } else {
+            throw new ClassCastException("Could not iterate based on " + focus);
+        }
+    }
+
+    /**
+     * <p>Date iterator.</p>
+     */
+    static class DateIterator implements Iterator {
+        private final Calendar endFinal;
+        private final Calendar spot;
+
+        /**
+         * Constructs a DateIterator that ranges from one date to another.
+         *
+         * @param startFinal start date (inclusive)
+         * @param endFinal end date (not inclusive)
+         */
+        DateIterator(Calendar startFinal, Calendar endFinal) {
+            super();
+            this.endFinal = endFinal;
+            spot = startFinal;
+            spot.add(Calendar.DATE, -1);
+        }
+
+        /**
+         * Has the iterator not reached the end date yet?
+         *
+         * @return <code>true</code> if the iterator has yet to reach the end date
+         */
+        public boolean hasNext() {
+            return spot.before(endFinal);
+        }
+
+        /**
+         * Return the next calendar in the iteration
+         *
+         * @return Object calendar for the next date
+         */
+        public Object next() {
+            if (spot.equals(endFinal)) {
+                throw new NoSuchElementException();
+            }
+            spot.add(Calendar.DATE, 1);
+            return spot.clone();
+        }
+
+        /**
+         * Always throws UnsupportedOperationException.
+         *
+         * @throws UnsupportedOperationException
+         * @see java.util.Iterator#remove()
+         */
+        public void remove() {
+            throw new UnsupportedOperationException();
+        }
+    }
+
+    //-------------------------------------------------------------------------
+    // Deprecated int constants
+    // TODO: Remove in 3.0
+
+    /**
+     * Number of milliseconds in a standard second.
+     *
+     * @deprecated Use MILLIS_PER_SECOND. This will be removed in Commons Lang 3.0.
+     */
+    public static final int MILLIS_IN_SECOND = 1000;
+    /**
+     * Number of milliseconds in a standard minute.
+     *
+     * @deprecated Use MILLIS_PER_MINUTE. This will be removed in Commons Lang 3.0.
+     */
+    public static final int MILLIS_IN_MINUTE = 60 * 1000;
+    /**
+     * Number of milliseconds in a standard hour.
+     *
+     * @deprecated Use MILLIS_PER_HOUR. This will be removed in Commons Lang 3.0.
+     */
+    public static final int MILLIS_IN_HOUR = 60 * 60 * 1000;
+    /**
+     * Number of milliseconds in a standard day.
+     *
+     * @deprecated Use MILLIS_PER_DAY. This will be removed in Commons Lang 3.0.
+     */
+    public static final int MILLIS_IN_DAY = 24 * 60 * 60 * 1000;
+
+}

Propchange: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DateUtils.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DateUtils.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DateUtils.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DurationFormatUtils.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DurationFormatUtils.java?rev=571559&view=auto
==============================================================================
--- geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DurationFormatUtils.java (added)
+++ geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DurationFormatUtils.java Fri Aug 31 13:22:41 2007
@@ -0,0 +1,671 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.geronimo.gshell.common;
+
+//
+// NOTE: Copied and massaged from commons-lang 2.3
+//
+
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+
+import org.codehaus.plexus.util.StringUtils;
+
+/**
+ * <p>Duration formatting utilities and constants. The following table describes the tokens
+ * used in the pattern language for formatting. </p>
+ * <table border="1">
+ *  <tr><th>character</th><th>duration element</th></tr>
+ *  <tr><td>y</td><td>years</td></tr>
+ *  <tr><td>M</td><td>months</td></tr>
+ *  <tr><td>d</td><td>days</td></tr>
+ *  <tr><td>H</td><td>hours</td></tr>
+ *  <tr><td>m</td><td>minutes</td></tr>
+ *  <tr><td>s</td><td>seconds</td></tr>
+ *  <tr><td>S</td><td>milliseconds</td></tr>
+ * </table>
+ *
+ * @author Apache Ant - DateUtils
+ * @author <a href="mailto:sbailliez@apache.org">Stephane Bailliez</a>
+ * @author <a href="mailto:stefan.bodewig@epost.de">Stefan Bodewig</a>
+ * @author Stephen Colebourne
+ * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
+ * @since 2.1
+ * @version $Id$
+ */
+public class DurationFormatUtils
+{
+    /**
+     * <p>DurationFormatUtils instances should NOT be constructed in standard programming.</p>
+     *
+     * <p>This constructor is public to permit tools that require a JavaBean instance
+     * to operate.</p>
+     */
+    public DurationFormatUtils() {
+        super();
+    }
+
+    /**
+     * <p>Pattern used with <code>FastDateFormat</code> and <code>SimpleDateFormat</code>
+     * for the ISO8601 period format used in durations.</p>
+     *
+     * @see java.text.SimpleDateFormat
+     */
+    public static final String ISO_EXTENDED_FORMAT_PATTERN = "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.S'S'";
+
+    //-----------------------------------------------------------------------
+    /**
+     * <p>Formats the time gap as a string.</p>
+     *
+     * <p>The format used is ISO8601-like:
+     * <i>H</i>:<i>m</i>:<i>s</i>.<i>S</i>.</p>
+     *
+     * @param durationMillis  the duration to format
+     * @return the time as a String
+     */
+    public static String formatDurationHMS(long durationMillis) {
+        return formatDuration(durationMillis, "H:mm:ss.SSS");
+    }
+
+    /**
+     * <p>Formats the time gap as a string.</p>
+     *
+     * <p>The format used is the ISO8601 period format.</p>
+     *
+     * <p>This method formats durations using the days and lower fields of the
+     * ISO format pattern, such as P7D6TH5M4.321S.</p>
+     *
+     * @param durationMillis  the duration to format
+     * @return the time as a String
+     */
+    public static String formatDurationISO(long durationMillis) {
+        return formatDuration(durationMillis, ISO_EXTENDED_FORMAT_PATTERN, false);
+    }
+
+    /**
+     * <p>Formats the time gap as a string, using the specified format, and padding with zeros and
+     * using the default timezone.</p>
+     *
+     * <p>This method formats durations using the days and lower fields of the
+     * format pattern. Months and larger are not used.</p>
+     *
+     * @param durationMillis  the duration to format
+     * @param format  the way in which to format the duration
+     * @return the time as a String
+     */
+    public static String formatDuration(long durationMillis, String format) {
+        return formatDuration(durationMillis, format, true);
+    }
+
+    /**
+     * <p>Formats the time gap as a string, using the specified format.
+     * Padding the left hand side of numbers with zeroes is optional and
+     * the timezone may be specified.</p>
+     *
+     * <p>This method formats durations using the days and lower fields of the
+     * format pattern. Months and larger are not used.</p>
+     *
+     * @param durationMillis  the duration to format
+     * @param format  the way in which to format the duration
+     * @param padWithZeros  whether to pad the left hand side of numbers with 0's
+     * @return the time as a String
+     */
+    public static String formatDuration(long durationMillis, String format, boolean padWithZeros) {
+
+        Token[] tokens = lexx(format);
+
+        int days         = 0;
+        int hours        = 0;
+        int minutes      = 0;
+        int seconds      = 0;
+        int milliseconds = 0;
+
+        if (Token.containsTokenWithValue(tokens, d) ) {
+            days = (int) (durationMillis / DateUtils.MILLIS_PER_DAY);
+            durationMillis = durationMillis - (days * DateUtils.MILLIS_PER_DAY);
+        }
+        if (Token.containsTokenWithValue(tokens, H) ) {
+            hours = (int) (durationMillis / DateUtils.MILLIS_PER_HOUR);
+            durationMillis = durationMillis - (hours * DateUtils.MILLIS_PER_HOUR);
+        }
+        if (Token.containsTokenWithValue(tokens, m) ) {
+            minutes = (int) (durationMillis / DateUtils.MILLIS_PER_MINUTE);
+            durationMillis = durationMillis - (minutes * DateUtils.MILLIS_PER_MINUTE);
+        }
+        if (Token.containsTokenWithValue(tokens, s) ) {
+            seconds = (int) (durationMillis / DateUtils.MILLIS_PER_SECOND);
+            durationMillis = durationMillis - (seconds * DateUtils.MILLIS_PER_SECOND);
+        }
+        if (Token.containsTokenWithValue(tokens, S) ) {
+            milliseconds = (int) durationMillis;
+        }
+
+        return format(tokens, 0, 0, days, hours, minutes, seconds, milliseconds, padWithZeros);
+    }
+
+    /**
+     * <p>Formats an elapsed time into a plurialization correct string.</p>
+     *
+     * <p>This method formats durations using the days and lower fields of the
+     * format pattern. Months and larger are not used.</p>
+     *
+     * @param durationMillis  the elapsed time to report in milliseconds
+     * @param suppressLeadingZeroElements  suppresses leading 0 elements
+     * @param suppressTrailingZeroElements  suppresses trailing 0 elements
+     * @return the formatted text in days/hours/minutes/seconds
+     */
+    public static String formatDurationWords(
+        long durationMillis,
+        boolean suppressLeadingZeroElements,
+        boolean suppressTrailingZeroElements) {
+
+        // This method is generally replacable by the format method, but
+        // there are a series of tweaks and special cases that require
+        // trickery to replicate.
+        String duration = formatDuration(durationMillis, "d' days 'H' hours 'm' minutes 's' seconds'");
+        if (suppressLeadingZeroElements) {
+            // this is a temporary marker on the front. Like ^ in regexp.
+            duration = " " + duration;
+            String tmp = StringUtils.replaceOnce(duration, " 0 days", "");
+            if (tmp.length() != duration.length()) {
+                duration = tmp;
+                tmp = StringUtils.replaceOnce(duration, " 0 hours", "");
+                if (tmp.length() != duration.length()) {
+                    duration = tmp;
+                    tmp = StringUtils.replaceOnce(duration, " 0 minutes", "");
+                    duration = tmp;
+                    if (tmp.length() != duration.length()) {
+                        duration = StringUtils.replaceOnce(tmp, " 0 seconds", "");
+                    }
+                }
+            }
+            if (duration.length() != 0) {
+                // strip the space off again
+                duration = duration.substring(1);
+            }
+        }
+        if (suppressTrailingZeroElements) {
+            String tmp = StringUtils.replaceOnce(duration, " 0 seconds", "");
+            if (tmp.length() != duration.length()) {
+                duration = tmp;
+                tmp = StringUtils.replaceOnce(duration, " 0 minutes", "");
+                if (tmp.length() != duration.length()) {
+                    duration = tmp;
+                    tmp = StringUtils.replaceOnce(duration, " 0 hours", "");
+                    if (tmp.length() != duration.length()) {
+                        duration = StringUtils.replaceOnce(tmp, " 0 days", "");
+                    }
+                }
+            }
+        }
+        // handle plurals
+        duration = " " + duration;
+        duration = StringUtils.replaceOnce(duration, " 1 seconds", " 1 second");
+        duration = StringUtils.replaceOnce(duration, " 1 minutes", " 1 minute");
+        duration = StringUtils.replaceOnce(duration, " 1 hours", " 1 hour");
+        duration = StringUtils.replaceOnce(duration, " 1 days", " 1 day");
+        return duration.trim();
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * <p>Formats the time gap as a string.</p>
+     *
+     * <p>The format used is the ISO8601 period format.</p>
+     *
+     * @param startMillis  the start of the duration to format
+     * @param endMillis  the end of the duration to format
+     * @return the time as a String
+     */
+    public static String formatPeriodISO(long startMillis, long endMillis) {
+        return formatPeriod(startMillis, endMillis, ISO_EXTENDED_FORMAT_PATTERN, false, TimeZone.getDefault());
+    }
+
+    /**
+     * <p>Formats the time gap as a string, using the specified format.
+     * Padding the left hand side of numbers with zeroes is optional.
+     *
+     * @param startMillis  the start of the duration
+     * @param endMillis  the end of the duration
+     * @param format  the way in which to format the duration
+     * @return the time as a String
+     */
+    public static String formatPeriod(long startMillis, long endMillis, String format) {
+        return formatPeriod(startMillis, endMillis, format, true, TimeZone.getDefault());
+    }
+
+    /**
+     * <p>Formats the time gap as a string, using the specified format.
+     * Padding the left hand side of numbers with zeroes is optional and
+     * the timezone may be specified. </p>
+     *
+     * <p>When calculating the difference between months/days, it chooses to
+     * calculate months first. So when working out the number of months and
+     * days between January 15th and March 10th, it choose 1 month and
+     * 23 days gained by choosing January->February = 1 month and then
+     * calculating days forwards, and not the 1 month and 26 days gained by
+     * choosing March -> February = 1 month and then calculating days
+     * backwards. </p>
+     *
+     * <p>For more control, the <a href="http://joda-time.sf.net/">Joda-Time</a>
+     * library is recommended.</p>
+     *
+     * @param startMillis  the start of the duration
+     * @param endMillis  the end of the duration
+     * @param format  the way in which to format the duration
+     * @param padWithZeros whether to pad the left hand side of numbers with 0's
+     * @param timezone the millis are defined in
+     * @return the time as a String
+     */
+    public static String formatPeriod(long startMillis, long endMillis, String format, boolean padWithZeros,
+            TimeZone timezone) {
+
+        // Used to optimise for differences under 28 days and
+        // called formatDuration(millis, format); however this did not work
+        // over leap years.
+        // TODO: Compare performance to see if anything was lost by
+        // losing this optimisation.
+
+        Token[] tokens = lexx(format);
+
+        // timezones get funky around 0, so normalizing everything to GMT
+        // stops the hours being off
+        Calendar start = Calendar.getInstance(timezone);
+        start.setTime(new Date(startMillis));
+        Calendar end = Calendar.getInstance(timezone);
+        end.setTime(new Date(endMillis));
+
+        // initial estimates
+        int milliseconds = end.get(Calendar.MILLISECOND) - start.get(Calendar.MILLISECOND);
+        int seconds = end.get(Calendar.SECOND) - start.get(Calendar.SECOND);
+        int minutes = end.get(Calendar.MINUTE) - start.get(Calendar.MINUTE);
+        int hours = end.get(Calendar.HOUR_OF_DAY) - start.get(Calendar.HOUR_OF_DAY);
+        int days = end.get(Calendar.DAY_OF_MONTH) - start.get(Calendar.DAY_OF_MONTH);
+        int months = end.get(Calendar.MONTH) - start.get(Calendar.MONTH);
+        int years = end.get(Calendar.YEAR) - start.get(Calendar.YEAR);
+
+        // each initial estimate is adjusted in case it is under 0
+        while (milliseconds < 0) {
+            milliseconds += 1000;
+            seconds -= 1;
+        }
+        while (seconds < 0) {
+            seconds += 60;
+            minutes -= 1;
+        }
+        while (minutes < 0) {
+            minutes += 60;
+            hours -= 1;
+        }
+        while (hours < 0) {
+            hours += 24;
+            days -= 1;
+        }
+
+        if (Token.containsTokenWithValue(tokens, M)) {
+            while (days < 0) {
+                days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
+                months -= 1;
+                start.add(Calendar.MONTH, 1);
+            }
+
+            while (months < 0) {
+                months += 12;
+                years -= 1;
+            }
+
+            if (!Token.containsTokenWithValue(tokens, y) && years != 0) {
+                while (years != 0) {
+                    months += 12 * years;
+                    years = 0;
+                }
+            }
+        } else {
+            // there are no M's in the format string
+
+            if( !Token.containsTokenWithValue(tokens, y) ) {
+                int target = end.get(Calendar.YEAR);
+                if (months < 0) {
+                    // target is end-year -1
+                    target -= 1;
+                }
+
+                while ( (start.get(Calendar.YEAR) != target)) {
+                    days += start.getActualMaximum(Calendar.DAY_OF_YEAR) - start.get(Calendar.DAY_OF_YEAR);
+
+                    // Not sure I grok why this is needed, but the brutal tests show it is
+                    if(start instanceof GregorianCalendar) {
+                        if( (start.get(Calendar.MONTH) == Calendar.FEBRUARY) &&
+                            (start.get(Calendar.DAY_OF_MONTH) == 29 ) )
+                        {
+                            days += 1;
+                        }
+                    }
+
+                    start.add(Calendar.YEAR, 1);
+
+                    days += start.get(Calendar.DAY_OF_YEAR);
+                }
+
+                years = 0;
+            }
+
+            while( start.get(Calendar.MONTH) != end.get(Calendar.MONTH) ) {
+                days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
+                start.add(Calendar.MONTH, 1);
+            }
+
+            months = 0;
+
+            while (days < 0) {
+                days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
+                months -= 1;
+                start.add(Calendar.MONTH, 1);
+            }
+
+        }
+
+        // The rest of this code adds in values that
+        // aren't requested. This allows the user to ask for the
+        // number of months and get the real count and not just 0->11.
+
+        if (!Token.containsTokenWithValue(tokens, d)) {
+            hours += 24 * days;
+            days = 0;
+        }
+        if (!Token.containsTokenWithValue(tokens, H)) {
+            minutes += 60 * hours;
+            hours = 0;
+        }
+        if (!Token.containsTokenWithValue(tokens, m)) {
+            seconds += 60 * minutes;
+            minutes = 0;
+        }
+        if (!Token.containsTokenWithValue(tokens, s)) {
+            milliseconds += 1000 * seconds;
+            seconds = 0;
+        }
+
+        return format(tokens, years, months, days, hours, minutes, seconds, milliseconds, padWithZeros);
+    }
+
+    //-----------------------------------------------------------------------
+    /**
+     * <p>The internal method to do the formatting.</p>
+     *
+     * @param tokens  the tokens
+     * @param years  the number of years
+     * @param months  the number of months
+     * @param days  the number of days
+     * @param hours  the number of hours
+     * @param minutes  the number of minutes
+     * @param seconds  the number of seconds
+     * @param milliseconds  the number of millis
+     * @param padWithZeros  whether to pad
+     * @return the formatted string
+     */
+    static String format(Token[] tokens, int years, int months, int days, int hours, int minutes, int seconds,
+            int milliseconds, boolean padWithZeros) {
+        StringBuffer buffer = new StringBuffer();
+        boolean lastOutputSeconds = false;
+        int sz = tokens.length;
+        for (int i = 0; i < sz; i++) {
+            Token token = tokens[i];
+            Object value = token.getValue();
+            int count = token.getCount();
+            if (value instanceof StringBuffer) {
+                buffer.append(value.toString());
+            } else {
+                if (value == y) {
+                    buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(years), count, "0") : Integer
+                            .toString(years));
+                    lastOutputSeconds = false;
+                } else if (value == M) {
+                    buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(months), count, "0") : Integer
+                            .toString(months));
+                    lastOutputSeconds = false;
+                } else if (value == d) {
+                    buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(days), count, "0") : Integer
+                            .toString(days));
+                    lastOutputSeconds = false;
+                } else if (value == H) {
+                    buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(hours), count, "0") : Integer
+                            .toString(hours));
+                    lastOutputSeconds = false;
+                } else if (value == m) {
+                    buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(minutes), count, "0") : Integer
+                            .toString(minutes));
+                    lastOutputSeconds = false;
+                } else if (value == s) {
+                    buffer.append(padWithZeros ? StringUtils.leftPad(Integer.toString(seconds), count, "0") : Integer
+                            .toString(seconds));
+                    lastOutputSeconds = true;
+                } else if (value == S) {
+                    if (lastOutputSeconds) {
+                        milliseconds += 1000;
+                        String str = padWithZeros
+                                ? StringUtils.leftPad(Integer.toString(milliseconds), count, "0")
+                                : Integer.toString(milliseconds);
+                        buffer.append(str.substring(1));
+                    } else {
+                        buffer.append(padWithZeros
+                                ? StringUtils.leftPad(Integer.toString(milliseconds), count, "0")
+                                : Integer.toString(milliseconds));
+                    }
+                    lastOutputSeconds = false;
+                }
+            }
+        }
+        return buffer.toString();
+    }
+
+    static final Object y = "y";
+    static final Object M = "M";
+    static final Object d = "d";
+    static final Object H = "H";
+    static final Object m = "m";
+    static final Object s = "s";
+    static final Object S = "S";
+
+    /**
+     * Parses a classic date format string into Tokens
+     *
+     * @param format to parse
+     * @return Token[] of tokens
+     */
+    static Token[] lexx(String format) {
+        char[] array = format.toCharArray();
+        ArrayList list = new ArrayList(array.length);
+
+        boolean inLiteral = false;
+        StringBuffer buffer = null;
+        Token previous = null;
+        int sz = array.length;
+        for(int i=0; i<sz; i++) {
+            char ch = array[i];
+            if(inLiteral && ch != '\'') {
+                buffer.append(ch);
+                continue;
+            }
+            Object value = null;
+            switch(ch) {
+                // TODO: Need to handle escaping of '
+                case '\'' :
+                  if(inLiteral) {
+                      buffer = null;
+                      inLiteral = false;
+                  } else {
+                      buffer = new StringBuffer();
+                      list.add(new Token(buffer));
+                      inLiteral = true;
+                  }
+                  break;
+                case 'y'  : value = y; break;
+                case 'M'  : value = M; break;
+                case 'd'  : value = d; break;
+                case 'H'  : value = H; break;
+                case 'm'  : value = m; break;
+                case 's'  : value = s; break;
+                case 'S'  : value = S; break;
+                default   :
+                  if(buffer == null) {
+                      buffer = new StringBuffer();
+                      list.add(new Token(buffer));
+                  }
+                  buffer.append(ch);
+            }
+
+            if(value != null) {
+                if(previous != null && previous.getValue() == value) {
+                    previous.increment();
+                } else {
+                    Token token = new Token(value);
+                    list.add(token);
+                    previous = token;
+                }
+                buffer = null;
+            }
+        }
+        return (Token[]) list.toArray( new Token[list.size()] );
+    }
+
+    /**
+     * Element that is parsed from the format pattern.
+     */
+    static class Token {
+
+        /**
+         * Helper method to determine if a set of tokens contain a value
+         *
+         * @param tokens set to look in
+         * @param value to look for
+         * @return boolean <code>true</code> if contained
+         */
+        static boolean containsTokenWithValue(Token[] tokens, Object value) {
+            int sz = tokens.length;
+            for (int i = 0; i < sz; i++) {
+                if (tokens[i].getValue() == value) {
+                    return true;
+                }
+            }
+            return false;
+        }
+
+        private Object value;
+        private int count;
+
+        /**
+         * Wraps a token around a value. A value would be something like a 'Y'.
+         *
+         * @param value to wrap
+         */
+        Token(Object value) {
+            this.value = value;
+            this.count = 1;
+        }
+
+        /**
+         * Wraps a token around a repeated number of a value, for example it would
+         * store 'yyyy' as a value for y and a count of 4.
+         *
+         * @param value to wrap
+         * @param count to wrap
+         */
+        Token(Object value, int count) {
+            this.value = value;
+            this.count = count;
+        }
+
+        /**
+         * Adds another one of the value
+         */
+        void increment() {
+            count++;
+        }
+
+        /**
+         * Gets the current number of values represented
+         *
+         * @return int number of values represented
+         */
+        int getCount() {
+            return count;
+        }
+
+        /**
+         * Gets the particular value this token represents.
+         *
+         * @return Object value
+         */
+        Object getValue() {
+            return value;
+        }
+
+        /**
+         * Supports equality of this Token to another Token.
+         *
+         * @param obj2 Object to consider equality of
+         * @return boolean <code>true</code> if equal
+         */
+        public boolean equals(Object obj2) {
+            if (obj2 instanceof Token) {
+                Token tok2 = (Token) obj2;
+                if (this.value.getClass() != tok2.value.getClass()) {
+                    return false;
+                }
+                if (this.count != tok2.count) {
+                    return false;
+                }
+                if (this.value instanceof StringBuffer) {
+                    return this.value.toString().equals(tok2.value.toString());
+                } else if (this.value instanceof Number) {
+                    return this.value.equals(tok2.value);
+                } else {
+                    return this.value == tok2.value;
+                }
+            }
+            return false;
+        }
+
+        /**
+         * Returns a hashcode for the token equal to the
+         * hashcode for the token's value. Thus 'TT' and 'TTTT'
+         * will have the same hashcode.
+         *
+         * @return The hashcode for the token
+         */
+        public int hashCode() {
+            return this.value.hashCode();
+        }
+
+        /**
+         * Represents this token as a String.
+         *
+         * @return String representation of the token
+         */
+        public String toString() {
+            return StringUtils.repeat(this.value.toString(), this.count);
+        }
+    }
+
+}

Propchange: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DurationFormatUtils.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DurationFormatUtils.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/DurationFormatUtils.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Added: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/StopWatch.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/StopWatch.java?rev=571559&view=auto
==============================================================================
--- geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/StopWatch.java (added)
+++ geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/StopWatch.java Fri Aug 31 13:22:41 2007
@@ -0,0 +1,272 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.geronimo.gshell.common;
+
+//
+// NOTE: Copied and massaged from commons-lang 2.3
+//
+
+/**
+ * <p><code>StopWatch</code> provides a convenient API for timings.</p>
+ *
+ * <p>To start the watch, call {@link #start()}. At this point you can:</p>
+ * <ul>
+ *  <li>{@link #split()} the watch to get the time whilst the watch continues in the
+ *   background. {@link #unsplit()} will remove the effect of the split. At this point,
+ *   these three options are available again.</li>
+ *  <li>{@link #suspend()} the watch to pause it. {@link #resume()} allows the watch
+ *   to continue. Any time between the suspend and resume will not be counted in
+ *   the total. At this point, these three options are available again.</li>
+ *  <li>{@link #stop()} the watch to complete the timing session.</li>
+ * </ul>
+ *
+ * <p>It is intended that the output methods {@link #toString()} and {@link #getTime()}
+ * should only be called after stop, split or suspend, however a suitable result will
+ * be returned at other points.</p>
+ *
+ * <p>NOTE: As from v2.1, the methods protect against inappropriate calls.
+ * Thus you cannot now call stop before start, resume before suspend or
+ * unsplit before split.</p>
+ *
+ * <p>1. split(), suspend(), or stop() cannot be invoked twice<br />
+ * 2. unsplit() may only be called if the watch has been split()<br />
+ * 3. resume() may only be called if the watch has been suspend()<br />
+ * 4. start() cannot be called twice without calling reset()</p>
+ *
+ * @author Stephen Colebourne
+ * @since 2.0
+ * @version $Id$
+ */
+public class StopWatch
+{
+    // running states
+    private static final int STATE_UNSTARTED = 0;
+    private static final int STATE_RUNNING   = 1;
+    private static final int STATE_STOPPED   = 2;
+    private static final int STATE_SUSPENDED = 3;
+
+    // split state
+    private static final int STATE_UNSPLIT = 10;
+    private static final int STATE_SPLIT   = 11;
+
+    /**
+     *  The current running state of the StopWatch.
+     */
+    private int runningState = STATE_UNSTARTED;
+
+    /**
+     * Whether the stopwatch has a split time recorded.
+     */
+    private int splitState   = STATE_UNSPLIT;
+
+    /**
+     * The start time.
+     */
+    private long startTime = -1;
+    /**
+     * The stop time.
+     */
+    private long stopTime = -1;
+
+    /**
+     * <p>Constructor.</p>
+     */
+    public StopWatch() {
+        super();
+    }
+
+    /**
+     * <p>Start the stopwatch.</p>
+     *
+     * <p>This method starts a new timing session, clearing any previous values.</p>
+     *
+     * @throws IllegalStateException if the StopWatch is already running.
+     */
+    public void start() {
+        if(this.runningState == STATE_STOPPED) {
+            throw new IllegalStateException("Stopwatch must be reset before being restarted. ");
+        }
+        if(this.runningState != STATE_UNSTARTED) {
+            throw new IllegalStateException("Stopwatch already started. ");
+        }
+        stopTime = -1;
+        startTime = System.currentTimeMillis();
+        this.runningState = STATE_RUNNING;
+    }
+
+    /**
+     * <p>Stop the stopwatch.</p>
+     *
+     * <p>This method ends a new timing session, allowing the time to be retrieved.</p>
+     *
+     * @throws IllegalStateException if the StopWatch is not running.
+     */
+    public void stop() {
+        if(this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) {
+            throw new IllegalStateException("Stopwatch is not running. ");
+        }
+        if(this.runningState == STATE_RUNNING) {
+            stopTime = System.currentTimeMillis();
+        }
+        this.runningState = STATE_STOPPED;
+    }
+
+    /**
+     * <p>Resets the stopwatch. Stops it if need be. </p>
+     *
+     * <p>This method clears the internal values to allow the object to be reused.</p>
+     */
+    public void reset() {
+        this.runningState = STATE_UNSTARTED;
+        this.splitState   = STATE_UNSPLIT;
+        startTime = -1;
+        stopTime = -1;
+    }
+
+    /**
+     * <p>Split the time.</p>
+     *
+     * <p>This method sets the stop time of the watch to allow a time to be extracted.
+     * The start time is unaffected, enabling {@link #unsplit()} to continue the
+     * timing from the original start point.</p>
+     *
+     * @throws IllegalStateException if the StopWatch is not running.
+     */
+    public void split() {
+        if(this.runningState != STATE_RUNNING) {
+            throw new IllegalStateException("Stopwatch is not running. ");
+        }
+        stopTime = System.currentTimeMillis();
+        this.splitState = STATE_SPLIT;
+    }
+
+    /**
+     * <p>Remove a split.</p>
+     *
+     * <p>This method clears the stop time. The start time is unaffected, enabling
+     * timing from the original start point to continue.</p>
+     *
+     * @throws IllegalStateException if the StopWatch has not been split.
+     */
+    public void unsplit() {
+        if(this.splitState != STATE_SPLIT) {
+            throw new IllegalStateException("Stopwatch has not been split. ");
+        }
+        stopTime = -1;
+        this.splitState = STATE_UNSPLIT;
+    }
+
+    /**
+     * <p>Suspend the stopwatch for later resumption.</p>
+     *
+     * <p>This method suspends the watch until it is resumed. The watch will not include
+     * time between the suspend and resume calls in the total time.</p>
+     *
+     * @throws IllegalStateException if the StopWatch is not currently running.
+     */
+    public void suspend() {
+        if(this.runningState != STATE_RUNNING) {
+            throw new IllegalStateException("Stopwatch must be running to suspend. ");
+        }
+        stopTime = System.currentTimeMillis();
+        this.runningState = STATE_SUSPENDED;
+    }
+
+    /**
+     * <p>Resume the stopwatch after a suspend.</p>
+     *
+     * <p>This method resumes the watch after it was suspended. The watch will not include
+     * time between the suspend and resume calls in the total time.</p>
+     *
+     * @throws IllegalStateException if the StopWatch has not been suspended.
+     */
+    public void resume() {
+        if(this.runningState != STATE_SUSPENDED) {
+            throw new IllegalStateException("Stopwatch must be suspended to resume. ");
+        }
+        startTime += (System.currentTimeMillis() - stopTime);
+        stopTime = -1;
+        this.runningState = STATE_RUNNING;
+    }
+
+    /**
+     * <p>Get the time on the stopwatch.</p>
+     *
+     * <p>This is either the time between the start and the moment this method
+     * is called, or the amount of time between start and stop.</p>
+     *
+     * @return the time in milliseconds
+     */
+    public long getTime() {
+        if(this.runningState == STATE_STOPPED || this.runningState == STATE_SUSPENDED) {
+            return this.stopTime - this.startTime;
+        } else
+        if(this.runningState == STATE_UNSTARTED) {
+            return 0;
+        } else
+        if(this.runningState == STATE_RUNNING) {
+            return System.currentTimeMillis() - this.startTime;
+        }
+        throw new RuntimeException("Illegal running state has occured. ");
+    }
+
+    /**
+     * <p>Get the split time on the stopwatch.</p>
+     *
+     * <p>This is the time between start and latest split. </p>
+     *
+     * @return the split time in milliseconds
+     *
+     * @throws IllegalStateException if the StopWatch has not yet been split.
+     * @since 2.1
+     */
+    public long getSplitTime() {
+        if(this.splitState != STATE_SPLIT) {
+            throw new IllegalStateException("Stopwatch must be split to get the split time. ");
+        }
+        return this.stopTime - this.startTime;
+    }
+
+    /**
+     * <p>Gets a summary of the time that the stopwatch recorded as a string.</p>
+     *
+     * <p>The format used is ISO8601-like,
+     * <i>hours</i>:<i>minutes</i>:<i>seconds</i>.<i>milliseconds</i>.</p>
+     *
+     * @return the time as a String
+     */
+    public String toString() {
+        return DurationFormatUtils.formatDurationHMS(getTime());
+    }
+
+    /**
+     * <p>Gets a summary of the split time that the stopwatch recorded as a string.</p>
+     *
+     * <p>The format used is ISO8601-like,
+     * <i>hours</i>:<i>minutes</i>:<i>seconds</i>.<i>milliseconds</i>.</p>
+     *
+     * @return the split time as a String
+     * @since 2.1
+     */
+    public String toSplitString() {
+        return DurationFormatUtils.formatDurationHMS(getSplitTime());
+    }
+
+}
\ No newline at end of file

Propchange: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/StopWatch.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/StopWatch.java
------------------------------------------------------------------------------
    svn:keywords = Date Author Id Revision HeadURL

Propchange: geronimo/sandbox/gshell/trunk/gshell-common/src/main/java/org/apache/geronimo/gshell/common/StopWatch.java
------------------------------------------------------------------------------
    svn:mime-type = text/plain

Modified: geronimo/sandbox/gshell/trunk/gshell-core/pom.xml
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gshell/trunk/gshell-core/pom.xml?rev=571559&r1=571558&r2=571559&view=diff
==============================================================================
--- geronimo/sandbox/gshell/trunk/gshell-core/pom.xml (original)
+++ geronimo/sandbox/gshell/trunk/gshell-core/pom.xml Fri Aug 31 13:22:41 2007
@@ -39,23 +39,17 @@
             <artifactId>gshell-api</artifactId>
             <version>${pom.version}</version>
         </dependency>
-
+        
         <dependency>
             <groupId>jline</groupId>
             <artifactId>jline</artifactId>
         </dependency>
-
-        <dependency>
-            <groupId>org.apache.geronimo.gshell</groupId>
-            <artifactId>gshell-diet-plexus-utils</artifactId>
-            <version>${pom.version}</version>
-        </dependency>
         
         <dependency>
             <groupId>org.codehaus.plexus</groupId>
             <artifactId>plexus-container-default</artifactId>
         </dependency>
-
+        
         <dependency>
             <groupId>org.codehaus.plexus</groupId>
             <artifactId>plexus-expression-evaluator</artifactId>

Modified: geronimo/sandbox/gshell/trunk/gshell-core/src/main/java/org/apache/geronimo/gshell/Shell.java
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gshell/trunk/gshell-core/src/main/java/org/apache/geronimo/gshell/Shell.java?rev=571559&r1=571558&r2=571559&view=diff
==============================================================================
--- geronimo/sandbox/gshell/trunk/gshell-core/src/main/java/org/apache/geronimo/gshell/Shell.java (original)
+++ geronimo/sandbox/gshell/trunk/gshell-core/src/main/java/org/apache/geronimo/gshell/Shell.java Fri Aug 31 13:22:41 2007
@@ -21,7 +21,7 @@
 
 import java.util.Iterator;
 
-import org.apache.commons.lang.time.StopWatch;
+import org.apache.geronimo.gshell.common.StopWatch;
 import org.apache.geronimo.gshell.command.Command;
 import org.apache.geronimo.gshell.command.CommandContext;
 import org.apache.geronimo.gshell.command.CommandManager;

Modified: geronimo/sandbox/gshell/trunk/gshell-diet/pom.xml
URL: http://svn.apache.org/viewvc/geronimo/sandbox/gshell/trunk/gshell-diet/pom.xml?rev=571559&r1=571558&r2=571559&view=diff
==============================================================================
--- geronimo/sandbox/gshell/trunk/gshell-diet/pom.xml (original)
+++ geronimo/sandbox/gshell/trunk/gshell-diet/pom.xml Fri Aug 31 13:22:41 2007
@@ -39,7 +39,6 @@
     </description>
     
     <modules>
-        <module>gshell-diet-commons-lang</module>
         <module>gshell-diet-plexus-utils</module>
         <module>gshell-diet-log4j</module>
     </modules>



Mime
View raw message