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