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