001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
025 * in the United States and other countries.]
026 *
027 * ---------
028 * Week.java
029 * ---------
030 * (C) Copyright 2001-2008, by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Aimin Han;
034 *
035 * Changes
036 * -------
037 * 11-Oct-2001 : Version 1 (DG);
038 * 18-Dec-2001 : Changed order of parameters in constructor (DG);
039 * 19-Dec-2001 : Added a new constructor as suggested by Paul English (DG);
040 * 29-Jan-2002 : Worked on the parseWeek() method (DG);
041 * 13-Feb-2002 : Fixed bug in Week(Date) constructor (DG);
042 * 26-Feb-2002 : Changed getStart(), getMiddle() and getEnd() methods to
043 *               evaluate with reference to a particular time zone (DG);
044 * 05-Apr-2002 : Reinstated this class to the JCommon library (DG);
045 * 24-Jun-2002 : Removed unnecessary main method (DG);
046 * 10-Sep-2002 : Added getSerialIndex() method (DG);
047 * 06-Oct-2002 : Fixed errors reported by Checkstyle (DG);
048 * 18-Oct-2002 : Changed to observe 52 or 53 weeks per year, consistent with
049 *               GregorianCalendar. Thanks to Aimin Han for the code (DG);
050 * 02-Jan-2003 : Removed debug code (DG);
051 * 13-Mar-2003 : Moved to com.jrefinery.data.time package, and implemented
052 *               Serializable (DG);
053 * 21-Oct-2003 : Added hashCode() method (DG);
054 * 24-May-2004 : Modified getFirstMillisecond() and getLastMillisecond() to
055 *               take account of firstDayOfWeek setting in Java's Calendar
056 *               class (DG);
057 * 30-Sep-2004 : Replaced getTime().getTime() with getTimeInMillis() (DG);
058 * 04-Nov-2004 : Reverted change of 30-Sep-2004, because it won't work for
059 *               JDK 1.3 (DG);
060 * ------------- JFREECHART 1.0.x ---------------------------------------------
061 * 06-Mar-2006 : Fix for bug 1448828, incorrect calculation of week and year
062 *               for the first few days of some years (DG);
063 * 05-Oct-2006 : Updated API docs (DG);
064 * 06-Oct-2006 : Refactored to cache first and last millisecond values (DG);
065 * 09-Jan-2007 : Fixed bug in next() (DG);
066 * 28-Aug-2007 : Added new constructor to avoid problem in creating new
067 *               instances (DG);
068 * 19-Dec-2007 : Fixed bug in deprecated constructor (DG);
069 * 16-Sep-2008 : Deprecated DEFAULT_TIME_ZONE (DG);
070 *
071 */
072
073package org.jfree.data.time;
074
075import java.io.Serializable;
076import java.util.Calendar;
077import java.util.Date;
078import java.util.Locale;
079import java.util.TimeZone;
080
081/**
082 * A calendar week.  All years are considered to have 53 weeks, numbered from 1
083 * to 53, although in many cases the 53rd week is empty.  Most of the time, the
084 * 1st week of the year *begins* in the previous calendar year, but it always
085 * finishes in the current year (this behaviour matches the workings of the
086 * <code>GregorianCalendar</code> class).
087 * <P>
088 * This class is immutable, which is a requirement for all
089 * {@link RegularTimePeriod} subclasses.
090 */
091public class Week extends RegularTimePeriod implements Serializable {
092
093    /** For serialization. */
094    private static final long serialVersionUID = 1856387786939865061L;
095
096    /** Constant for the first week in the year. */
097    public static final int FIRST_WEEK_IN_YEAR = 1;
098
099    /** Constant for the last week in the year. */
100    public static final int LAST_WEEK_IN_YEAR = 53;
101
102    /** The year in which the week falls. */
103    private short year;
104
105    /** The week (1-53). */
106    private byte week;
107
108    /** The first millisecond. */
109    private long firstMillisecond;
110
111    /** The last millisecond. */
112    private long lastMillisecond;
113
114    /**
115     * Creates a new time period for the week in which the current system
116     * date/time falls.
117     */
118    public Week() {
119        this(new Date());
120    }
121
122    /**
123     * Creates a time period representing the week in the specified year.
124     *
125     * @param week  the week (1 to 53).
126     * @param year  the year (1900 to 9999).
127     */
128    public Week(int week, int year) {
129        if ((week < FIRST_WEEK_IN_YEAR) && (week > LAST_WEEK_IN_YEAR)) {
130            throw new IllegalArgumentException(
131                    "The 'week' argument must be in the range 1 - 53.");
132        }
133        this.week = (byte) week;
134        this.year = (short) year;
135        peg(Calendar.getInstance());
136    }
137
138    /**
139     * Creates a time period representing the week in the specified year.
140     *
141     * @param week  the week (1 to 53).
142     * @param year  the year (1900 to 9999).
143     */
144    public Week(int week, Year year) {
145        if ((week < FIRST_WEEK_IN_YEAR) && (week > LAST_WEEK_IN_YEAR)) {
146            throw new IllegalArgumentException(
147                    "The 'week' argument must be in the range 1 - 53.");
148        }
149        this.week = (byte) week;
150        this.year = (short) year.getYear();
151        peg(Calendar.getInstance());
152   }
153
154    /**
155     * Creates a time period for the week in which the specified date/time
156     * falls, using the default time zone and locale (the locale can affect the
157     * day-of-the-week that marks the beginning of the week, as well as the
158     * minimal number of days in the first week of the year).
159     *
160     * @param time  the time (<code>null</code> not permitted).
161     *
162     * @see #Week(Date, TimeZone, Locale)
163     */
164    public Week(Date time) {
165        // defer argument checking...
166        this(time, TimeZone.getDefault(), Locale.getDefault());
167    }
168
169    /**
170     * Creates a time period for the week in which the specified date/time
171     * falls, calculated relative to the specified time zone.
172     *
173     * @param time  the date/time (<code>null</code> not permitted).
174     * @param zone  the time zone (<code>null</code> not permitted).
175     *
176     * @deprecated As of 1.0.7, use {@link #Week(Date, TimeZone, Locale)}.
177     */
178    public Week(Date time, TimeZone zone) {
179        // defer argument checking...
180        this(time, zone, Locale.getDefault());
181    }
182
183    /**
184     * Creates a time period for the week in which the specified date/time
185     * falls, calculated relative to the specified time zone.
186     *
187     * @param time  the date/time (<code>null</code> not permitted).
188     * @param zone  the time zone (<code>null</code> not permitted).
189     * @param locale  the locale (<code>null</code> not permitted).
190     *
191     * @since 1.0.7
192     */
193    public Week(Date time, TimeZone zone, Locale locale) {
194        if (time == null) {
195            throw new IllegalArgumentException("Null 'time' argument.");
196        }
197        if (zone == null) {
198            throw new IllegalArgumentException("Null 'zone' argument.");
199        }
200        if (locale == null) {
201            throw new IllegalArgumentException("Null 'locale' argument.");
202        }
203        Calendar calendar = Calendar.getInstance(zone, locale);
204        calendar.setTime(time);
205
206        // sometimes the last few days of the year are considered to fall in
207        // the *first* week of the following year.  Refer to the Javadocs for
208        // GregorianCalendar.
209        int tempWeek = calendar.get(Calendar.WEEK_OF_YEAR);
210        if (tempWeek == 1
211                && calendar.get(Calendar.MONTH) == Calendar.DECEMBER) {
212            this.week = 1;
213            this.year = (short) (calendar.get(Calendar.YEAR) + 1);
214        }
215        else {
216            this.week = (byte) Math.min(tempWeek, LAST_WEEK_IN_YEAR);
217            int yyyy = calendar.get(Calendar.YEAR);
218            // alternatively, sometimes the first few days of the year are
219            // considered to fall in the *last* week of the previous year...
220            if (calendar.get(Calendar.MONTH) == Calendar.JANUARY
221                    && this.week >= 52) {
222                yyyy--;
223            }
224            this.year = (short) yyyy;
225        }
226        peg(calendar);
227    }
228
229    /**
230     * Returns the year in which the week falls.
231     *
232     * @return The year (never <code>null</code>).
233     */
234    public Year getYear() {
235        return new Year(this.year);
236    }
237
238    /**
239     * Returns the year in which the week falls, as an integer value.
240     *
241     * @return The year.
242     */
243    public int getYearValue() {
244        return this.year;
245    }
246
247    /**
248     * Returns the week.
249     *
250     * @return The week.
251     */
252    public int getWeek() {
253        return this.week;
254    }
255
256    /**
257     * Returns the first millisecond of the week.  This will be determined
258     * relative to the time zone specified in the constructor, or in the
259     * calendar instance passed in the most recent call to the
260     * {@link #peg(Calendar)} method.
261     *
262     * @return The first millisecond of the week.
263     *
264     * @see #getLastMillisecond()
265     */
266    public long getFirstMillisecond() {
267        return this.firstMillisecond;
268    }
269
270    /**
271     * Returns the last millisecond of the week.  This will be
272     * determined relative to the time zone specified in the constructor, or
273     * in the calendar instance passed in the most recent call to the
274     * {@link #peg(Calendar)} method.
275     *
276     * @return The last millisecond of the week.
277     *
278     * @see #getFirstMillisecond()
279     */
280    public long getLastMillisecond() {
281        return this.lastMillisecond;
282    }
283
284    /**
285     * Recalculates the start date/time and end date/time for this time period
286     * relative to the supplied calendar (which incorporates a time zone).
287     *
288     * @param calendar  the calendar (<code>null</code> not permitted).
289     *
290     * @since 1.0.3
291     */
292    public void peg(Calendar calendar) {
293        this.firstMillisecond = getFirstMillisecond(calendar);
294        this.lastMillisecond = getLastMillisecond(calendar);
295    }
296
297    /**
298     * Returns the week preceding this one.  This method will return
299     * <code>null</code> for some lower limit on the range of weeks (currently
300     * week 1, 1900).  For week 1 of any year, the previous week is always week
301     * 53, but week 53 may not contain any days (you should check for this).
302     *
303     * @return The preceding week (possibly <code>null</code>).
304     */
305    public RegularTimePeriod previous() {
306
307        Week result;
308        if (this.week != FIRST_WEEK_IN_YEAR) {
309            result = new Week(this.week - 1, this.year);
310        }
311        else {
312            // we need to work out if the previous year has 52 or 53 weeks...
313            if (this.year > 1900) {
314                int yy = this.year - 1;
315                Calendar prevYearCalendar = Calendar.getInstance();
316                prevYearCalendar.set(yy, Calendar.DECEMBER, 31);
317                result = new Week(prevYearCalendar.getActualMaximum(
318                        Calendar.WEEK_OF_YEAR), yy);
319            }
320            else {
321                result = null;
322            }
323        }
324        return result;
325
326    }
327
328    /**
329     * Returns the week following this one.  This method will return
330     * <code>null</code> for some upper limit on the range of weeks (currently
331     * week 53, 9999).  For week 52 of any year, the following week is always
332     * week 53, but week 53 may not contain any days (you should check for
333     * this).
334     *
335     * @return The following week (possibly <code>null</code>).
336     */
337    public RegularTimePeriod next() {
338
339        Week result;
340        if (this.week < 52) {
341            result = new Week(this.week + 1, this.year);
342        }
343        else {
344            Calendar calendar = Calendar.getInstance();
345            calendar.set(this.year, Calendar.DECEMBER, 31);
346            int actualMaxWeek
347                = calendar.getActualMaximum(Calendar.WEEK_OF_YEAR);
348            if (this.week < actualMaxWeek) {
349                result = new Week(this.week + 1, this.year);
350            }
351            else {
352                if (this.year < 9999) {
353                    result = new Week(FIRST_WEEK_IN_YEAR, this.year + 1);
354                }
355                else {
356                    result = null;
357                }
358            }
359        }
360        return result;
361
362    }
363
364    /**
365     * Returns a serial index number for the week.
366     *
367     * @return The serial index number.
368     */
369    public long getSerialIndex() {
370        return this.year * 53L + this.week;
371    }
372
373    /**
374     * Returns the first millisecond of the week, evaluated using the supplied
375     * calendar (which determines the time zone).
376     *
377     * @param calendar  the calendar (<code>null</code> not permitted).
378     *
379     * @return The first millisecond of the week.
380     *
381     * @throws NullPointerException if <code>calendar</code> is
382     *     <code>null</code>.
383     */
384    public long getFirstMillisecond(Calendar calendar) {
385        Calendar c = (Calendar) calendar.clone();
386        c.clear();
387        c.set(Calendar.YEAR, this.year);
388        c.set(Calendar.WEEK_OF_YEAR, this.week);
389        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
390        c.set(Calendar.HOUR, 0);
391        c.set(Calendar.MINUTE, 0);
392        c.set(Calendar.SECOND, 0);
393        c.set(Calendar.MILLISECOND, 0);
394        //return c.getTimeInMillis();  // this won't work for JDK 1.3
395        return c.getTime().getTime();
396    }
397
398    /**
399     * Returns the last millisecond of the week, evaluated using the supplied
400     * calendar (which determines the time zone).
401     *
402     * @param calendar  the calendar (<code>null</code> not permitted).
403     *
404     * @return The last millisecond of the week.
405     *
406     * @throws NullPointerException if <code>calendar</code> is
407     *     <code>null</code>.
408     */
409    public long getLastMillisecond(Calendar calendar) {
410        Calendar c = (Calendar) calendar.clone();
411        c.clear();
412        c.set(Calendar.YEAR, this.year);
413        c.set(Calendar.WEEK_OF_YEAR, this.week + 1);
414        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
415        c.set(Calendar.HOUR, 0);
416        c.set(Calendar.MINUTE, 0);
417        c.set(Calendar.SECOND, 0);
418        c.set(Calendar.MILLISECOND, 0);
419        //return c.getTimeInMillis();  // this won't work for JDK 1.3
420        return c.getTime().getTime() - 1;
421    }
422
423    /**
424     * Returns a string representing the week (e.g. "Week 9, 2002").
425     *
426     * TODO: look at internationalisation.
427     *
428     * @return A string representing the week.
429     */
430    public String toString() {
431        return "Week " + this.week + ", " + this.year;
432    }
433
434    /**
435     * Tests the equality of this Week object to an arbitrary object.  Returns
436     * true if the target is a Week instance representing the same week as this
437     * object.  In all other cases, returns false.
438     *
439     * @param obj  the object (<code>null</code> permitted).
440     *
441     * @return <code>true</code> if week and year of this and object are the
442     *         same.
443     */
444    public boolean equals(Object obj) {
445
446        if (obj == this) {
447            return true;
448        }
449        if (!(obj instanceof Week)) {
450            return false;
451        }
452        Week that = (Week) obj;
453        if (this.week != that.week) {
454            return false;
455        }
456        if (this.year != that.year) {
457            return false;
458        }
459        return true;
460
461    }
462
463    /**
464     * Returns a hash code for this object instance.  The approach described by
465     * Joshua Bloch in "Effective Java" has been used here:
466     * <p>
467     * <code>http://developer.java.sun.com/developer/Books/effectivejava
468     * /Chapter3.pdf</code>
469     *
470     * @return A hash code.
471     */
472    public int hashCode() {
473        int result = 17;
474        result = 37 * result + this.week;
475        result = 37 * result + this.year;
476        return result;
477    }
478
479    /**
480     * Returns an integer indicating the order of this Week object relative to
481     * the specified object:
482     *
483     * negative == before, zero == same, positive == after.
484     *
485     * @param o1  the object to compare.
486     *
487     * @return negative == before, zero == same, positive == after.
488     */
489    public int compareTo(Object o1) {
490
491        int result;
492
493        // CASE 1 : Comparing to another Week object
494        // --------------------------------------------
495        if (o1 instanceof Week) {
496            Week w = (Week) o1;
497            result = this.year - w.getYear().getYear();
498            if (result == 0) {
499                result = this.week - w.getWeek();
500            }
501        }
502
503        // CASE 2 : Comparing to another TimePeriod object
504        // -----------------------------------------------
505        else if (o1 instanceof RegularTimePeriod) {
506            // more difficult case - evaluate later...
507            result = 0;
508        }
509
510        // CASE 3 : Comparing to a non-TimePeriod object
511        // ---------------------------------------------
512        else {
513            // consider time periods to be ordered after general objects
514            result = 1;
515        }
516
517        return result;
518
519    }
520
521    /**
522     * Parses the string argument as a week.
523     * <P>
524     * This method is required to accept the format "YYYY-Wnn".  It will also
525     * accept "Wnn-YYYY". Anything else, at the moment, is a bonus.
526     *
527     * @param s  string to parse.
528     *
529     * @return <code>null</code> if the string is not parseable, the week
530     *         otherwise.
531     */
532    public static Week parseWeek(String s) {
533
534        Week result = null;
535        if (s != null) {
536
537            // trim whitespace from either end of the string
538            s = s.trim();
539
540            int i = Week.findSeparator(s);
541            if (i != -1) {
542                String s1 = s.substring(0, i).trim();
543                String s2 = s.substring(i + 1, s.length()).trim();
544
545                Year y = Week.evaluateAsYear(s1);
546                int w;
547                if (y != null) {
548                    w = Week.stringToWeek(s2);
549                    if (w == -1) {
550                        throw new TimePeriodFormatException(
551                                "Can't evaluate the week.");
552                    }
553                    result = new Week(w, y);
554                }
555                else {
556                    y = Week.evaluateAsYear(s2);
557                    if (y != null) {
558                        w = Week.stringToWeek(s1);
559                        if (w == -1) {
560                            throw new TimePeriodFormatException(
561                                    "Can't evaluate the week.");
562                        }
563                        result = new Week(w, y);
564                    }
565                    else {
566                        throw new TimePeriodFormatException(
567                                "Can't evaluate the year.");
568                    }
569                }
570
571            }
572            else {
573                throw new TimePeriodFormatException(
574                        "Could not find separator.");
575            }
576
577        }
578        return result;
579
580    }
581
582    /**
583     * Finds the first occurrence of ' ', '-', ',' or '.'
584     *
585     * @param s  the string to parse.
586     *
587     * @return <code>-1</code> if none of the characters was found, the
588     *      index of the first occurrence otherwise.
589     */
590    private static int findSeparator(String s) {
591
592        int result = s.indexOf('-');
593        if (result == -1) {
594            result = s.indexOf(',');
595        }
596        if (result == -1) {
597            result = s.indexOf(' ');
598        }
599        if (result == -1) {
600            result = s.indexOf('.');
601        }
602        return result;
603    }
604
605    /**
606     * Creates a year from a string, or returns null (format exceptions
607     * suppressed).
608     *
609     * @param s  string to parse.
610     *
611     * @return <code>null</code> if the string is not parseable, the year
612     *         otherwise.
613     */
614    private static Year evaluateAsYear(String s) {
615
616        Year result = null;
617        try {
618            result = Year.parseYear(s);
619        }
620        catch (TimePeriodFormatException e) {
621            // suppress
622        }
623        return result;
624
625    }
626
627    /**
628     * Converts a string to a week.
629     *
630     * @param s  the string to parse.
631     * @return <code>-1</code> if the string does not contain a week number,
632     *         the number of the week otherwise.
633     */
634    private static int stringToWeek(String s) {
635
636        int result = -1;
637        s = s.replace('W', ' ');
638        s = s.trim();
639        try {
640            result = Integer.parseInt(s);
641            if ((result < 1) || (result > LAST_WEEK_IN_YEAR)) {
642                result = -1;
643            }
644        }
645        catch (NumberFormatException e) {
646            // suppress
647        }
648        return result;
649
650    }
651
652}