001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2013, 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 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
025 * Other names may be trademarks of their respective owners.]
026 *
027 * ---------
028 * Week.java
029 * ---------
030 * (C) Copyright 2001-2013, 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 * 05-Jul-2012 : Replaced getTime().getTime() with getTimeInMillis() (DG);
071 * 03-Jul-2013 : Use ParamChecks (DG);
072 *
073 */
074
075package org.jfree.data.time;
076
077import java.io.Serializable;
078import java.util.Calendar;
079import java.util.Date;
080import java.util.Locale;
081import java.util.TimeZone;
082import org.jfree.chart.util.ParamChecks;
083
084/**
085 * A calendar week.  All years are considered to have 53 weeks, numbered from 1
086 * to 53, although in many cases the 53rd week is empty.  Most of the time, the
087 * 1st week of the year *begins* in the previous calendar year, but it always
088 * finishes in the current year (this behaviour matches the workings of the
089 * <code>GregorianCalendar</code> class).
090 * <P>
091 * This class is immutable, which is a requirement for all
092 * {@link RegularTimePeriod} subclasses.
093 */
094public class Week extends RegularTimePeriod implements Serializable {
095
096    /** For serialization. */
097    private static final long serialVersionUID = 1856387786939865061L;
098
099    /** Constant for the first week in the year. */
100    public static final int FIRST_WEEK_IN_YEAR = 1;
101
102    /** Constant for the last week in the year. */
103    public static final int LAST_WEEK_IN_YEAR = 53;
104
105    /** The year in which the week falls. */
106    private short year;
107
108    /** The week (1-53). */
109    private byte week;
110
111    /** The first millisecond. */
112    private long firstMillisecond;
113
114    /** The last millisecond. */
115    private long lastMillisecond;
116
117    /**
118     * Creates a new time period for the week in which the current system
119     * date/time falls.
120     */
121    public Week() {
122        this(new Date());
123    }
124
125    /**
126     * Creates a time period representing the week in the specified year.
127     *
128     * @param week  the week (1 to 53).
129     * @param year  the year (1900 to 9999).
130     */
131    public Week(int week, int year) {
132        if ((week < FIRST_WEEK_IN_YEAR) && (week > LAST_WEEK_IN_YEAR)) {
133            throw new IllegalArgumentException(
134                    "The 'week' argument must be in the range 1 - 53.");
135        }
136        this.week = (byte) week;
137        this.year = (short) year;
138        peg(Calendar.getInstance());
139    }
140
141    /**
142     * Creates a time period representing the week in the specified year.
143     *
144     * @param week  the week (1 to 53).
145     * @param year  the year (1900 to 9999).
146     */
147    public Week(int week, Year year) {
148        if ((week < FIRST_WEEK_IN_YEAR) && (week > LAST_WEEK_IN_YEAR)) {
149            throw new IllegalArgumentException(
150                    "The 'week' argument must be in the range 1 - 53.");
151        }
152        this.week = (byte) week;
153        this.year = (short) year.getYear();
154        peg(Calendar.getInstance());
155   }
156
157    /**
158     * Creates a time period for the week in which the specified date/time
159     * falls, using the default time zone and locale (the locale can affect the
160     * day-of-the-week that marks the beginning of the week, as well as the
161     * minimal number of days in the first week of the year).
162     *
163     * @param time  the time (<code>null</code> not permitted).
164     *
165     * @see #Week(Date, TimeZone, Locale)
166     */
167    public Week(Date time) {
168        // defer argument checking...
169        this(time, TimeZone.getDefault(), Locale.getDefault());
170    }
171
172    /**
173     * Creates a time period for the week in which the specified date/time
174     * falls, calculated relative to the specified time zone.
175     *
176     * @param time  the date/time (<code>null</code> not permitted).
177     * @param zone  the time zone (<code>null</code> not permitted).
178     *
179     * @deprecated As of 1.0.7, use {@link #Week(Date, TimeZone, Locale)}.
180     */
181    public Week(Date time, TimeZone zone) {
182        // defer argument checking...
183        this(time, zone, Locale.getDefault());
184    }
185
186    /**
187     * Creates a time period for the week in which the specified date/time
188     * falls, calculated relative to the specified time zone.
189     *
190     * @param time  the date/time (<code>null</code> not permitted).
191     * @param zone  the time zone (<code>null</code> not permitted).
192     * @param locale  the locale (<code>null</code> not permitted).
193     *
194     * @since 1.0.7
195     */
196    public Week(Date time, TimeZone zone, Locale locale) {
197        ParamChecks.nullNotPermitted(time, "time");
198        ParamChecks.nullNotPermitted(zone, "zone");
199        ParamChecks.nullNotPermitted(locale, "locale");
200        Calendar calendar = Calendar.getInstance(zone, locale);
201        calendar.setTime(time);
202
203        // sometimes the last few days of the year are considered to fall in
204        // the *first* week of the following year.  Refer to the Javadocs for
205        // GregorianCalendar.
206        int tempWeek = calendar.get(Calendar.WEEK_OF_YEAR);
207        if (tempWeek == 1
208                && calendar.get(Calendar.MONTH) == Calendar.DECEMBER) {
209            this.week = 1;
210            this.year = (short) (calendar.get(Calendar.YEAR) + 1);
211        }
212        else {
213            this.week = (byte) Math.min(tempWeek, LAST_WEEK_IN_YEAR);
214            int yyyy = calendar.get(Calendar.YEAR);
215            // alternatively, sometimes the first few days of the year are
216            // considered to fall in the *last* week of the previous year...
217            if (calendar.get(Calendar.MONTH) == Calendar.JANUARY
218                    && this.week >= 52) {
219                yyyy--;
220            }
221            this.year = (short) yyyy;
222        }
223        peg(calendar);
224    }
225
226    /**
227     * Returns the year in which the week falls.
228     *
229     * @return The year (never <code>null</code>).
230     */
231    public Year getYear() {
232        return new Year(this.year);
233    }
234
235    /**
236     * Returns the year in which the week falls, as an integer value.
237     *
238     * @return The year.
239     */
240    public int getYearValue() {
241        return this.year;
242    }
243
244    /**
245     * Returns the week.
246     *
247     * @return The week.
248     */
249    public int getWeek() {
250        return this.week;
251    }
252
253    /**
254     * Returns the first millisecond of the week.  This will be determined
255     * relative to the time zone specified in the constructor, or in the
256     * calendar instance passed in the most recent call to the
257     * {@link #peg(Calendar)} method.
258     *
259     * @return The first millisecond of the week.
260     *
261     * @see #getLastMillisecond()
262     */
263    @Override
264    public long getFirstMillisecond() {
265        return this.firstMillisecond;
266    }
267
268    /**
269     * Returns the last millisecond of the week.  This will be
270     * determined relative to the time zone specified in the constructor, or
271     * in the calendar instance passed in the most recent call to the
272     * {@link #peg(Calendar)} method.
273     *
274     * @return The last millisecond of the week.
275     *
276     * @see #getFirstMillisecond()
277     */
278    @Override
279    public long getLastMillisecond() {
280        return this.lastMillisecond;
281    }
282
283    /**
284     * Recalculates the start date/time and end date/time for this time period
285     * relative to the supplied calendar (which incorporates a time zone).
286     *
287     * @param calendar  the calendar (<code>null</code> not permitted).
288     *
289     * @since 1.0.3
290     */
291    @Override
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    @Override
306    public RegularTimePeriod previous() {
307
308        Week result;
309        if (this.week != FIRST_WEEK_IN_YEAR) {
310            result = new Week(this.week - 1, this.year);
311        }
312        else {
313            // we need to work out if the previous year has 52 or 53 weeks...
314            if (this.year > 1900) {
315                int yy = this.year - 1;
316                Calendar prevYearCalendar = Calendar.getInstance();
317                prevYearCalendar.set(yy, Calendar.DECEMBER, 31);
318                result = new Week(prevYearCalendar.getActualMaximum(
319                        Calendar.WEEK_OF_YEAR), yy);
320            }
321            else {
322                result = null;
323            }
324        }
325        return result;
326
327    }
328
329    /**
330     * Returns the week following this one.  This method will return
331     * <code>null</code> for some upper limit on the range of weeks (currently
332     * week 53, 9999).  For week 52 of any year, the following week is always
333     * week 53, but week 53 may not contain any days (you should check for
334     * this).
335     *
336     * @return The following week (possibly <code>null</code>).
337     */
338    @Override
339    public RegularTimePeriod next() {
340
341        Week result;
342        if (this.week < 52) {
343            result = new Week(this.week + 1, this.year);
344        }
345        else {
346            Calendar calendar = Calendar.getInstance();
347            calendar.set(this.year, Calendar.DECEMBER, 31);
348            int actualMaxWeek
349                = calendar.getActualMaximum(Calendar.WEEK_OF_YEAR);
350            if (this.week < actualMaxWeek) {
351                result = new Week(this.week + 1, this.year);
352            }
353            else {
354                if (this.year < 9999) {
355                    result = new Week(FIRST_WEEK_IN_YEAR, this.year + 1);
356                }
357                else {
358                    result = null;
359                }
360            }
361        }
362        return result;
363
364    }
365
366    /**
367     * Returns a serial index number for the week.
368     *
369     * @return The serial index number.
370     */
371    @Override
372    public long getSerialIndex() {
373        return this.year * 53L + this.week;
374    }
375
376    /**
377     * Returns the first millisecond of the week, evaluated using the supplied
378     * calendar (which determines the time zone).
379     *
380     * @param calendar  the calendar (<code>null</code> not permitted).
381     *
382     * @return The first millisecond of the week.
383     *
384     * @throws NullPointerException if <code>calendar</code> is
385     *     <code>null</code>.
386     */
387    @Override
388    public long getFirstMillisecond(Calendar calendar) {
389        Calendar c = (Calendar) calendar.clone();
390        c.clear();
391        c.set(Calendar.YEAR, this.year);
392        c.set(Calendar.WEEK_OF_YEAR, this.week);
393        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
394        c.set(Calendar.HOUR, 0);
395        c.set(Calendar.MINUTE, 0);
396        c.set(Calendar.SECOND, 0);
397        c.set(Calendar.MILLISECOND, 0);
398        return c.getTimeInMillis();
399    }
400
401    /**
402     * Returns the last millisecond of the week, evaluated using the supplied
403     * calendar (which determines the time zone).
404     *
405     * @param calendar  the calendar (<code>null</code> not permitted).
406     *
407     * @return The last millisecond of the week.
408     *
409     * @throws NullPointerException if <code>calendar</code> is
410     *     <code>null</code>.
411     */
412    @Override
413    public long getLastMillisecond(Calendar calendar) {
414        Calendar c = (Calendar) calendar.clone();
415        c.clear();
416        c.set(Calendar.YEAR, this.year);
417        c.set(Calendar.WEEK_OF_YEAR, this.week + 1);
418        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
419        c.set(Calendar.HOUR, 0);
420        c.set(Calendar.MINUTE, 0);
421        c.set(Calendar.SECOND, 0);
422        c.set(Calendar.MILLISECOND, 0);
423        return c.getTimeInMillis() - 1;
424    }
425
426    /**
427     * Returns a string representing the week (e.g. "Week 9, 2002").
428     *
429     * TODO: look at internationalisation.
430     *
431     * @return A string representing the week.
432     */
433    @Override
434    public String toString() {
435        return "Week " + this.week + ", " + this.year;
436    }
437
438    /**
439     * Tests the equality of this Week object to an arbitrary object.  Returns
440     * true if the target is a Week instance representing the same week as this
441     * object.  In all other cases, returns false.
442     *
443     * @param obj  the object (<code>null</code> permitted).
444     *
445     * @return <code>true</code> if week and year of this and object are the
446     *         same.
447     */
448    @Override
449    public boolean equals(Object obj) {
450
451        if (obj == this) {
452            return true;
453        }
454        if (!(obj instanceof Week)) {
455            return false;
456        }
457        Week that = (Week) obj;
458        if (this.week != that.week) {
459            return false;
460        }
461        if (this.year != that.year) {
462            return false;
463        }
464        return true;
465
466    }
467
468    /**
469     * Returns a hash code for this object instance.  The approach described by
470     * Joshua Bloch in "Effective Java" has been used here:
471     * <p>
472     * <code>http://developer.java.sun.com/developer/Books/effectivejava
473     * /Chapter3.pdf</code>
474     *
475     * @return A hash code.
476     */
477    @Override
478    public int hashCode() {
479        int result = 17;
480        result = 37 * result + this.week;
481        result = 37 * result + this.year;
482        return result;
483    }
484
485    /**
486     * Returns an integer indicating the order of this Week object relative to
487     * the specified object:
488     *
489     * negative == before, zero == same, positive == after.
490     *
491     * @param o1  the object to compare.
492     *
493     * @return negative == before, zero == same, positive == after.
494     */
495    @Override
496    public int compareTo(Object o1) {
497
498        int result;
499
500        // CASE 1 : Comparing to another Week object
501        // --------------------------------------------
502        if (o1 instanceof Week) {
503            Week w = (Week) o1;
504            result = this.year - w.getYear().getYear();
505            if (result == 0) {
506                result = this.week - w.getWeek();
507            }
508        }
509
510        // CASE 2 : Comparing to another TimePeriod object
511        // -----------------------------------------------
512        else if (o1 instanceof RegularTimePeriod) {
513            // more difficult case - evaluate later...
514            result = 0;
515        }
516
517        // CASE 3 : Comparing to a non-TimePeriod object
518        // ---------------------------------------------
519        else {
520            // consider time periods to be ordered after general objects
521            result = 1;
522        }
523
524        return result;
525
526    }
527
528    /**
529     * Parses the string argument as a week.
530     * <P>
531     * This method is required to accept the format "YYYY-Wnn".  It will also
532     * accept "Wnn-YYYY". Anything else, at the moment, is a bonus.
533     *
534     * @param s  string to parse.
535     *
536     * @return <code>null</code> if the string is not parseable, the week
537     *         otherwise.
538     */
539    public static Week parseWeek(String s) {
540
541        Week result = null;
542        if (s != null) {
543
544            // trim whitespace from either end of the string
545            s = s.trim();
546
547            int i = Week.findSeparator(s);
548            if (i != -1) {
549                String s1 = s.substring(0, i).trim();
550                String s2 = s.substring(i + 1, s.length()).trim();
551
552                Year y = Week.evaluateAsYear(s1);
553                int w;
554                if (y != null) {
555                    w = Week.stringToWeek(s2);
556                    if (w == -1) {
557                        throw new TimePeriodFormatException(
558                                "Can't evaluate the week.");
559                    }
560                    result = new Week(w, y);
561                }
562                else {
563                    y = Week.evaluateAsYear(s2);
564                    if (y != null) {
565                        w = Week.stringToWeek(s1);
566                        if (w == -1) {
567                            throw new TimePeriodFormatException(
568                                    "Can't evaluate the week.");
569                        }
570                        result = new Week(w, y);
571                    }
572                    else {
573                        throw new TimePeriodFormatException(
574                                "Can't evaluate the year.");
575                    }
576                }
577
578            }
579            else {
580                throw new TimePeriodFormatException(
581                        "Could not find separator.");
582            }
583
584        }
585        return result;
586
587    }
588
589    /**
590     * Finds the first occurrence of ' ', '-', ',' or '.'
591     *
592     * @param s  the string to parse.
593     *
594     * @return <code>-1</code> if none of the characters was found, the
595     *      index of the first occurrence otherwise.
596     */
597    private static int findSeparator(String s) {
598
599        int result = s.indexOf('-');
600        if (result == -1) {
601            result = s.indexOf(',');
602        }
603        if (result == -1) {
604            result = s.indexOf(' ');
605        }
606        if (result == -1) {
607            result = s.indexOf('.');
608        }
609        return result;
610    }
611
612    /**
613     * Creates a year from a string, or returns null (format exceptions
614     * suppressed).
615     *
616     * @param s  string to parse.
617     *
618     * @return <code>null</code> if the string is not parseable, the year
619     *         otherwise.
620     */
621    private static Year evaluateAsYear(String s) {
622
623        Year result = null;
624        try {
625            result = Year.parseYear(s);
626        }
627        catch (TimePeriodFormatException e) {
628            // suppress
629        }
630        return result;
631
632    }
633
634    /**
635     * Converts a string to a week.
636     *
637     * @param s  the string to parse.
638     * @return <code>-1</code> if the string does not contain a week number,
639     *         the number of the week otherwise.
640     */
641    private static int stringToWeek(String s) {
642
643        int result = -1;
644        s = s.replace('W', ' ');
645        s = s.trim();
646        try {
647            result = Integer.parseInt(s);
648            if ((result < 1) || (result > LAST_WEEK_IN_YEAR)) {
649                result = -1;
650            }
651        }
652        catch (NumberFormatException e) {
653            // suppress
654        }
655        return result;
656
657    }
658
659}