001    /* ===========================================================
002     * JFreeChart : a free chart library for the Java(tm) platform
003     * ===========================================================
004     *
005     * (C) Copyright 2000-2008, 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     * Month.java
029     * ----------
030     * (C) Copyright 2001-2008, by Object Refinery Limited and Contributors.
031     *
032     * Original Author:  David Gilbert (for Object Refinery Limited);
033     * Contributor(s):   Chris Boek;
034     *
035     * Changes
036     * -------
037     * 11-Oct-2001 : Version 1 (DG);
038     * 14-Nov-2001 : Added method to get year as primitive (DG);
039     *               Override for toString() method (DG);
040     * 18-Dec-2001 : Changed order of parameters in constructor (DG);
041     * 19-Dec-2001 : Added a new constructor as suggested by Paul English (DG);
042     * 29-Jan-2002 : Worked on the parseMonth() method (DG);
043     * 14-Feb-2002 : Fixed bugs in the Month constructors (DG);
044     * 26-Feb-2002 : Changed getStart(), getMiddle() and getEnd() methods to
045     *               evaluate with reference to a particular time zone (DG);
046     * 19-Mar-2002 : Changed API for TimePeriod classes (DG);
047     * 10-Sep-2002 : Added getSerialIndex() method (DG);
048     * 04-Oct-2002 : Fixed errors reported by Checkstyle (DG);
049     * 10-Jan-2003 : Changed base class and method names (DG);
050     * 13-Mar-2003 : Moved to com.jrefinery.data.time package, and implemented
051     *               Serializable (DG);
052     * 21-Oct-2003 : Added hashCode() method (DG);
053     * 01-Nov-2005 : Fixed bug 1345383 (argument check in constructor) (DG);
054     * ------------- JFREECHART 1.0.x ---------------------------------------------
055     * 05-Oct-2006 : Updated API docs (DG);
056     * 06-Oct-2006 : Refactored to cache first and last millisecond values (DG);
057     * 04-Apr-2007 : Fixed bug in Month(Date, TimeZone) constructor (CB);
058     * 01-Sep-2008 : Added clarification for previous() and next() methods (DG);
059     * 16-Sep-2008 : Deprecated DEFAULT_TIME_ZONE, and updated parsing to handle
060     *               extended range in Year (DG);
061     * 25-Nov-2008 : Added new constructor with Locale (DG);
062     *
063     */
064    
065    package org.jfree.data.time;
066    
067    import java.io.Serializable;
068    import java.util.Calendar;
069    import java.util.Date;
070    import java.util.Locale;
071    import java.util.TimeZone;
072    
073    import org.jfree.date.MonthConstants;
074    import org.jfree.date.SerialDate;
075    
076    /**
077     * Represents a single month.  This class is immutable, which is a requirement
078     * for all {@link RegularTimePeriod} subclasses.
079     */
080    public class Month extends RegularTimePeriod implements Serializable {
081    
082        /** For serialization. */
083        private static final long serialVersionUID = -5090216912548722570L;
084    
085        /** The month (1-12). */
086        private int month;
087    
088        /** The year in which the month falls. */
089        private int year;
090    
091        /** The first millisecond. */
092        private long firstMillisecond;
093    
094        /** The last millisecond. */
095        private long lastMillisecond;
096    
097        /**
098         * Constructs a new Month, based on the current system time.
099         */
100        public Month() {
101            this(new Date());
102        }
103    
104        /**
105         * Constructs a new month instance.
106         *
107         * @param month  the month (in the range 1 to 12).
108         * @param year  the year.
109         */
110        public Month(int month, int year) {
111            if ((month < 1) || (month > 12)) {
112                throw new IllegalArgumentException("Month outside valid range.");
113            }
114            this.month = month;
115            this.year = year;
116            peg(Calendar.getInstance());
117        }
118    
119        /**
120         * Constructs a new month instance.
121         *
122         * @param month  the month (in the range 1 to 12).
123         * @param year  the year.
124         */
125        public Month(int month, Year year) {
126            if ((month < 1) || (month > 12)) {
127                throw new IllegalArgumentException("Month outside valid range.");
128            }
129            this.month = month;
130            this.year = year.getYear();
131            peg(Calendar.getInstance());
132        }
133    
134        /**
135         * Constructs a new <code>Month</code> instance, based on a date/time and
136         * the default time zone.
137         *
138         * @param time  the date/time (<code>null</code> not permitted).
139         *
140         * @see #Month(Date, TimeZone)
141         */
142        public Month(Date time) {
143            this(time, TimeZone.getDefault());
144        }
145    
146        /**
147         * Constructs a new <code>Month</code> instance, based on a date/time and
148         * a time zone.  The first and last millisecond values are initially
149         * pegged to the given time zone also.
150         *
151         * @param time  the date/time.
152         * @param zone  the time zone (<code>null</code> not permitted).
153         *
154         * @deprecated Since 1.0.12, use {@link #Month(Date, TimeZone, Locale)}
155         *     instead.
156         */
157        public Month(Date time, TimeZone zone) {
158            this(time, zone, Locale.getDefault());
159        }
160    
161        /**
162         * Creates a new <code>Month</code> instance, based on the specified time,
163         * zone and locale.
164         *
165         * @param time  the current time.
166         * @param zone  the time zone.
167         * @param locale  the locale.
168         *
169         * @since 1.0.12
170         */
171        public Month(Date time, TimeZone zone, Locale locale) {
172            Calendar calendar = Calendar.getInstance(zone);
173            calendar.setTime(time);
174            this.month = calendar.get(Calendar.MONTH) + 1;
175            this.year = calendar.get(Calendar.YEAR);
176            peg(calendar);
177        }
178    
179        /**
180         * Returns the year in which the month falls.
181         *
182         * @return The year in which the month falls (as a Year object).
183         */
184        public Year getYear() {
185            return new Year(this.year);
186        }
187    
188        /**
189         * Returns the year in which the month falls.
190         *
191         * @return The year in which the month falls (as an int).
192         */
193        public int getYearValue() {
194            return this.year;
195        }
196    
197        /**
198         * Returns the month.  Note that 1=JAN, 2=FEB, ...
199         *
200         * @return The month.
201         */
202        public int getMonth() {
203            return this.month;
204        }
205    
206        /**
207         * Returns the first millisecond of the month.  This will be determined
208         * relative to the time zone specified in the constructor, or in the
209         * calendar instance passed in the most recent call to the
210         * {@link #peg(Calendar)} method.
211         *
212         * @return The first millisecond of the month.
213         *
214         * @see #getLastMillisecond()
215         */
216        public long getFirstMillisecond() {
217            return this.firstMillisecond;
218        }
219    
220        /**
221         * Returns the last millisecond of the month.  This will be
222         * determined relative to the time zone specified in the constructor, or
223         * in the calendar instance passed in the most recent call to the
224         * {@link #peg(Calendar)} method.
225         *
226         * @return The last millisecond of the month.
227         *
228         * @see #getFirstMillisecond()
229         */
230        public long getLastMillisecond() {
231            return this.lastMillisecond;
232        }
233    
234        /**
235         * Recalculates the start date/time and end date/time for this time period
236         * relative to the supplied calendar (which incorporates a time zone).
237         *
238         * @param calendar  the calendar (<code>null</code> not permitted).
239         *
240         * @since 1.0.3
241         */
242        public void peg(Calendar calendar) {
243            this.firstMillisecond = getFirstMillisecond(calendar);
244            this.lastMillisecond = getLastMillisecond(calendar);
245        }
246    
247        /**
248         * Returns the month preceding this one.  Note that the returned
249         * {@link Month} is "pegged" using the default time-zone, irrespective of
250         * the time-zone used to peg of the current month (which is not recorded
251         * anywhere).  See the {@link #peg(Calendar)} method.
252         *
253         * @return The month preceding this one.
254         */
255        public RegularTimePeriod previous() {
256            Month result;
257            if (this.month != MonthConstants.JANUARY) {
258                result = new Month(this.month - 1, this.year);
259            }
260            else {
261                if (this.year > 1900) {
262                    result = new Month(MonthConstants.DECEMBER, this.year - 1);
263                }
264                else {
265                    result = null;
266                }
267            }
268            return result;
269        }
270    
271        /**
272         * Returns the month following this one.  Note that the returned
273         * {@link Month} is "pegged" using the default time-zone, irrespective of
274         * the time-zone used to peg of the current month (which is not recorded
275         * anywhere).  See the {@link #peg(Calendar)} method.
276         *
277         * @return The month following this one.
278         */
279        public RegularTimePeriod next() {
280            Month result;
281            if (this.month != MonthConstants.DECEMBER) {
282                result = new Month(this.month + 1, this.year);
283            }
284            else {
285                if (this.year < 9999) {
286                    result = new Month(MonthConstants.JANUARY, this.year + 1);
287                }
288                else {
289                    result = null;
290                }
291            }
292            return result;
293        }
294    
295        /**
296         * Returns a serial index number for the month.
297         *
298         * @return The serial index number.
299         */
300        public long getSerialIndex() {
301            return this.year * 12L + this.month;
302        }
303    
304        /**
305         * Returns a string representing the month (e.g. "January 2002").
306         * <P>
307         * To do: look at internationalisation.
308         *
309         * @return A string representing the month.
310         */
311        public String toString() {
312            return SerialDate.monthCodeToString(this.month) + " " + this.year;
313        }
314    
315        /**
316         * Tests the equality of this Month object to an arbitrary object.
317         * Returns true if the target is a Month instance representing the same
318         * month as this object.  In all other cases, returns false.
319         *
320         * @param obj  the object (<code>null</code> permitted).
321         *
322         * @return <code>true</code> if month and year of this and object are the
323         *         same.
324         */
325        public boolean equals(Object obj) {
326    
327            if (obj != null) {
328                if (obj instanceof Month) {
329                    Month target = (Month) obj;
330                    return (this.month == target.getMonth()
331                            && (this.year == target.getYearValue()));
332                }
333                else {
334                    return false;
335                }
336            }
337            else {
338                return false;
339            }
340    
341        }
342    
343        /**
344         * Returns a hash code for this object instance.  The approach described by
345         * Joshua Bloch in "Effective Java" has been used here:
346         * <p>
347         * <code>http://developer.java.sun.com/developer/Books/effectivejava
348         * /Chapter3.pdf</code>
349         *
350         * @return A hash code.
351         */
352        public int hashCode() {
353            int result = 17;
354            result = 37 * result + this.month;
355            result = 37 * result + this.year;
356            return result;
357        }
358    
359        /**
360         * Returns an integer indicating the order of this Month object relative to
361         * the specified
362         * object: negative == before, zero == same, positive == after.
363         *
364         * @param o1  the object to compare.
365         *
366         * @return negative == before, zero == same, positive == after.
367         */
368        public int compareTo(Object o1) {
369    
370            int result;
371    
372            // CASE 1 : Comparing to another Month object
373            // --------------------------------------------
374            if (o1 instanceof Month) {
375                Month m = (Month) o1;
376                result = this.year - m.getYearValue();
377                if (result == 0) {
378                    result = this.month - m.getMonth();
379                }
380            }
381    
382            // CASE 2 : Comparing to another TimePeriod object
383            // -----------------------------------------------
384            else if (o1 instanceof RegularTimePeriod) {
385                // more difficult case - evaluate later...
386                result = 0;
387            }
388    
389            // CASE 3 : Comparing to a non-TimePeriod object
390            // ---------------------------------------------
391            else {
392                // consider time periods to be ordered after general objects
393                result = 1;
394            }
395    
396            return result;
397    
398        }
399    
400        /**
401         * Returns the first millisecond of the month, evaluated using the supplied
402         * calendar (which determines the time zone).
403         *
404         * @param calendar  the calendar (<code>null</code> not permitted).
405         *
406         * @return The first millisecond of the month.
407         *
408         * @throws NullPointerException if <code>calendar</code> is
409         *     <code>null</code>.
410         */
411        public long getFirstMillisecond(Calendar calendar) {
412            calendar.set(this.year, this.month - 1, 1, 0, 0, 0);
413            calendar.set(Calendar.MILLISECOND, 0);
414            // in the following line, we'd rather call calendar.getTimeInMillis()
415            // to avoid object creation, but that isn't supported in Java 1.3.1
416            return calendar.getTime().getTime();
417        }
418    
419        /**
420         * Returns the last millisecond of the month, evaluated using the supplied
421         * calendar (which determines the time zone).
422         *
423         * @param calendar  the calendar (<code>null</code> not permitted).
424         *
425         * @return The last millisecond of the month.
426         *
427         * @throws NullPointerException if <code>calendar</code> is
428         *     <code>null</code>.
429         */
430        public long getLastMillisecond(Calendar calendar) {
431            int eom = SerialDate.lastDayOfMonth(this.month, this.year);
432            calendar.set(this.year, this.month - 1, eom, 23, 59, 59);
433            calendar.set(Calendar.MILLISECOND, 999);
434            // in the following line, we'd rather call calendar.getTimeInMillis()
435            // to avoid object creation, but that isn't supported in Java 1.3.1
436            return calendar.getTime().getTime();
437        }
438    
439        /**
440         * Parses the string argument as a month.  This method is required to
441         * accept the format "YYYY-MM".  It will also accept "MM-YYYY". Anything
442         * else, at the moment, is a bonus.
443         *
444         * @param s  the string to parse (<code>null</code> permitted).
445         *
446         * @return <code>null</code> if the string is not parseable, the month
447         *         otherwise.
448         */
449        public static Month parseMonth(String s) {
450            Month result = null;
451            if (s == null) {
452                return result;
453            }
454            // trim whitespace from either end of the string
455            s = s.trim();
456            int i = Month.findSeparator(s);
457            String s1, s2;
458            boolean yearIsFirst;
459            // if there is no separator, we assume the first four characters
460            // are YYYY
461            if (i == -1) {
462                yearIsFirst = true;
463                s1 = s.substring(0, 5);
464                s2 = s.substring(5);
465            }
466            else {
467                s1 = s.substring(0, i).trim();
468                s2 = s.substring(i + 1, s.length()).trim();
469                // now it is trickier to determine if the month or year is first
470                Year y1 = Month.evaluateAsYear(s1);
471                if (y1 == null) {
472                    yearIsFirst = false;
473                }
474                else {
475                    Year y2 = Month.evaluateAsYear(s2);
476                    if (y2 == null) {
477                        yearIsFirst = true;
478                    }
479                    else {
480                        yearIsFirst = (s1.length() > s2.length());
481                    }
482                }
483            }
484            Year year;
485            int month;
486            if (yearIsFirst) {
487                year = Month.evaluateAsYear(s1);
488                month = SerialDate.stringToMonthCode(s2);
489            }
490            else {
491                year = Month.evaluateAsYear(s2);
492                month = SerialDate.stringToMonthCode(s1);
493            }
494            if (month == -1) {
495                throw new TimePeriodFormatException("Can't evaluate the month.");
496            }
497            if (year == null) {
498                throw new TimePeriodFormatException("Can't evaluate the year.");
499            }
500            result = new Month(month, year);
501            return result;
502        }
503    
504        /**
505         * Finds the first occurrence of '-', or if that character is not found,
506         * the first occurrence of ',', or the first occurrence of ' ' or '.'
507         *
508         * @param s  the string to parse.
509         *
510         * @return The position of the separator character, or <code>-1</code> if
511         *     none of the characters were found.
512         */
513        private static int findSeparator(String s) {
514            int result = s.indexOf('-');
515            if (result == -1) {
516                result = s.indexOf(',');
517            }
518            if (result == -1) {
519                result = s.indexOf(' ');
520            }
521            if (result == -1) {
522                result = s.indexOf('.');
523            }
524            return result;
525        }
526    
527        /**
528         * Creates a year from a string, or returns <code>null</code> (format
529         * exceptions suppressed).
530         *
531         * @param s  the string to parse.
532         *
533         * @return <code>null</code> if the string is not parseable, the year
534         *         otherwise.
535         */
536        private static Year evaluateAsYear(String s) {
537            Year result = null;
538            try {
539                result = Year.parseYear(s);
540            }
541            catch (TimePeriodFormatException e) {
542                // suppress
543            }
544            return result;
545        }
546    
547    }