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