1/*
2 * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package javax.xml.datatype;
27
28import java.math.BigDecimal;
29import java.math.BigInteger;
30import java.util.Calendar;
31import java.util.Date;
32import java.util.GregorianCalendar;
33
34import javax.xml.namespace.QName;
35
36/**
37 * <p>Immutable representation of a time span as defined in
38 * the W3C XML Schema 1.0 specification.
39 *
40 * <p>A Duration object represents a period of Gregorian time,
41 * which consists of six fields (years, months, days, hours,
42 * minutes, and seconds) plus a sign (+/-) field.
43 *
44 * <p>The first five fields have non-negative ({@literal >=}0) integers or null
45 * (which represents that the field is not set),
46 * and the seconds field has a non-negative decimal or null.
47 * A negative sign indicates a negative duration.
48 *
49 * <p>This class provides a number of methods that make it easy
50 * to use for the duration datatype of XML Schema 1.0 with
51 * the errata.
52 *
53 * <h2>Order relationship</h2>
54 * <p>Duration objects only have partial order, where two values A and B
55 * maybe either:
56 * <ol>
57 *  <li>A{@literal <}B (A is shorter than B)
58 *  <li>A{@literal >}B (A is longer than B)
59 *  <li>A==B   (A and B are of the same duration)
60 *  <li>A{@literal <>}B (Comparison between A and B is indeterminate)
61 * </ol>
62 *
63 * <p>For example, 30 days cannot be meaningfully compared to one month.
64 * The {@link #compare(Duration duration)} method implements this
65 * relationship.
66 *
67 * <p>See the {@link #isLongerThan(Duration)} method for details about
68 * the order relationship among {@code Duration} objects.
69 *
70 * <h2>Operations over Duration</h2>
71 * <p>This class provides a set of basic arithmetic operations, such
72 * as addition, subtraction and multiplication.
73 * Because durations don't have total order, an operation could
74 * fail for some combinations of operations. For example, you cannot
75 * subtract 15 days from 1 month. See the javadoc of those methods
76 * for detailed conditions where this could happen.
77 *
78 * <p>Also, division of a duration by a number is not provided because
79 * the {@code Duration} class can only deal with finite precision
80 * decimal numbers. For example, one cannot represent 1 sec divided by 3.
81 *
82 * <p>However, you could substitute a division by 3 with multiplying
83 * by numbers such as 0.3 or 0.333.
84 *
85 * <h2>Range of allowed values</h2>
86 * <p>
87 * Because some operations of {@code Duration} rely on {@link Calendar}
88 * even though {@link Duration} can hold very large or very small values,
89 * some of the methods may not work correctly on such {@code Duration}s.
90 * The impacted methods document their dependency on {@link Calendar}.
91 *
92 * @author <a href="mailto:Joseph.Fialli@Sun.COM">Joseph Fialli</a>
93 * @author <a href="mailto:Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
94 * @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
95 * @author <a href="mailto:Sunitha.Reddy@Sun.com">Sunitha Reddy</a>
96 * @see XMLGregorianCalendar#add(Duration)
97 * @since 1.5
98 */
99public abstract class Duration {
100
101    /**
102     * Debugging {@code true} or {@code false}.
103     */
104    private static final boolean DEBUG = true;
105
106    /**
107     * Default no-arg constructor.
108     *
109     * <p>Note: Always use the {@link DatatypeFactory} to
110     * construct an instance of {@code Duration}.
111     * The constructor on this class cannot be guaranteed to
112     * produce an object with a consistent state and may be
113     * removed in the future.
114     */
115    public Duration() {
116    }
117
118    /**
119     * Return the name of the XML Schema date/time type that this instance
120     * maps to. Type is computed based on fields that are set,
121     * i.e. {@link #isSet(DatatypeConstants.Field field)} == {@code true}.
122     *
123     * <table class="striped">
124     *   <caption>Required fields for XML Schema 1.0 Date/Time Datatypes.<br>
125     *         <i>(timezone is optional for all date/time datatypes)</i></caption>
126     *   <thead>
127     *     <tr>
128     *       <th>Datatype</th>
129     *       <th>year</th>
130     *       <th>month</th>
131     *       <th>day</th>
132     *       <th>hour</th>
133     *       <th>minute</th>
134     *       <th>second</th>
135     *     </tr>
136     *   </thead>
137     *   <tbody>
138     *     <tr>
139     *       <td>{@link DatatypeConstants#DURATION}</td>
140     *       <td>X</td>
141     *       <td>X</td>
142     *       <td>X</td>
143     *       <td>X</td>
144     *       <td>X</td>
145     *       <td>X</td>
146     *     </tr>
147     *     <tr>
148     *       <td>{@link DatatypeConstants#DURATION_DAYTIME}</td>
149     *       <td></td>
150     *       <td></td>
151     *       <td>X</td>
152     *       <td>X</td>
153     *       <td>X</td>
154     *       <td>X</td>
155     *     </tr>
156     *     <tr>
157     *       <td>{@link DatatypeConstants#DURATION_YEARMONTH}</td>
158     *       <td>X</td>
159     *       <td>X</td>
160     *       <td></td>
161     *       <td></td>
162     *       <td></td>
163     *       <td></td>
164     *     </tr>
165     *   </tbody>
166     * </table>
167     *
168     * @return one of the following constants:
169     *   {@link DatatypeConstants#DURATION},
170     *   {@link DatatypeConstants#DURATION_DAYTIME} or
171     *   {@link DatatypeConstants#DURATION_YEARMONTH}.
172     *
173     * @throws IllegalStateException If the combination of set fields does not match one of the XML Schema date/time datatypes.
174     */
175    public QName getXMLSchemaType() {
176
177        boolean yearSet = isSet(DatatypeConstants.YEARS);
178        boolean monthSet = isSet(DatatypeConstants.MONTHS);
179        boolean daySet = isSet(DatatypeConstants.DAYS);
180        boolean hourSet = isSet(DatatypeConstants.HOURS);
181        boolean minuteSet = isSet(DatatypeConstants.MINUTES);
182        boolean secondSet = isSet(DatatypeConstants.SECONDS);
183
184        // DURATION
185        if (yearSet
186            && monthSet
187            && daySet
188            && hourSet
189            && minuteSet
190            && secondSet) {
191            return DatatypeConstants.DURATION;
192        }
193
194        // DURATION_DAYTIME
195        if (!yearSet
196            && !monthSet
197            && daySet
198            && hourSet
199            && minuteSet
200            && secondSet) {
201            return DatatypeConstants.DURATION_DAYTIME;
202        }
203
204        // DURATION_YEARMONTH
205        if (yearSet
206            && monthSet
207            && !daySet
208            && !hourSet
209            && !minuteSet
210            && !secondSet) {
211            return DatatypeConstants.DURATION_YEARMONTH;
212        }
213
214        // nothing matches
215        throw new IllegalStateException(
216                "javax.xml.datatype.Duration#getXMLSchemaType():"
217                + " this Duration does not match one of the XML Schema date/time datatypes:"
218                + " year set = " + yearSet
219                + " month set = " + monthSet
220                + " day set = " + daySet
221                + " hour set = " + hourSet
222                + " minute set = " + minuteSet
223                + " second set = " + secondSet
224        );
225    }
226
227    /**
228     * Returns the sign of this duration in -1,0, or 1.
229     *
230     * @return
231     *      -1 if this duration is negative, 0 if the duration is zero,
232     *      and 1 if the duration is positive.
233     */
234    public abstract int getSign();
235
236    /**
237     * Get the years value of this {@code Duration} as an {@code int} or {@code 0} if not present.
238     *
239     * <p>{@code getYears()} is a convenience method for
240     * {@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)}.
241     *
242     * <p>As the return value is an {@code int}, an incorrect value will be returned for {@code Duration}s
243     * with years that go beyond the range of an {@code int}.
244     * Use {@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)} to avoid possible loss of precision.
245     *
246     * @return If the years field is present, return its value as an {@code int}, else return {@code 0}.
247     */
248    public int getYears() {
249        return getField(DatatypeConstants.YEARS).intValue();
250    }
251
252    /**
253     * Obtains the value of the MONTHS field as an integer value,
254     * or 0 if not present.
255     *
256     * This method works just like {@link #getYears()} except
257     * that this method works on the MONTHS field.
258     *
259     * @return Months of this {@code Duration}.
260     */
261    public int getMonths() {
262        return getField(DatatypeConstants.MONTHS).intValue();
263    }
264
265    /**
266     * Obtains the value of the DAYS field as an integer value,
267     * or 0 if not present.
268     *
269     * This method works just like {@link #getYears()} except
270     * that this method works on the DAYS field.
271     *
272     * @return Days of this {@code Duration}.
273     */
274    public int getDays() {
275        return getField(DatatypeConstants.DAYS).intValue();
276    }
277
278    /**
279     * Obtains the value of the HOURS field as an integer value,
280     * or 0 if not present.
281     *
282     * This method works just like {@link #getYears()} except
283     * that this method works on the HOURS field.
284     *
285     * @return Hours of this {@code Duration}.
286     *
287     */
288    public int getHours() {
289        return getField(DatatypeConstants.HOURS).intValue();
290    }
291
292    /**
293     * Obtains the value of the MINUTES field as an integer value,
294     * or 0 if not present.
295     *
296     * This method works just like {@link #getYears()} except
297     * that this method works on the MINUTES field.
298     *
299     * @return Minutes of this {@code Duration}.
300     *
301     */
302    public int getMinutes() {
303        return getField(DatatypeConstants.MINUTES).intValue();
304    }
305
306    /**
307     * Obtains the value of the SECONDS field as an integer value,
308     * or 0 if not present.
309     *
310     * This method works just like {@link #getYears()} except
311     * that this method works on the SECONDS field.
312     *
313     * @return seconds in the integer value. The fraction of seconds
314     *   will be discarded (for example, if the actual value is 2.5,
315     *   this method returns 2)
316     */
317    public int getSeconds() {
318        return getField(DatatypeConstants.SECONDS).intValue();
319    }
320
321    /**
322     * Returns the length of the duration in milli-seconds.
323     *
324     * <p>If the seconds field carries more digits than milli-second order,
325     * those will be simply discarded (or in other words, rounded to zero.)
326     * For example, for any Calendar value {@code x},
327     * <pre>
328     * {@code new Duration("PT10.00099S").getTimeInMills(x) == 10000}
329     * {@code new Duration("-PT10.00099S").getTimeInMills(x) == -10000}
330     * </pre>
331     *
332     * <p>
333     * Note that this method uses the {@link #addTo(Calendar)} method,
334     * which may work incorrectly with {@code Duration} objects with
335     * very large values in its fields. See the {@link #addTo(Calendar)}
336     * method for details.
337     *
338     * @param startInstant
339     *      The length of a month/year varies. The {@code startInstant} is
340     *      used to disambiguate this variance. Specifically, this method
341     *      returns the difference between {@code startInstant} and
342     *      {@code startInstant+duration}
343     *
344     * @return milliseconds between {@code startInstant} and
345     *   {@code startInstant} plus this {@code Duration}
346     *
347     * @throws NullPointerException if {@code startInstant} parameter
348     * is null.
349     *
350     */
351    public long getTimeInMillis(final Calendar startInstant) {
352        Calendar cal = (Calendar) startInstant.clone();
353        addTo(cal);
354        return getCalendarTimeInMillis(cal)
355                    - getCalendarTimeInMillis(startInstant);
356    }
357
358    /**
359     * Returns the length of the duration in milli-seconds.
360     *
361     * <p>If the seconds field carries more digits than milli-second order,
362     * those will be simply discarded (or in other words, rounded to zero.)
363     * For example, for any {@code Date} value {@code x},
364     * <pre>
365     * {@code new Duration("PT10.00099S").getTimeInMills(x) == 10000}
366     * {@code new Duration("-PT10.00099S").getTimeInMills(x) == -10000}
367     * </pre>
368     *
369     * <p>
370     * Note that this method uses the {@link #addTo(Date)} method,
371     * which may work incorrectly with {@code Duration} objects with
372     * very large values in its fields. See the {@link #addTo(Date)}
373     * method for details.
374     *
375     * @param startInstant
376     *      The length of a month/year varies. The {@code startInstant} is
377     *      used to disambiguate this variance. Specifically, this method
378     *      returns the difference between {@code startInstant} and
379     *      {@code startInstant+duration}.
380     *
381     * @throws NullPointerException
382     *      If the startInstant parameter is null.
383     *
384     * @return milliseconds between {@code startInstant} and
385     *   {@code startInstant} plus this {@code Duration}
386     *
387     * @see #getTimeInMillis(Calendar)
388     */
389    public long getTimeInMillis(final Date startInstant) {
390        Calendar cal = new GregorianCalendar();
391        cal.setTime(startInstant);
392        this.addTo(cal);
393        return getCalendarTimeInMillis(cal) - startInstant.getTime();
394    }
395
396    /**
397     * Gets the value of a field.
398     *
399     * Fields of a duration object may contain arbitrary large value.
400     * Therefore this method is designed to return a {@link Number} object.
401     *
402     * In case of YEARS, MONTHS, DAYS, HOURS, and MINUTES, the returned
403     * number will be a non-negative integer. In case of seconds,
404     * the returned number may be a non-negative decimal value.
405     *
406     * @param field
407     *      one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
408     *      MINUTES, or SECONDS.)
409     * @return
410     *      If the specified field is present, this method returns
411     *      a non-null non-negative {@link Number} object that
412     *      represents its value. If it is not present, return null.
413     *      For YEARS, MONTHS, DAYS, HOURS, and MINUTES, this method
414     *      returns a {@link java.math.BigInteger} object. For SECONDS, this
415     *      method returns a {@link java.math.BigDecimal}.
416     *
417     * @throws NullPointerException If the {@code field} is {@code null}.
418     */
419    public abstract Number getField(final DatatypeConstants.Field field);
420
421    /**
422     * Checks if a field is set.
423     *
424     * A field of a duration object may or may not be present.
425     * This method can be used to test if a field is present.
426     *
427     * @param field
428     *      one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
429     *      MINUTES, or SECONDS.)
430     * @return
431     *      true if the field is present. false if not.
432     *
433     * @throws NullPointerException
434     *      If the field parameter is null.
435     */
436    public abstract boolean isSet(final DatatypeConstants.Field field);
437
438    /**
439     * Computes a new duration whose value is {@code this+rhs}.
440     *
441     * <p>For example,
442     * <pre>
443     * "1 day" + "-3 days" = "-2 days"
444     * "1 year" + "1 day" = "1 year and 1 day"
445     * "-(1 hour,50 minutes)" + "-20 minutes" = "-(1 hours,70 minutes)"
446     * "15 hours" + "-3 days" = "-(2 days,9 hours)"
447     * "1 year" + "-1 day" = IllegalStateException
448     * </pre>
449     *
450     * <p>Since there's no way to meaningfully subtract 1 day from 1 month,
451     * there are cases where the operation fails in
452     * {@link IllegalStateException}.
453     *
454     * <p>
455     * Formally, the computation is defined as follows.
456     * <p>
457     * Firstly, we can assume that two {@code Duration}s to be added
458     * are both positive without losing generality (i.e.,
459     * {@code (-X)+Y=Y-X}, {@code X+(-Y)=X-Y},
460     * {@code (-X)+(-Y)=-(X+Y)})
461     *
462     * <p>
463     * Addition of two positive {@code Duration}s are simply defined as
464     * field by field addition where missing fields are treated as 0.
465     * <p>
466     * A field of the resulting {@code Duration} will be unset if and
467     * only if respective fields of two input {@code Duration}s are unset.
468     * <p>
469     * Note that {@code lhs.add(rhs)} will be always successful if
470     * {@code lhs.signum()*rhs.signum()!=-1} or both of them are
471     * normalized.
472     *
473     * @param rhs {@code Duration} to add to this {@code Duration}
474     *
475     * @return
476     *      non-null valid Duration object.
477     *
478     * @throws NullPointerException
479     *      If the rhs parameter is null.
480     * @throws IllegalStateException
481     *      If two durations cannot be meaningfully added. For
482     *      example, adding negative one day to one month causes
483     *      this exception.
484     *
485     *
486     * @see #subtract(Duration)
487     */
488    public abstract Duration add(final Duration rhs);
489
490    /**
491     * Adds this duration to a {@link Calendar} object.
492     *
493     * <p>
494     * Calls {@link java.util.Calendar#add(int,int)} in the
495     * order of YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, and MILLISECONDS
496     * if those fields are present. Because the {@link Calendar} class
497     * uses int to hold values, there are cases where this method
498     * won't work correctly (for example if values of fields
499     * exceed the range of int.)
500     *
501     * <p>
502     * Also, since this duration class is a Gregorian duration, this
503     * method will not work correctly if the given {@link Calendar}
504     * object is based on some other calendar systems.
505     *
506     * <p>
507     * Any fractional parts of this {@code Duration} object
508     * beyond milliseconds will be simply ignored. For example, if
509     * this duration is "P1.23456S", then 1 is added to SECONDS,
510     * 234 is added to MILLISECONDS, and the rest will be unused.
511     *
512     * <p>
513     * Note that because {@link Calendar#add(int, int)} is using
514     * {@code int}, {@code Duration} with values beyond the
515     * range of {@code int} in its fields
516     * will cause overflow/underflow to the given {@link Calendar}.
517     * {@link XMLGregorianCalendar#add(Duration)} provides the same
518     * basic operation as this method while avoiding
519     * the overflow/underflow issues.
520     *
521     * @param calendar
522     *      A calendar object whose value will be modified.
523     * @throws NullPointerException
524     *      if the calendar parameter is null.
525     */
526    public abstract void addTo(Calendar calendar);
527
528    /**
529     * Adds this duration to a {@link Date} object.
530     *
531     * <p>
532     * The given date is first converted into
533     * a {@link java.util.GregorianCalendar}, then the duration
534     * is added exactly like the {@link #addTo(Calendar)} method.
535     *
536     * <p>
537     * The updated time instant is then converted back into a
538     * {@link Date} object and used to update the given {@link Date} object.
539     *
540     * <p>
541     * This somewhat redundant computation is necessary to unambiguously
542     * determine the duration of months and years.
543     *
544     * @param date
545     *      A date object whose value will be modified.
546     * @throws NullPointerException
547     *      if the date parameter is null.
548     */
549    public void addTo(Date date) {
550
551        // check data parameter
552        if (date == null) {
553            throw new NullPointerException(
554                "Cannot call "
555                + this.getClass().getName()
556                + "#addTo(Date date) with date == null."
557            );
558        }
559
560        Calendar cal = new GregorianCalendar();
561        cal.setTime(date);
562        this.addTo(cal);
563        date.setTime(getCalendarTimeInMillis(cal));
564    }
565
566    /**
567     * Computes a new duration whose value is {@code this-rhs}.
568     *
569     * <p>For example:
570     * <pre>
571     * "1 day" - "-3 days" = "4 days"
572     * "1 year" - "1 day" = IllegalStateException
573     * "-(1 hour,50 minutes)" - "-20 minutes" = "-(1hours,30 minutes)"
574     * "15 hours" - "-3 days" = "3 days and 15 hours"
575     * "1 year" - "-1 day" = "1 year and 1 day"
576     * </pre>
577     *
578     * <p>Since there's no way to meaningfully subtract 1 day from 1 month,
579     * there are cases where the operation fails in {@link IllegalStateException}.
580     *
581     * <p>Formally the computation is defined as follows.
582     * First, we can assume that two {@code Duration}s are both positive
583     * without losing generality.  (i.e.,
584     * {@code (-X)-Y=-(X+Y)}, {@code X-(-Y)=X+Y},
585     * {@code (-X)-(-Y)=-(X-Y)})
586     *
587     * <p>Then two durations are subtracted field by field.
588     * If the sign of any non-zero field {@code F} is different from
589     * the sign of the most significant field,
590     * 1 (if {@code F} is negative) or -1 (otherwise)
591     * will be borrowed from the next bigger unit of {@code F}.
592     *
593     * <p>This process is repeated until all the non-zero fields have
594     * the same sign.
595     *
596     * <p>If a borrow occurs in the days field (in other words, if
597     * the computation needs to borrow 1 or -1 month to compensate
598     * days), then the computation fails by throwing an
599     * {@link IllegalStateException}.
600     *
601     * @param rhs {@code Duration} to subtract from this {@code Duration}.
602     *
603     * @return New {@code Duration} created from subtracting {@code rhs} from this {@code Duration}.
604     *
605     * @throws IllegalStateException
606     *      If two durations cannot be meaningfully subtracted. For
607     *      example, subtracting one day from one month causes
608     *      this exception.
609     *
610     * @throws NullPointerException
611     *      If the rhs parameter is null.
612     *
613     * @see #add(Duration)
614     */
615    public Duration subtract(final Duration rhs) {
616        return add(rhs.negate());
617    }
618
619    /**
620     * Computes a new duration whose value is {@code factor} times
621     * longer than the value of this duration.
622     *
623     * <p>This method is provided for the convenience.
624     * It is functionally equivalent to the following code:
625     * <pre>
626     * multiply(new BigDecimal(String.valueOf(factor)))
627     * </pre>
628     *
629     * @param factor Factor times longer of new {@code Duration} to create.
630     *
631     * @return New {@code Duration} that is {@code factor}times longer than this {@code Duration}.
632     *
633     * @see #multiply(BigDecimal)
634     */
635    public Duration multiply(int factor) {
636        return multiply(new BigDecimal(String.valueOf(factor)));
637    }
638
639    /**
640     * Computes a new duration whose value is {@code factor} times
641     * longer than the value of this duration.
642     *
643     * <p>
644     * For example,
645     * <pre>
646     * "P1M" (1 month) * "12" = "P12M" (12 months)
647     * "PT1M" (1 min) * "0.3" = "PT18S" (18 seconds)
648     * "P1M" (1 month) * "1.5" = IllegalStateException
649     * </pre>
650     *
651     * <p>
652     * Since the {@code Duration} class is immutable, this method
653     * doesn't change the value of this object. It simply computes
654     * a new Duration object and returns it.
655     *
656     * <p>
657     * The operation will be performed field by field with the precision
658     * of {@link BigDecimal}. Since all the fields except seconds are
659     * restricted to hold integers,
660     * any fraction produced by the computation will be
661     * carried down toward the next lower unit. For example,
662     * if you multiply "P1D" (1 day) with "0.5", then it will be 0.5 day,
663     * which will be carried down to "PT12H" (12 hours).
664     * When fractions of month cannot be meaningfully carried down
665     * to days, or year to months, this will cause an
666     * {@link IllegalStateException} to be thrown.
667     * For example if you multiple one month by 0.5.
668     *
669     * <p>
670     * To avoid {@link IllegalStateException}, use
671     * the {@link #normalizeWith(Calendar)} method to remove the years
672     * and months fields.
673     *
674     * @param factor to multiply by
675     *
676     * @return
677     *      returns a non-null valid {@code Duration} object
678     *
679     * @throws IllegalStateException if operation produces fraction in
680     * the months field.
681     *
682     * @throws NullPointerException if the {@code factor} parameter is
683     * {@code null}.
684     *
685     */
686    public abstract Duration multiply(final BigDecimal factor);
687
688    /**
689     * Returns a new {@code Duration} object whose
690     * value is {@code -this}.
691     *
692     * <p>
693     * Since the {@code Duration} class is immutable, this method
694     * doesn't change the value of this object. It simply computes
695     * a new Duration object and returns it.
696     *
697     * @return
698     *      always return a non-null valid {@code Duration} object.
699     */
700    public abstract Duration negate();
701
702    /**
703     * Converts the years and months fields into the days field
704     * by using a specific time instant as the reference point.
705     *
706     * <p>For example, duration of one month normalizes to 31 days
707     * given the start time instance "July 8th 2003, 17:40:32".
708     *
709     * <p>Formally, the computation is done as follows:
710     * <ol>
711     *  <li>the given Calendar object is cloned</li>
712     *  <li>the years, months and days fields will be added to the {@link Calendar} object
713     *      by using the {@link Calendar#add(int,int)} method</li>
714     *  <li>the difference between the two Calendars in computed in milliseconds and converted to days,
715     *     if a remainder occurs due to Daylight Savings Time, it is discarded</li>
716     *  <li>the computed days, along with the hours, minutes and seconds
717     *      fields of this duration object is used to construct a new
718     *      Duration object.</li>
719     * </ol>
720     *
721     * <p>Note that since the Calendar class uses {@code int} to
722     * hold the value of year and month, this method may produce
723     * an unexpected result if this duration object holds
724     * a very large value in the years or months fields.
725     *
726     * @param startTimeInstant {@code Calendar} reference point.
727     *
728     * @return {@code Duration} of years and months of this {@code Duration} as days.
729     *
730     * @throws NullPointerException If the startTimeInstant parameter is null.
731     */
732    public abstract Duration normalizeWith(final Calendar startTimeInstant);
733
734    /**
735     * Partial order relation comparison with this {@code Duration} instance.
736     *
737     * <p>Comparison result must be in accordance with
738     * <a href="http://www.w3.org/TR/xmlschema-2/#duration-order">W3C XML Schema 1.0 Part 2, Section 3.2.7.6.2,
739     * <i>Order relation on duration</i></a>.
740     *
741     * <p>Return:
742     * <ul>
743     *   <li>{@link DatatypeConstants#LESSER} if this {@code Duration} is shorter than {@code duration} parameter</li>
744     *   <li>{@link DatatypeConstants#EQUAL} if this {@code Duration} is equal to {@code duration} parameter</li>
745     *   <li>{@link DatatypeConstants#GREATER} if this {@code Duration} is longer than {@code duration} parameter</li>
746     *   <li>{@link DatatypeConstants#INDETERMINATE} if a conclusive partial order relation cannot be determined</li>
747     * </ul>
748     *
749     * @param duration to compare
750     *
751     * @return the relationship between {@code this Duration} and {@code duration} parameter as
752     *   {@link DatatypeConstants#LESSER}, {@link DatatypeConstants#EQUAL}, {@link DatatypeConstants#GREATER}
753     *   or {@link DatatypeConstants#INDETERMINATE}.
754     *
755     * @throws UnsupportedOperationException If the underlying implementation
756     *   cannot reasonably process the request, e.g. W3C XML Schema allows for
757     *   arbitrarily large/small/precise values, the request may be beyond the
758     *   implementations capability.
759     * @throws NullPointerException if {@code duration} is {@code null}.
760     *
761     * @see #isShorterThan(Duration)
762     * @see #isLongerThan(Duration)
763     */
764    public abstract int compare(final Duration duration);
765
766    /**
767     * Checks if this duration object is strictly longer than
768     * another {@code Duration} object.
769     *
770     * <p>Duration X is "longer" than Y if and only if X {@literal >} Y
771     * as defined in the section 3.2.6.2 of the XML Schema 1.0
772     * specification.
773     *
774     * <p>For example, "P1D" (one day) {@literal >} "PT12H" (12 hours) and
775     * "P2Y" (two years) {@literal >} "P23M" (23 months).
776     *
777     * @param duration {@code Duration} to test this {@code Duration} against.
778     *
779     * @throws UnsupportedOperationException If the underlying implementation
780     *   cannot reasonably process the request, e.g. W3C XML Schema allows for
781     *   arbitrarily large/small/precise values, the request may be beyond the
782     *   implementations capability.
783     * @throws NullPointerException If {@code duration} is null.
784     *
785     * @return
786     *      true if the duration represented by this object
787     *      is longer than the given duration. false otherwise.
788     *
789     * @see #isShorterThan(Duration)
790     * @see #compare(Duration duration)
791     */
792    public boolean isLongerThan(final Duration duration) {
793        return compare(duration) == DatatypeConstants.GREATER;
794    }
795
796    /**
797     * Checks if this duration object is strictly shorter than
798     * another {@code Duration} object.
799     *
800     * @param duration {@code Duration} to test this {@code Duration} against.
801     *
802     * @return {@code true} if {@code duration} parameter is shorter than this {@code Duration},
803     *   else {@code false}.
804     *
805     * @throws UnsupportedOperationException If the underlying implementation
806     *   cannot reasonably process the request, e.g. W3C XML Schema allows for
807     *   arbitrarily large/small/precise values, the request may be beyond the
808     *   implementations capability.
809     * @throws NullPointerException if {@code duration} is null.
810     *
811     * @see #isLongerThan(Duration duration)
812     * @see #compare(Duration duration)
813     */
814    public boolean isShorterThan(final Duration duration) {
815        return compare(duration) == DatatypeConstants.LESSER;
816    }
817
818    /**
819     * Checks if this duration object has the same duration
820     * as another {@code Duration} object.
821     *
822     * <p>For example, "P1D" (1 day) is equal to "PT24H" (24 hours).
823     *
824     * <p>Duration X is equal to Y if and only if time instant
825     * t+X and t+Y are the same for all the test time instants
826     * specified in the section 3.2.6.2 of the XML Schema 1.0
827     * specification.
828     *
829     * <p>Note that there are cases where two {@code Duration}s are
830     * "incomparable" to each other, like one month and 30 days.
831     * For example,
832     * <pre>
833     * !new Duration("P1M").isShorterThan(new Duration("P30D"))
834     * !new Duration("P1M").isLongerThan(new Duration("P30D"))
835     * !new Duration("P1M").equals(new Duration("P30D"))
836     * </pre>
837     *
838     * @param duration
839     *      The object to compare this {@code Duration} against.
840     *
841     * @return
842     *      {@code true} if this duration is the same length as
843     *         {@code duration}.
844     *      {@code false} if {@code duration} is {@code null},
845     *         is not a
846     *         {@code Duration} object,
847     *         or its length is different from this duration.
848     *
849     * @throws UnsupportedOperationException If the underlying implementation
850     *   cannot reasonably process the request, e.g. W3C XML Schema allows for
851     *   arbitrarily large/small/precise values, the request may be beyond the
852     *   implementations capability.
853     *
854     * @see #compare(Duration duration)
855     */
856    public boolean equals(final Object duration) {
857
858        if (duration == null || !(duration instanceof Duration)) {
859            return false;
860        }
861
862        return compare((Duration) duration) == DatatypeConstants.EQUAL;
863    }
864
865    /**
866     * Returns a hash code consistent with the definition of the equals method.
867     *
868     * @see Object#hashCode()
869     */
870    public abstract int hashCode();
871
872    /**
873     * Returns a {@code String} representation of this {@code Duration Object}.
874     *
875     * <p>The result is formatted according to the XML Schema 1.0 spec
876     * and can be always parsed back later into the
877     * equivalent {@code Duration Object} by {@link DatatypeFactory#newDuration(String  lexicalRepresentation)}.
878     *
879     * <p>Formally, the following holds for any {@code Duration}
880     * {@code Object} x:
881     * <pre>
882     * new Duration(x.toString()).equals(x)
883     * </pre>
884     *
885     * @return A non-{@code null} valid {@code String} representation of this {@code Duration}.
886     */
887    public String toString() {
888
889        StringBuffer buf = new StringBuffer();
890
891        if (getSign() < 0) {
892            buf.append('-');
893        }
894        buf.append('P');
895
896        BigInteger years = (BigInteger) getField(DatatypeConstants.YEARS);
897        if (years != null) {
898            buf.append(years + "Y");
899        }
900
901        BigInteger months = (BigInteger) getField(DatatypeConstants.MONTHS);
902        if (months != null) {
903            buf.append(months + "M");
904        }
905
906        BigInteger days = (BigInteger) getField(DatatypeConstants.DAYS);
907        if (days != null) {
908            buf.append(days + "D");
909        }
910
911        BigInteger hours = (BigInteger) getField(DatatypeConstants.HOURS);
912        BigInteger minutes = (BigInteger) getField(DatatypeConstants.MINUTES);
913        BigDecimal seconds = (BigDecimal) getField(DatatypeConstants.SECONDS);
914        if (hours != null || minutes != null || seconds != null) {
915            buf.append('T');
916            if (hours != null) {
917                buf.append(hours + "H");
918            }
919            if (minutes != null) {
920                buf.append(minutes + "M");
921            }
922            if (seconds != null) {
923                buf.append(toString(seconds) + "S");
924            }
925        }
926
927        return buf.toString();
928    }
929
930    /**
931     * Turns {@link BigDecimal} to a string representation.
932     *
933     * <p>Due to a behavior change in the {@link BigDecimal#toString()}
934     * method in JDK1.5, this had to be implemented here.
935     *
936     * @param bd {@code BigDecimal} to format as a {@code String}
937     *
938     * @return  {@code String} representation of {@code BigDecimal}
939     */
940    private String toString(BigDecimal bd) {
941        String intString = bd.unscaledValue().toString();
942        int scale = bd.scale();
943
944        if (scale == 0) {
945            return intString;
946        }
947
948        /* Insert decimal point */
949        StringBuffer buf;
950        int insertionPoint = intString.length() - scale;
951        if (insertionPoint == 0) { /* Point goes right before intVal */
952            return "0." + intString;
953        } else if (insertionPoint > 0) { /* Point goes inside intVal */
954            buf = new StringBuffer(intString);
955            buf.insert(insertionPoint, '.');
956        } else { /* We must insert zeros between point and intVal */
957            buf = new StringBuffer(3 - insertionPoint + intString.length());
958            buf.append("0.");
959            for (int i = 0; i < -insertionPoint; i++) {
960                buf.append('0');
961            }
962            buf.append(intString);
963        }
964        return buf.toString();
965    }
966
967
968    /**
969     * Calls the {@link Calendar#getTimeInMillis} method.
970     * Prior to JDK1.4, this method was protected and therefore
971     * cannot be invoked directly.
972     *
973     * <p>TODO: In future, this should be replaced by {@code cal.getTimeInMillis()}.
974     *
975     * @param cal {@code Calendar} to get time in milliseconds.
976     *
977     * @return Milliseconds of {@code cal}.
978     */
979    private static long getCalendarTimeInMillis(final Calendar cal) {
980        return cal.getTime().getTime();
981    }
982}
983