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 * Year.java
029 * ---------
030 * (C) Copyright 2001-present, by David Gilbert.
031 *
032 * Original Author:  David Gilbert;
033 * Contributor(s):   -;
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;
044
045/**
046 * Represents a year in the range -9999 to 9999.  This class is immutable,
047 * which is a requirement for all {@link RegularTimePeriod} subclasses.
048 */
049public class Year extends RegularTimePeriod implements Serializable {
050
051    /**
052     * The minimum year value.
053     */
054    public static final int MINIMUM_YEAR = -9999;
055
056    /**
057     * The maximum year value.
058     */
059    public static final int MAXIMUM_YEAR = 9999;
060
061    /** For serialization. */
062    private static final long serialVersionUID = -7659990929736074836L;
063
064    /** The year. */
065    private short year;
066
067    /** The first millisecond. */
068    private long firstMillisecond;
069
070    /** The last millisecond. */
071    private long lastMillisecond;
072
073    /**
074     * Creates a new {@code Year}, based on the current system date/time.
075     * The time zone and locale are determined by the calendar
076     * returned by {@link RegularTimePeriod#getCalendarInstance()}.
077     */
078    public Year() {
079        this(new Date());
080    }
081
082    /**
083     * Creates a time period representing a single year.
084     * The time zone and locale are determined by the calendar
085     * returned by {@link RegularTimePeriod#getCalendarInstance()}.
086     *
087     * @param year  the year.
088     */
089    public Year(int year) {
090        if ((year < Year.MINIMUM_YEAR) || (year > Year.MAXIMUM_YEAR)) {
091            throw new IllegalArgumentException(
092                "Year constructor: year (" + year + ") outside valid range.");
093        }
094        this.year = (short) year;
095        peg(getCalendarInstance());
096    }
097
098    /**
099     * Creates a new {@code Year}, based on a particular instant in time.
100     * The time zone and locale are determined by the calendar
101     * returned by {@link RegularTimePeriod#getCalendarInstance()}.
102     *
103     * @param time  the time ({@code null} not permitted).
104     *
105     * @see #Year(Date, TimeZone, Locale)
106     */
107    public Year(Date time) {
108        this(time, getCalendarInstance());
109    }
110
111    /**
112     * Creates a new {@code Year} instance, for the specified time zone
113     * and locale.
114     *
115     * @param time  the current time ({@code null} not permitted).
116     * @param zone  the time zone.
117     * @param locale  the locale.
118     */
119    public Year(Date time, TimeZone zone, Locale locale) {
120        Calendar calendar = Calendar.getInstance(zone, locale);
121        calendar.setTime(time);
122        this.year = (short) calendar.get(Calendar.YEAR);
123        peg(calendar);
124    }
125
126    /**
127     * Constructs a new instance, based on a particular date/time.
128     * The time zone and locale are determined by the {@code calendar}
129     * parameter.
130     *
131     * @param time the date/time ({@code null} not permitted).
132     * @param calendar the calendar to use for calculations ({@code null} not permitted).
133     */
134    public Year(Date time, Calendar calendar) {
135        calendar.setTime(time);
136        this.year = (short) calendar.get(Calendar.YEAR);
137        peg(calendar);
138    }
139
140    /**
141     * Returns the year.
142     *
143     * @return The year.
144     */
145    public int getYear() {
146        return this.year;
147    }
148
149    /**
150     * Returns the first millisecond of the year.  This will be determined
151     * relative to the time zone specified in the constructor, or in the
152     * calendar instance passed in the most recent call to the
153     * {@link #peg(Calendar)} method.
154     *
155     * @return The first millisecond of the year.
156     *
157     * @see #getLastMillisecond()
158     */
159    @Override
160    public long getFirstMillisecond() {
161        return this.firstMillisecond;
162    }
163
164    /**
165     * Returns the last millisecond of the year.  This will be
166     * determined relative to the time zone specified in the constructor, or
167     * in the calendar instance passed in the most recent call to the
168     * {@link #peg(Calendar)} method.
169     *
170     * @return The last millisecond of the year.
171     *
172     * @see #getFirstMillisecond()
173     */
174    @Override
175    public long getLastMillisecond() {
176        return this.lastMillisecond;
177    }
178
179    /**
180     * Recalculates the start date/time and end date/time for this time period
181     * relative to the supplied calendar (which incorporates a time zone).
182     *
183     * @param calendar  the calendar ({@code null} not permitted).
184     */
185    @Override
186    public void peg(Calendar calendar) {
187        this.firstMillisecond = getFirstMillisecond(calendar);
188        this.lastMillisecond = getLastMillisecond(calendar);
189    }
190
191    /**
192     * Returns the year preceding this one.
193     * No matter what time zone and locale this instance was created with,
194     * the returned instance will use the default calendar for time
195     * calculations, obtained with {@link RegularTimePeriod#getCalendarInstance()}.
196     *
197     * @return The year preceding this one (or {@code null} if the
198     *         current year is -9999).
199     */
200    @Override
201    public RegularTimePeriod previous() {
202        if (this.year > Year.MINIMUM_YEAR) {
203            return new Year(this.year - 1);
204        }
205        else {
206            return null;
207        }
208    }
209
210    /**
211     * Returns the year following this one.
212     * No matter what time zone and locale this instance was created with,
213     * the returned instance will use the default calendar for time
214     * calculations, obtained with {@link RegularTimePeriod#getCalendarInstance()}.
215     *
216     * @return The year following this one (or {@code null} if the current
217     *         year is 9999).
218     */
219    @Override
220    public RegularTimePeriod next() {
221        if (this.year < Year.MAXIMUM_YEAR) {
222            return new Year(this.year + 1);
223        }
224        else {
225            return null;
226        }
227    }
228
229    /**
230     * Returns a serial index number for the year.
231     * <P>
232     * The implementation simply returns the year number (e.g. 2002).
233     *
234     * @return The serial index number.
235     */
236    @Override
237    public long getSerialIndex() {
238        return this.year;
239    }
240
241    /**
242     * Returns the first millisecond of the year, evaluated using the supplied
243     * calendar (which determines the time zone).
244     *
245     * @param calendar  the calendar ({@code null} not permitted).
246     *
247     * @return The first millisecond of the year.
248     *
249     * @throws NullPointerException if {@code calendar} is
250     *     {@code null}.
251     */
252    @Override
253    public long getFirstMillisecond(Calendar calendar) {
254        calendar.set(this.year, Calendar.JANUARY, 1, 0, 0, 0);
255        calendar.set(Calendar.MILLISECOND, 0);
256        return calendar.getTimeInMillis();
257    }
258
259    /**
260     * Returns the last millisecond of the year, evaluated using the supplied
261     * calendar (which determines the time zone).
262     *
263     * @param calendar  the calendar ({@code null} not permitted).
264     *
265     * @return The last millisecond of the year.
266     *
267     * @throws NullPointerException if {@code calendar} is
268     *     {@code null}.
269     */
270    @Override
271    public long getLastMillisecond(Calendar calendar) {
272        calendar.set(this.year, Calendar.DECEMBER, 31, 23, 59, 59);
273        calendar.set(Calendar.MILLISECOND, 999);
274        return calendar.getTimeInMillis();
275    }
276
277    /**
278     * Tests the equality of this {@code Year} object to an arbitrary
279     * object.  Returns {@code true} if the target is a {@code Year}
280     * instance representing the same year as this object.  In all other cases,
281     * returns {@code false}.
282     *
283     * @param obj  the object ({@code null} permitted).
284     *
285     * @return {@code true} if the year of this and the object are the
286     *         same.
287     */
288    @Override
289    public boolean equals(Object obj) {
290        if (obj == this) {
291            return true;
292        }
293        if (!(obj instanceof Year)) {
294            return false;
295        }
296        Year that = (Year) obj;
297        return (this.year == that.year);
298    }
299
300    /**
301     * Returns a hash code for this object instance.  The approach described by
302     * Joshua Bloch in "Effective Java" has been used here:
303     * <p>
304     * {@code http://developer.java.sun.com/developer/Books/effectivejava
305     *     /Chapter3.pdf}
306     *
307     * @return A hash code.
308     */
309    @Override
310    public int hashCode() {
311        int result = 17;
312        int c = this.year;
313        result = 37 * result + c;
314        return result;
315    }
316
317    /**
318     * Returns an integer indicating the order of this {@code Year} object
319     * relative to the specified object:
320     *
321     * negative == before, zero == same, positive == after.
322     *
323     * @param o1  the object to compare.
324     *
325     * @return negative == before, zero == same, positive == after.
326     */
327    @Override
328    public int compareTo(Object o1) {
329
330        int result;
331
332        // CASE 1 : Comparing to another Year object
333        // -----------------------------------------
334        if (o1 instanceof Year) {
335            Year y = (Year) o1;
336            result = this.year - y.getYear();
337        }
338
339        // CASE 2 : Comparing to another TimePeriod object
340        // -----------------------------------------------
341        else if (o1 instanceof RegularTimePeriod) {
342            // more difficult case - evaluate later...
343            result = 0;
344        }
345
346        // CASE 3 : Comparing to a non-TimePeriod object
347        // ---------------------------------------------
348        else {
349            // consider time periods to be ordered after general objects
350            result = 1;
351        }
352
353        return result;
354
355    }
356
357    /**
358     * Returns a string representing the year..
359     *
360     * @return A string representing the year.
361     */
362    @Override
363    public String toString() {
364        return Integer.toString(this.year);
365    }
366
367    /**
368     * Parses the string argument as a year.
369     * <P>
370     * The string format is YYYY.
371     *
372     * @param s  a string representing the year.
373     *
374     * @return {@code null} if the string is not parseable, the year
375     *         otherwise.
376     */
377    public static Year parseYear(String s) {
378
379        // parse the string...
380        int y;
381        try {
382            y = Integer.parseInt(s.trim());
383        }
384        catch (NumberFormatException e) {
385            throw new TimePeriodFormatException("Cannot parse string.");
386        }
387
388        // create the year...
389        try {
390            return new Year(y);
391        }
392        catch (IllegalArgumentException e) {
393            throw new TimePeriodFormatException("Year outside valid range.");
394        }
395    }
396
397}