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