001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, 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-2016, 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.Args;
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} 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} 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} not permitted).
177     * @param zone  the time zone ({@code null} not permitted).
178     * @param locale  the locale ({@code null} not permitted).
179     *
180     * @since 1.0.7
181     */
182    public Week(Date time, TimeZone zone, Locale locale) {
183        Args.nullNotPermitted(time, "time");
184        Args.nullNotPermitted(zone, "zone");
185        Args.nullNotPermitted(locale, "locale");
186        Calendar calendar = Calendar.getInstance(zone, locale);
187        calendar.setTime(time);
188
189        // sometimes the last few days of the year are considered to fall in
190        // the *first* week of the following year.  Refer to the Javadocs for
191        // GregorianCalendar.
192        int tempWeek = calendar.get(Calendar.WEEK_OF_YEAR);
193        if (tempWeek == 1
194                && calendar.get(Calendar.MONTH) == Calendar.DECEMBER) {
195            this.week = 1;
196            this.year = (short) (calendar.get(Calendar.YEAR) + 1);
197        }
198        else {
199            this.week = (byte) Math.min(tempWeek, LAST_WEEK_IN_YEAR);
200            int yyyy = calendar.get(Calendar.YEAR);
201            // alternatively, sometimes the first few days of the year are
202            // considered to fall in the *last* week of the previous year...
203            if (calendar.get(Calendar.MONTH) == Calendar.JANUARY
204                    && this.week >= 52) {
205                yyyy--;
206            }
207            this.year = (short) yyyy;
208        }
209        peg(calendar);
210    }
211
212    /**
213     * Returns the year in which the week falls.
214     *
215     * @return The year (never {@code null}).
216     */
217    public Year getYear() {
218        return new Year(this.year);
219    }
220
221    /**
222     * Returns the year in which the week falls, as an integer value.
223     *
224     * @return The year.
225     */
226    public int getYearValue() {
227        return this.year;
228    }
229
230    /**
231     * Returns the week.
232     *
233     * @return The week.
234     */
235    public int getWeek() {
236        return this.week;
237    }
238
239    /**
240     * Returns the first millisecond of the week.  This will be determined
241     * relative to the time zone specified in the constructor, or in the
242     * calendar instance passed in the most recent call to the
243     * {@link #peg(Calendar)} method.
244     *
245     * @return The first millisecond of the week.
246     *
247     * @see #getLastMillisecond()
248     */
249    @Override
250    public long getFirstMillisecond() {
251        return this.firstMillisecond;
252    }
253
254    /**
255     * Returns the last millisecond of the week.  This will be
256     * determined relative to the time zone specified in the constructor, or
257     * in the calendar instance passed in the most recent call to the
258     * {@link #peg(Calendar)} method.
259     *
260     * @return The last millisecond of the week.
261     *
262     * @see #getFirstMillisecond()
263     */
264    @Override
265    public long getLastMillisecond() {
266        return this.lastMillisecond;
267    }
268
269    /**
270     * Recalculates the start date/time and end date/time for this time period
271     * relative to the supplied calendar (which incorporates a time zone).
272     *
273     * @param calendar  the calendar ({@code null} not permitted).
274     *
275     * @since 1.0.3
276     */
277    @Override
278    public void peg(Calendar calendar) {
279        this.firstMillisecond = getFirstMillisecond(calendar);
280        this.lastMillisecond = getLastMillisecond(calendar);
281    }
282
283    /**
284     * Returns the week preceding this one.  This method will return
285     * {@code null} for some lower limit on the range of weeks (currently
286     * week 1, 1900).  For week 1 of any year, the previous week is always week
287     * 53, but week 53 may not contain any days (you should check for this).
288     *
289     * @return The preceding week (possibly {@code null}).
290     */
291    @Override
292    public RegularTimePeriod previous() {
293
294        Week result;
295        if (this.week != FIRST_WEEK_IN_YEAR) {
296            result = new Week(this.week - 1, this.year);
297        }
298        else {
299            // we need to work out if the previous year has 52 or 53 weeks...
300            if (this.year > 1900) {
301                int yy = this.year - 1;
302                Calendar prevYearCalendar = Calendar.getInstance();
303                prevYearCalendar.set(yy, Calendar.DECEMBER, 31);
304                result = new Week(prevYearCalendar.getActualMaximum(
305                        Calendar.WEEK_OF_YEAR), yy);
306            }
307            else {
308                result = null;
309            }
310        }
311        return result;
312
313    }
314
315    /**
316     * Returns the week following this one.  This method will return
317     * {@code null} for some upper limit on the range of weeks (currently
318     * week 53, 9999).  For week 52 of any year, the following week is always
319     * week 53, but week 53 may not contain any days (you should check for
320     * this).
321     *
322     * @return The following week (possibly {@code null}).
323     */
324    @Override
325    public RegularTimePeriod next() {
326
327        Week result;
328        if (this.week < 52) {
329            result = new Week(this.week + 1, this.year);
330        }
331        else {
332            Calendar calendar = Calendar.getInstance();
333            calendar.set(this.year, Calendar.DECEMBER, 31);
334            int actualMaxWeek
335                = calendar.getActualMaximum(Calendar.WEEK_OF_YEAR);
336            if (this.week < actualMaxWeek) {
337                result = new Week(this.week + 1, this.year);
338            }
339            else {
340                if (this.year < 9999) {
341                    result = new Week(FIRST_WEEK_IN_YEAR, this.year + 1);
342                }
343                else {
344                    result = null;
345                }
346            }
347        }
348        return result;
349
350    }
351
352    /**
353     * Returns a serial index number for the week.
354     *
355     * @return The serial index number.
356     */
357    @Override
358    public long getSerialIndex() {
359        return this.year * 53L + this.week;
360    }
361
362    /**
363     * Returns the first millisecond of the week, evaluated using the supplied
364     * calendar (which determines the time zone).
365     *
366     * @param calendar  the calendar ({@code null} not permitted).
367     *
368     * @return The first millisecond of the week.
369     *
370     * @throws NullPointerException if {@code calendar} is
371     *     {@code null}.
372     */
373    @Override
374    public long getFirstMillisecond(Calendar calendar) {
375        Calendar c = (Calendar) calendar.clone();
376        c.clear();
377        c.set(Calendar.YEAR, this.year);
378        c.set(Calendar.WEEK_OF_YEAR, this.week);
379        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
380        c.set(Calendar.HOUR, 0);
381        c.set(Calendar.MINUTE, 0);
382        c.set(Calendar.SECOND, 0);
383        c.set(Calendar.MILLISECOND, 0);
384        return c.getTimeInMillis();
385    }
386
387    /**
388     * Returns the last millisecond of the week, evaluated using the supplied
389     * calendar (which determines the time zone).
390     *
391     * @param calendar  the calendar ({@code null} not permitted).
392     *
393     * @return The last millisecond of the week.
394     *
395     * @throws NullPointerException if {@code calendar} is
396     *     {@code null}.
397     */
398    @Override
399    public long getLastMillisecond(Calendar calendar) {
400        Calendar c = (Calendar) calendar.clone();
401        c.clear();
402        c.set(Calendar.YEAR, this.year);
403        c.set(Calendar.WEEK_OF_YEAR, this.week + 1);
404        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
405        c.set(Calendar.HOUR, 0);
406        c.set(Calendar.MINUTE, 0);
407        c.set(Calendar.SECOND, 0);
408        c.set(Calendar.MILLISECOND, 0);
409        return c.getTimeInMillis() - 1;
410    }
411
412    /**
413     * Returns a string representing the week (e.g. "Week 9, 2002").
414     *
415     * TODO: look at internationalisation.
416     *
417     * @return A string representing the week.
418     */
419    @Override
420    public String toString() {
421        return "Week " + this.week + ", " + this.year;
422    }
423
424    /**
425     * Tests the equality of this Week object to an arbitrary object.  Returns
426     * true if the target is a Week instance representing the same week as this
427     * object.  In all other cases, returns false.
428     *
429     * @param obj  the object ({@code null} permitted).
430     *
431     * @return {@code true} if week and year of this and object are the
432     *         same.
433     */
434    @Override
435    public boolean equals(Object obj) {
436
437        if (obj == this) {
438            return true;
439        }
440        if (!(obj instanceof Week)) {
441            return false;
442        }
443        Week that = (Week) obj;
444        if (this.week != that.week) {
445            return false;
446        }
447        if (this.year != that.year) {
448            return false;
449        }
450        return true;
451
452    }
453
454    /**
455     * Returns a hash code for this object instance.  The approach described by
456     * Joshua Bloch in "Effective Java" has been used here:
457     * <p>
458     * {@code http://developer.java.sun.com/developer/Books/effectivejava
459     * /Chapter3.pdf}
460     *
461     * @return A hash code.
462     */
463    @Override
464    public int hashCode() {
465        int result = 17;
466        result = 37 * result + this.week;
467        result = 37 * result + this.year;
468        return result;
469    }
470
471    /**
472     * Returns an integer indicating the order of this Week object relative to
473     * the specified object:
474     *
475     * negative == before, zero == same, positive == after.
476     *
477     * @param o1  the object to compare.
478     *
479     * @return negative == before, zero == same, positive == after.
480     */
481    @Override
482    public int compareTo(Object o1) {
483
484        int result;
485
486        // CASE 1 : Comparing to another Week object
487        // --------------------------------------------
488        if (o1 instanceof Week) {
489            Week w = (Week) o1;
490            result = this.year - w.getYear().getYear();
491            if (result == 0) {
492                result = this.week - w.getWeek();
493            }
494        }
495
496        // CASE 2 : Comparing to another TimePeriod object
497        // -----------------------------------------------
498        else if (o1 instanceof RegularTimePeriod) {
499            // more difficult case - evaluate later...
500            result = 0;
501        }
502
503        // CASE 3 : Comparing to a non-TimePeriod object
504        // ---------------------------------------------
505        else {
506            // consider time periods to be ordered after general objects
507            result = 1;
508        }
509
510        return result;
511
512    }
513
514    /**
515     * Parses the string argument as a week.
516     * <P>
517     * This method is required to accept the format "YYYY-Wnn".  It will also
518     * accept "Wnn-YYYY". Anything else, at the moment, is a bonus.
519     *
520     * @param s  string to parse.
521     *
522     * @return {@code null} if the string is not parseable, the week
523     *         otherwise.
524     */
525    public static Week parseWeek(String s) {
526
527        Week result = null;
528        if (s != null) {
529
530            // trim whitespace from either end of the string
531            s = s.trim();
532
533            int i = Week.findSeparator(s);
534            if (i != -1) {
535                String s1 = s.substring(0, i).trim();
536                String s2 = s.substring(i + 1, s.length()).trim();
537
538                Year y = Week.evaluateAsYear(s1);
539                int w;
540                if (y != null) {
541                    w = Week.stringToWeek(s2);
542                    if (w == -1) {
543                        throw new TimePeriodFormatException(
544                                "Can't evaluate the week.");
545                    }
546                    result = new Week(w, y);
547                }
548                else {
549                    y = Week.evaluateAsYear(s2);
550                    if (y != null) {
551                        w = Week.stringToWeek(s1);
552                        if (w == -1) {
553                            throw new TimePeriodFormatException(
554                                    "Can't evaluate the week.");
555                        }
556                        result = new Week(w, y);
557                    }
558                    else {
559                        throw new TimePeriodFormatException(
560                                "Can't evaluate the year.");
561                    }
562                }
563
564            }
565            else {
566                throw new TimePeriodFormatException(
567                        "Could not find separator.");
568            }
569
570        }
571        return result;
572
573    }
574
575    /**
576     * Finds the first occurrence of ' ', '-', ',' or '.'
577     *
578     * @param s  the string to parse.
579     *
580     * @return {@code -1} if none of the characters was found, the
581     *      index of the first occurrence otherwise.
582     */
583    private static int findSeparator(String s) {
584
585        int result = s.indexOf('-');
586        if (result == -1) {
587            result = s.indexOf(',');
588        }
589        if (result == -1) {
590            result = s.indexOf(' ');
591        }
592        if (result == -1) {
593            result = s.indexOf('.');
594        }
595        return result;
596    }
597
598    /**
599     * Creates a year from a string, or returns null (format exceptions
600     * suppressed).
601     *
602     * @param s  string to parse.
603     *
604     * @return {@code null} if the string is not parseable, the year
605     *         otherwise.
606     */
607    private static Year evaluateAsYear(String s) {
608
609        Year result = null;
610        try {
611            result = Year.parseYear(s);
612        }
613        catch (TimePeriodFormatException e) {
614            // suppress
615        }
616        return result;
617
618    }
619
620    /**
621     * Converts a string to a week.
622     *
623     * @param s  the string to parse.
624     * @return {@code -1} if the string does not contain a week number,
625     *         the number of the week otherwise.
626     */
627    private static int stringToWeek(String s) {
628
629        int result = -1;
630        s = s.replace('W', ' ');
631        s = s.trim();
632        try {
633            result = Integer.parseInt(s);
634            if ((result < 1) || (result > LAST_WEEK_IN_YEAR)) {
635                result = -1;
636            }
637        }
638        catch (NumberFormatException e) {
639            // suppress
640        }
641        return result;
642
643    }
644
645}