KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > xml > datatype > Duration


1 // $Id: Duration.java,v 1.36.8.1.4.3 2004/06/07 06:33:50 jsuttor Exp $
2

3 /*
4  * @(#)Duration.java 1.13 04/07/26
5  *
6  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
7  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
8  */

9
10 package javax.xml.datatype;
11
12 import java.math.BigDecimal JavaDoc;
13 import java.math.BigInteger JavaDoc;
14 import java.util.Calendar JavaDoc;
15 import java.util.Date JavaDoc;
16 import java.util.GregorianCalendar JavaDoc;
17
18 import javax.xml.namespace.QName JavaDoc;
19
20 /**
21  * <p>Immutable representation of a time span as defined in
22  * the W3C XML Schema 1.0 specification.</p>
23  *
24  * <p>A Duration object represents a period of Gregorian time,
25  * which consists of six fields (years, months, days, hours,
26  * minutes, and seconds) plus a sign (+/-) field.</p>
27  *
28  * <p>The first five fields have non-negative (>=0) integers or null
29  * (which represents that the field is not set),
30  * and the seconds field has a non-negative decimal or null.
31  * A negative sign indicates a negative duration.</p>
32  *
33  * <p>This class provides a number of methods that make it easy
34  * to use for the duration datatype of XML Schema 1.0 with
35  * the errata.</p>
36  *
37  * <h2>Order relationship</h2>
38  * <p>Duration objects only have partial order, where two values A and B
39  * maybe either:</p>
40  * <ol>
41  * <li>A&lt;B (A is shorter than B)
42  * <li>A&gt;B (A is longer than B)
43  * <li>A==B (A and B are of the same duration)
44  * <li>A&lt;>B (Comparison between A and B is indeterminate)
45  * </ol>
46
47  * * <p>For example, 30 days cannot be meaningfully compared to one month.
48  * The {@link #compare(Duration duration)} method implements this
49  * relationship.</p>
50  *
51  * <p>See the {@link #isLongerThan(Duration)} method for details about
52  * the order relationship among <code>Duration</code> objects.</p>
53  *
54  * <h2>Operations over Duration</h2>
55  * <p>This class provides a set of basic arithmetic operations, such
56  * as addition, subtraction and multiplication.
57  * Because durations don't have total order, an operation could
58  * fail for some combinations of operations. For example, you cannot
59  * subtract 15 days from 1 month. See the javadoc of those methods
60  * for detailed conditions where this could happen.</p>
61  *
62  * <p>Also, division of a duration by a number is not provided because
63  * the <code>Duration</code> class can only deal with finite precision
64  * decimal numbers. For example, one cannot represent 1 sec divided by 3.</p>
65  *
66  * <p>However, you could substitute a division by 3 with multiplying
67  * by numbers such as 0.3 or 0.333.</p>
68  *
69  * <h2>Range of allowed values</h2>
70  * <p>
71  * Because some operations of <code>Duration</code> rely on {@link Calendar}
72  * even though {@link Duration} can hold very large or very small values,
73  * some of the methods may not work correctly on such <code>Duration</code>s.
74  * The impacted methods document their dependency on {@link Calendar}.
75  *
76  *
77  * @author <a HREF="mailto:Joseph.Fialli@Sun.COM">Joseph Fialli</a>
78  * @author <a HREF="mailto:Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
79  * @author <a HREF="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
80  * @version $Revision: 1.36.8.1.4.3 $, $Date: 2004/06/07 06:33:50 $
81  * @see XMLGregorianCalendar#add(Duration)
82  * @since 1.5
83  */

84 public abstract class Duration {
85         
86     /**
87      * <p>Debugging <code>true</code> or <code>false</code>.</p>
88      */

89     private static final boolean DEBUG = true;
90
91     /**
92      * <p>Return the name of the XML Schema date/time type that this instance
93      * maps to. Type is computed based on fields that are set,
94      * i.e. {@link #isSet(DatatypeConstants.Field field)} == <code>true</code>.</p>
95      *
96      * <table border="2" rules="all" cellpadding="2">
97      * <thead>
98      * <tr>
99      * <th align="center" colspan="7">
100      * Required fields for XML Schema 1.0 Date/Time Datatypes.<br/>
101      * <i>(timezone is optional for all date/time datatypes)</i>
102      * </th>
103      * </tr>
104      * </thead>
105      * <tbody>
106      * <tr>
107      * <td>Datatype</td>
108      * <td>year</td>
109      * <td>month</td>
110      * <td>day</td>
111      * <td>hour</td>
112      * <td>minute</td>
113      * <td>second</td>
114      * </tr>
115      * <tr>
116      * <td>{@link DatatypeConstants#DURATION}</td>
117      * <td>X</td>
118      * <td>X</td>
119      * <td>X</td>
120      * <td>X</td>
121      * <td>X</td>
122      * <td>X</td>
123      * </tr>
124      * <tr>
125      * <td>{@link DatatypeConstants#DURATION_DAYTIME}</td>
126      * <td></td>
127      * <td></td>
128      * <td>X</td>
129      * <td>X</td>
130      * <td>X</td>
131      * <td>X</td>
132      * </tr>
133      * <tr>
134      * <td>{@link DatatypeConstants#DURATION_YEARMONTH}</td>
135      * <td>X</td>
136      * <td>X</td>
137      * <td></td>
138      * <td></td>
139      * <td></td>
140      * <td></td>
141      * </tr>
142      * </tbody>
143      * </table>
144      *
145      * @return one of the following constants:
146      * {@link DatatypeConstants#DURATION},
147      * {@link DatatypeConstants#DURATION_DAYTIME} or
148      * {@link DatatypeConstants#DURATION_YEARMONTH}.
149      *
150      * @throws IllegalStateException If the combination of set fields does not match one of the XML Schema date/time datatypes.
151      */

152     public QName JavaDoc getXMLSchemaType() {
153         
154         boolean yearSet = isSet(DatatypeConstants.YEARS);
155         boolean monthSet = isSet(DatatypeConstants.MONTHS);
156         boolean daySet = isSet(DatatypeConstants.DAYS);
157         boolean hourSet = isSet(DatatypeConstants.HOURS);
158         boolean minuteSet = isSet(DatatypeConstants.MINUTES);
159         boolean secondSet = isSet(DatatypeConstants.SECONDS);
160         
161         // DURATION
162
if (yearSet
163             && monthSet
164             && daySet
165             && hourSet
166             && minuteSet
167             && secondSet) {
168             return DatatypeConstants.DURATION;
169         }
170
171         // DURATION_DAYTIME
172
if (!yearSet
173             && !monthSet
174             && daySet
175             && hourSet
176             && minuteSet
177             && secondSet) {
178             return DatatypeConstants.DURATION_DAYTIME;
179         }
180
181         // DURATION_YEARMONTH
182
if (yearSet
183             && monthSet
184             && !daySet
185             && !hourSet
186             && !minuteSet
187             && !secondSet) {
188             return DatatypeConstants.DURATION_YEARMONTH;
189         }
190
191         // nothing matches
192
throw new IllegalStateException JavaDoc(
193                 "javax.xml.datatype.Duration#getXMLSchemaType():"
194                 + " this Duration does not match one of the XML Schema date/time datatypes:"
195                 + " year set = " + yearSet
196                 + " month set = " + monthSet
197                 + " day set = " + daySet
198                 + " hour set = " + hourSet
199                 + " minute set = " + minuteSet
200                 + " second set = " + secondSet
201         );
202     }
203
204     /**
205      * Returns the sign of this duration in -1,0, or 1.
206      *
207      * @return
208      * -1 if this duration is negative, 0 if the duration is zero,
209      * and 1 if the duration is positive.
210      */

211     public abstract int getSign();
212
213     /**
214      * <p>Get the years value of this <code>Duration</code> as an <code>int</code> or <code>0</code> if not present.</p>
215      *
216      * <p><code>getYears()</code> is a convenience method for
217      * {@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)}.</p>
218      *
219      * <p>As the return value is an <code>int</code>, an incorrect value will be returned for <code>Duration</code>s
220      * with years that go beyond the range of an <code>int</code>.
221      * Use {@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)} to avoid possible loss of precision.</p>
222      *
223      * @return If the years field is present, return its value as an <code>int</code>, else return <code>0</code>.
224      */

225     public int getYears() {
226         return getField(DatatypeConstants.YEARS).intValue();
227     }
228     
229     /**
230      * Obtains the value of the MONTHS field as an integer value,
231      * or 0 if not present.
232      *
233      * This method works just like {@link #getYears()} except
234      * that this method works on the MONTHS field.
235      *
236      * @return Months of this <code>Duration</code>.
237      */

238     public int getMonths() {
239         return getField(DatatypeConstants.MONTHS).intValue();
240     }
241     
242     /**
243      * Obtains the value of the DAYS field as an integer value,
244      * or 0 if not present.
245      *
246      * This method works just like {@link #getYears()} except
247      * that this method works on the DAYS field.
248      *
249      * @return Days of this <code>Duration</code>.
250      */

251     public int getDays() {
252         return getField(DatatypeConstants.DAYS).intValue();
253     }
254     
255     /**
256      * Obtains the value of the HOURS field as an integer value,
257      * or 0 if not present.
258      *
259      * This method works just like {@link #getYears()} except
260      * that this method works on the HOURS field.
261      *
262      * @return Hours of this <code>Duration</code>.
263      *
264      */

265     public int getHours() {
266         return getField(DatatypeConstants.HOURS).intValue();
267     }
268     
269     /**
270      * Obtains the value of the MINUTES field as an integer value,
271      * or 0 if not present.
272      *
273      * This method works just like {@link #getYears()} except
274      * that this method works on the MINUTES field.
275      *
276      * @return Minutes of this <code>Duration</code>.
277      *
278      */

279     public int getMinutes() {
280         return getField(DatatypeConstants.MINUTES).intValue();
281     }
282     
283     /**
284      * Obtains the value of the SECONDS field as an integer value,
285      * or 0 if not present.
286      *
287      * This method works just like {@link #getYears()} except
288      * that this method works on the SECONDS field.
289      *
290      * @return seconds in the integer value. The fraction of seconds
291      * will be discarded (for example, if the actual value is 2.5,
292      * this method returns 2)
293      */

294     public int getSeconds() {
295         return getField(DatatypeConstants.SECONDS).intValue();
296     }
297     
298     /**
299      * <p>Returns the length of the duration in milli-seconds.</p>
300      *
301      * <p>If the seconds field carries more digits than milli-second order,
302      * those will be simply discarded (or in other words, rounded to zero.)
303      * For example, for any Calendar value <code>x<code>,</p>
304      * <pre>
305      * <code>new Duration("PT10.00099S").getTimeInMills(x) == 10000</code>.
306      * <code>new Duration("-PT10.00099S").getTimeInMills(x) == -10000</code>.
307      * </pre>
308      *
309      * <p>
310      * Note that this method uses the {@link #addTo(Calendar)} method,
311      * which may work incorrectly with <code>Duration</code> objects with
312      * very large values in its fields. See the {@link #addTo(Calendar)}
313      * method for details.
314      *
315      * @param startInstant
316      * The length of a month/year varies. The <code>startInstant</code> is
317      * used to disambiguate this variance. Specifically, this method
318      * returns the difference between <code>startInstant</code> and
319      * <code>startInstant+duration</code>
320      *
321      * @return milliseconds between <code>startInstant</code> and
322      * <code>startInstant</code> plus this <code>Duration</code>
323      *
324      * @throws NullPointerException if <code>startInstant</code> parameter
325      * is null.
326      *
327      */

328     public long getTimeInMillis(final Calendar JavaDoc startInstant) {
329         Calendar JavaDoc cal = (Calendar JavaDoc) startInstant.clone();
330         addTo(cal);
331         return getCalendarTimeInMillis(cal)
332                     - getCalendarTimeInMillis(startInstant);
333     }
334     
335     /**
336      * <p>Returns the length of the duration in milli-seconds.</p>
337      *
338      * <p>If the seconds field carries more digits than milli-second order,
339      * those will be simply discarded (or in other words, rounded to zero.)
340      * For example, for any <code>Date</code> value <code>x<code>,</p>
341      * <pre>
342      * <code>new Duration("PT10.00099S").getTimeInMills(x) == 10000</code>.
343      * <code>new Duration("-PT10.00099S").getTimeInMills(x) == -10000</code>.
344      * </pre>
345      *
346      * <p>
347      * Note that this method uses the {@link #addTo(Date)} method,
348      * which may work incorrectly with <code>Duration</code> objects with
349      * very large values in its fields. See the {@link #addTo(Date)}
350      * method for details.
351      *
352      * @param startInstant
353      * The length of a month/year varies. The <code>startInstant</code> is
354      * used to disambiguate this variance. Specifically, this method
355      * returns the difference between <code>startInstant</code> and
356      * <code>startInstant+duration</code>.
357      *
358      * @throws NullPointerException
359      * If the startInstant parameter is null.
360      *
361      * @return milliseconds between <code>startInstant</code> and
362      * <code>startInstant</code> plus this <code>Duration</code>
363      *
364      * @see #getTimeInMillis(Calendar)
365      */

366     public long getTimeInMillis(final Date JavaDoc startInstant) {
367         Calendar JavaDoc cal = new GregorianCalendar JavaDoc();
368         cal.setTime(startInstant);
369         this.addTo(cal);
370         return getCalendarTimeInMillis(cal) - startInstant.getTime();
371     }
372     
373     /**
374      * Gets the value of a field.
375      *
376      * Fields of a duration object may contain arbitrary large value.
377      * Therefore this method is designed to return a {@link Number} object.
378      *
379      * In case of YEARS, MONTHS, DAYS, HOURS, and MINUTES, the returned
380      * number will be a non-negative integer. In case of seconds,
381      * the returned number may be a non-negative decimal value.
382      *
383      * @param field
384      * one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
385      * MINUTES, or SECONDS.)
386      * @return
387      * If the specified field is present, this method returns
388      * a non-null non-negative {@link Number} object that
389      * represents its value. If it is not present, return null.
390      * For YEARS, MONTHS, DAYS, HOURS, and MINUTES, this method
391      * returns a {@link java.math.BigInteger} object. For SECONDS, this
392      * method returns a {@link java.math.BigDecimal}.
393      *
394      * @throws NullPointerException If the <code>field</code> is <code>null</code>.
395      */

396     public abstract Number JavaDoc getField(final DatatypeConstants.Field JavaDoc field);
397     
398     /**
399      * Checks if a field is set.
400      *
401      * A field of a duration object may or may not be present.
402      * This method can be used to test if a field is present.
403      *
404      * @param field
405      * one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
406      * MINUTES, or SECONDS.)
407      * @return
408      * true if the field is present. false if not.
409      *
410      * @throws NullPointerException
411      * If the field parameter is null.
412      */

413     public abstract boolean isSet(final DatatypeConstants.Field JavaDoc field);
414     
415     /**
416      * <p>Computes a new duration whose value is <code>this+rhs</code>.</p>
417      *
418      * <p>For example,</p>
419      * <pre>
420      * "1 day" + "-3 days" = "-2 days"
421      * "1 year" + "1 day" = "1 year and 1 day"
422      * "-(1 hour,50 minutes)" + "-20 minutes" = "-(1 hours,70 minutes)"
423      * "15 hours" + "-3 days" = "-(2 days,9 hours)"
424      * "1 year" + "-1 day" = IllegalStateException
425      * </pre>
426      *
427      * <p>Since there's no way to meaningfully subtract 1 day from 1 month,
428      * there are cases where the operation fails in
429      * {@link IllegalStateException}.</p>
430      *
431      * <p>
432      * Formally, the computation is defined as follows.</p>
433      * <p>
434      * Firstly, we can assume that two <code>Duration</code>s to be added
435      * are both positive without losing generality (i.e.,
436      * <code>(-X)+Y=Y-X</code>, <code>X+(-Y)=X-Y</code>,
437      * <code>(-X)+(-Y)=-(X+Y)</code>)
438      *
439      * <p>
440      * Addition of two positive <code>Duration</code>s are simply defined as
441      * field by field addition where missing fields are treated as 0.
442      * <p>
443      * A field of the resulting <code>Duration</code> will be unset if and
444      * only if respective fields of two input <code>Duration</code>s are unset.
445      * <p>
446      * Note that <code>lhs.add(rhs)</code> will be always successful if
447      * <code>lhs.signum()*rhs.signum()!=-1</code> or both of them are
448      * normalized.</p>
449      *
450      * @param rhs <code>Duration</code> to add to this <code>Duration</code>
451      *
452      * @return
453      * non-null valid Duration object.
454      *
455      * @throws NullPointerException
456      * If the rhs parameter is null.
457      * @throws IllegalStateException
458      * If two durations cannot be meaningfully added. For
459      * example, adding negative one day to one month causes
460      * this exception.
461      *
462      *
463      * @see #subtract(Duration)
464      */

465     public abstract Duration JavaDoc add(final Duration JavaDoc rhs);
466     
467     /**
468      * Adds this duration to a {@link Calendar} object.
469      *
470      * <p>
471      * Calls {@link java.util.Calendar#add(int,int)} in the
472      * order of YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, and MILLISECONDS
473      * if those fields are present. Because the {@link Calendar} class
474      * uses int to hold values, there are cases where this method
475      * won't work correctly (for example if values of fields
476      * exceed the range of int.)
477      * </p>
478      *
479      * <p>
480      * Also, since this duration class is a Gregorian duration, this
481      * method will not work correctly if the given {@link Calendar}
482      * object is based on some other calendar systems.
483      * </p>
484      *
485      * <p>
486      * Any fractional parts of this <code>Duration</code> object
487      * beyond milliseconds will be simply ignored. For example, if
488      * this duration is "P1.23456S", then 1 is added to SECONDS,
489      * 234 is added to MILLISECONDS, and the rest will be unused.
490      * </p>
491      *
492      * <p>
493      * Note that because {@link Calendar#add(int, int)} is using
494      * <tt>int</tt>, <code>Duration</code> with values beyond the
495      * range of <tt>int</tt> in its fields
496      * will cause overflow/underflow to the given {@link Calendar}.
497      * {@link XMLGregorianCalendar#add(Duration)} provides the same
498      * basic operation as this method while avoiding
499      * the overflow/underflow issues.
500      *
501      * @param calendar
502      * A calendar object whose value will be modified.
503      * @throws NullPointerException
504      * if the calendar parameter is null.
505      */

506     public abstract void addTo(Calendar JavaDoc calendar);
507     
508     /**
509      * Adds this duration to a {@link Date} object.
510      *
511      * <p>
512      * The given date is first converted into
513      * a {@link java.util.GregorianCalendar}, then the duration
514      * is added exactly like the {@link #addTo(Calendar)} method.
515      *
516      * <p>
517      * The updated time instant is then converted back into a
518      * {@link Date} object and used to update the given {@link Date} object.
519      *
520      * <p>
521      * This somewhat redundant computation is necessary to unambiguously
522      * determine the duration of months and years.
523      *
524      * @param date
525      * A date object whose value will be modified.
526      * @throws NullPointerException
527      * if the date parameter is null.
528      */

529     public void addTo(Date JavaDoc date) {
530         
531         // check data parameter
532
if (date == null) {
533             throw new NullPointerException JavaDoc(
534                 "Cannot call "
535                 + this.getClass().getName()
536                 + "#addTo(Date date) with date == null."
537             );
538         }
539         
540         Calendar JavaDoc cal = new GregorianCalendar JavaDoc();
541         cal.setTime(date);
542         this.addTo(cal);
543         date.setTime(getCalendarTimeInMillis(cal));
544     }
545     
546     /**
547      * <p>Computes a new duration whose value is <code>this-rhs</code>.</p>
548      *
549      * <p>For example:</p>
550      * <pre>
551      * "1 day" - "-3 days" = "4 days"
552      * "1 year" - "1 day" = IllegalStateException
553      * "-(1 hour,50 minutes)" - "-20 minutes" = "-(1hours,30 minutes)"
554      * "15 hours" - "-3 days" = "3 days and 15 hours"
555      * "1 year" - "-1 day" = "1 year and 1 day"
556      * </pre>
557      *
558      * <p>Since there's no way to meaningfully subtract 1 day from 1 month,
559      * there are cases where the operation fails in {@link IllegalStateException}.</p>
560      *
561      * <p>Formally the computation is defined as follows.
562      * First, we can assume that two <code>Duration</code>s are both positive
563      * without losing generality. (i.e.,
564      * <code>(-X)-Y=-(X+Y)</code>, <code>X-(-Y)=X+Y</code>,
565      * <code>(-X)-(-Y)=-(X-Y)</code>)</p>
566      *
567      * <p>Then two durations are subtracted field by field.
568      * If the sign of any non-zero field <tt>F</tt> is different from
569      * the sign of the most significant field,
570      * 1 (if <tt>F</tt> is negative) or -1 (otherwise)
571      * will be borrowed from the next bigger unit of <tt>F</tt>.</p>
572      *
573      * <p>This process is repeated until all the non-zero fields have
574      * the same sign.</p>
575      *
576      * <p>If a borrow occurs in the days field (in other words, if
577      * the computation needs to borrow 1 or -1 month to compensate
578      * days), then the computation fails by throwing an
579      * {@link IllegalStateException}.</p>
580      *
581      * @param rhs <code>Duration</code> to subtract from this <code>Duration</code>.
582      *
583      * @return New <code>Duration</code> created from subtracting <code>rhs</code> from this <code>Duration</code>.
584      *
585      * @throws IllegalStateException
586      * If two durations cannot be meaningfully subtracted. For
587      * example, subtracting one day from one month causes
588      * this exception.
589      *
590      * @throws NullPointerException
591      * If the rhs parameter is null.
592      *
593      * @see #add(Duration)
594      */

595     public Duration JavaDoc subtract(final Duration JavaDoc rhs) {
596         return add(rhs.negate());
597     }
598     
599     /**
600      * <p>Computes a new duration whose value is <code>factor</code> times
601      * longer than the value of this duration.</p>
602      *
603      * <p>This method is provided for the convenience.
604      * It is functionally equivalent to the following code:</p>
605      * <pre>
606      * multiply(new BigDecimal(String.valueOf(factor)))
607      * </pre>
608      *
609      * @param factor Factor times longer of new <code>Duration</code> to create.
610      *
611      * @return New <code>Duration</code> that is <code>factor</code>times longer than this <code>Duration</code>.
612      *
613      * @see #multiply(BigDecimal)
614      */

615     public Duration JavaDoc multiply(int factor) {
616         return multiply(new BigDecimal JavaDoc(String.valueOf(factor)));
617     }
618     
619     /**
620      * Computes a new duration whose value is <code>factor</code> times
621      * longer than the value of this duration.
622      *
623      * <p>
624      * For example,
625      * <pre>
626      * "P1M" (1 month) * "12" = "P12M" (12 months)
627      * "PT1M" (1 min) * "0.3" = "PT18S" (18 seconds)
628      * "P1M" (1 month) * "1.5" = IllegalStateException
629      * </pre>
630      *
631      * <p>
632      * Since the <code>Duration</code> class is immutable, this method
633      * doesn't change the value of this object. It simply computes
634      * a new Duration object and returns it.
635      *
636      * <p>
637      * The operation will be performed field by field with the precision
638      * of {@link BigDecimal}. Since all the fields except seconds are
639      * restricted to hold integers,
640      * any fraction produced by the computation will be
641      * carried down toward the next lower unit. For example,
642      * if you multiply "P1D" (1 day) with "0.5", then it will be 0.5 day,
643      * which will be carried down to "PT12H" (12 hours).
644      * When fractions of month cannot be meaningfully carried down
645      * to days, or year to months, this will cause an
646      * {@link IllegalStateException} to be thrown.
647      * For example if you multiple one month by 0.5.</p>
648      *
649      * <p>
650      * To avoid {@link IllegalStateException}, use
651      * the {@link #normalizeWith(Calendar)} method to remove the years
652      * and months fields.
653      *
654      * @param factor to multiply by
655      *
656      * @return
657      * returns a non-null valid <code>Duration</code> object
658      *
659      * @throws IllegalStateException if operation produces fraction in
660      * the months field.
661      *
662      * @throws NullPointerException if the <code>factor</code> parameter is
663      * <code>null</code>.
664      *
665      */

666     public abstract Duration JavaDoc multiply(final BigDecimal JavaDoc factor);
667     
668     /**
669      * Returns a new <code>Duration</code> object whose
670      * value is <code>-this</code>.
671      *
672      * <p>
673      * Since the <code>Duration</code> class is immutable, this method
674      * doesn't change the value of this object. It simply computes
675      * a new Duration object and returns it.
676      *
677      * @return
678      * always return a non-null valid <code>Duration</code> object.
679      */

680     public abstract Duration JavaDoc negate();
681     
682     /**
683      * <p>Converts the years and months fields into the days field
684      * by using a specific time instant as the reference point.</p>
685      *
686      * <p>For example, duration of one month normalizes to 31 days
687      * given the start time instance "July 8th 2003, 17:40:32".</p>
688      *
689      * <p>Formally, the computation is done as follows:</p>
690      * <ol>
691      * <li>the given Calendar object is cloned</li>
692      * <li>the years, months and days fields will be added to the {@link Calendar} object
693      * by using the {@link Calendar#add(int,int)} method</li>
694      * <li>the difference between the two Calendars in computed in milliseconds and converted to days,
695      * if a remainder occurs due to Daylight Savings Time, it is discarded</li>
696      * <li>the computed days, along with the hours, minutes and seconds
697      * fields of this duration object is used to construct a new
698      * Duration object.</li>
699      * </ol>
700      *
701      * <p>Note that since the Calendar class uses <code>int</code> to
702      * hold the value of year and month, this method may produce
703      * an unexpected result if this duration object holds
704      * a very large value in the years or months fields.</p>
705      *
706      * @param startTimeInstant <code>Calendar</code> reference point.
707      *
708      * @return <code>Duration</code> of years and months of this <code>Duration</code> as days.
709      *
710      * @throws NullPointerException If the startTimeInstant parameter is null.
711      */

712     public abstract Duration JavaDoc normalizeWith(final Calendar JavaDoc startTimeInstant);
713     
714     /**
715      * <p>Partial order relation comparison with this <code>Duration</code> instance.</p>
716      *
717      * <p>Comparison result must be in accordance with
718      * <a HREF="http://www.w3.org/TR/xmlschema-2/#duration-order">W3C XML Schema 1.0 Part 2, Section 3.2.7.6.2,
719      * <i>Order relation on duration</i></a>.</p>
720      *
721      * <p>Return:</p>
722      * <ul>
723      * <li>{@link DatatypeConstants#LESSER} if this <code>Duration</code> is shorter than <code>duration</code> parameter</li>
724      * <li>{@link DatatypeConstants#EQUAL} if this <code>Duration</code> is equal to <code>duration</code> parameter</li>
725      * <li>{@link DatatypeConstants#GREATER} if this <code>Duration</code> is longer than <code>duration</code> parameter</li>
726      * <li>{@link DatatypeConstants#INDETERMINATE} if a conclusive partial order relation cannot be determined</li>
727      * </ul>
728      *
729      * @param duration to compare
730      *
731      * @return the relationship between <code>this</code> <code>Duration</code>and <code>duration</code> parameter as
732      * {@link DatatypeConstants#LESSER}, {@link DatatypeConstants#EQUAL}, {@link DatatypeConstants#GREATER}
733      * or {@link DatatypeConstants#INDETERMINATE}.
734      *
735      * @throws UnsupportedOperationException If the underlying implementation
736      * cannot reasonably process the request, e.g. W3C XML Schema allows for
737      * arbitrarily large/small/precise values, the request may be beyond the
738      * implementations capability.
739      * @throws NullPointerException if <code>duration</code> is <code>null</code>.
740      *
741      * @see #isShorterThan(Duration)
742      * @see #isLongerThan(Duration)
743      */

744     public abstract int compare(final Duration JavaDoc duration);
745     
746     /**
747      * <p>Checks if this duration object is strictly longer than
748      * another <code>Duration</code> object.</p>
749      *
750      * <p>Duration X is "longer" than Y if and only if X>Y
751      * as defined in the section 3.2.6.2 of the XML Schema 1.0
752      * specification.</p>
753      *
754      * <p>For example, "P1D" (one day) > "PT12H" (12 hours) and
755      * "P2Y" (two years) > "P23M" (23 months).</p>
756      *
757      * @param duration <code>Duration</code> to test this <code>Duration</code> against.
758      *
759      * @throws UnsupportedOperationException If the underlying implementation
760      * cannot reasonably process the request, e.g. W3C XML Schema allows for
761      * arbitrarily large/small/precise values, the request may be beyond the
762      * implementations capability.
763      * @throws NullPointerException If <code>duration</code> is null.
764      *
765      * @return
766      * true if the duration represented by this object
767      * is longer than the given duration. false otherwise.
768      *
769      * @see #isShorterThan(Duration)
770      * @see #compare(Duration duration)
771      */

772     public boolean isLongerThan(final Duration JavaDoc duration) {
773         return compare(duration) == DatatypeConstants.GREATER;
774     }
775     
776     /**
777      * <p>Checks if this duration object is strictly shorter than
778      * another <code>Duration</code> object.</p>
779      *
780      * @param duration <code>Duration</code> to test this <code>Duration</code> against.
781      *
782      * @return <code>true</code> if <code>duration</code> parameter is shorter than this <code>Duration</code>,
783      * else <code>false</code>.
784      *
785      * @throws UnsupportedOperationException If the underlying implementation
786      * cannot reasonably process the request, e.g. W3C XML Schema allows for
787      * arbitrarily large/small/precise values, the request may be beyond the
788      * implementations capability.
789      * @throws NullPointerException if <code>duration</code> is null.
790      *
791      * @see #isLongerThan(Duration duration)
792      * @see #compare(Duration duration)
793      */

794     public boolean isShorterThan(final Duration JavaDoc duration) {
795         return compare(duration) == DatatypeConstants.LESSER;
796     }
797     
798     /**
799      * <p>Checks if this duration object has the same duration
800      * as another <code>Duration</code> object.</p>
801      *
802      * <p>For example, "P1D" (1 day) is equal to "PT24H" (24 hours).</p>
803      *
804      * <p>Duration X is equal to Y if and only if time instant
805      * t+X and t+Y are the same for all the test time instants
806      * specified in the section 3.2.6.2 of the XML Schema 1.0
807      * specification.</p>
808      *
809      * <p>Note that there are cases where two <code>Duration</code>s are
810      * "incomparable" to each other, like one month and 30 days.
811      * For example,</p>
812      * <pre>
813      * !new Duration("P1M").isShorterThan(new Duration("P30D"))
814      * !new Duration("P1M").isLongerThan(new Duration("P30D"))
815      * !new Duration("P1M").equals(new Duration("P30D"))
816      * </pre>
817      *
818      * @param duration
819      * A non-null valid <code>Duration</code> object.
820      *
821      * @return
822      * <code>true</code> if this duration is the same length as
823      * <code>duration</code>.
824      * <code>false</code> if <code>duration</code> is not a
825      * <code>Duration</code> object
826      * or its length is different from this duration.
827      *
828      * @throws UnsupportedOperationException If the underlying implementation
829      * cannot reasonably process the request, e.g. W3C XML Schema allows for
830      * arbitrarily large/small/precise values, the request may be beyond the
831      * implementations capability.
832      * @throws NullPointerException if parameter is null.
833      *
834      * @see #compare(Duration duration)
835      */

836     public boolean equals(final Object JavaDoc duration) {
837         if (duration == null) {
838             throw new NullPointerException JavaDoc();
839         }
840
841         if (!(duration instanceof Duration JavaDoc)) {
842             return false;
843         }
844
845         return compare((Duration JavaDoc) duration) == DatatypeConstants.EQUAL;
846     }
847     
848     /**
849      * Returns a hash code consistent with the definition of the equals method.
850      *
851      * @see Object#hashCode()
852      */

853     public abstract int hashCode();
854     
855     /**
856      * <p>Returns a <code>String</code> representation of this <code>Duration</code> <code>Object</code>.</p>
857      *
858      * <p>The result is formatted according to the XML Schema 1.0 spec and can be always parsed back later into the
859      * equivalent <code>Duration</code> <code>Object</code> by {@link DatatypeFactory#newDuration(String lexicalRepresentation)}.</p>
860      *
861      * <p>Formally, the following holds for any <code>Duration</code>
862      * <code>Object</code> x:</p>
863      * <pre>
864      * new Duration(x.toString()).equals(x)
865      * </pre>
866      *
867      * @return A non-<code>null</code> valid <code>String</code> representation of this <code>Duration</code>.
868      */

869     public String JavaDoc toString() {
870         
871         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
872         
873         if (getSign() < 0) {
874             buf.append('-');
875         }
876         buf.append('P');
877         
878         BigInteger JavaDoc years = (BigInteger JavaDoc) getField(DatatypeConstants.YEARS);
879         if (years != null) {
880             buf.append(years + "Y");
881         }
882         
883         BigInteger JavaDoc months = (BigInteger JavaDoc) getField(DatatypeConstants.MONTHS);
884         if (months != null) {
885             buf.append(months + "M");
886         }
887         
888         BigInteger JavaDoc days = (BigInteger JavaDoc) getField(DatatypeConstants.DAYS);
889         if (days != null) {
890             buf.append(days + "D");
891         }
892
893         BigInteger JavaDoc hours = (BigInteger JavaDoc) getField(DatatypeConstants.HOURS);
894         BigInteger JavaDoc minutes = (BigInteger JavaDoc) getField(DatatypeConstants.MINUTES);
895         BigDecimal JavaDoc seconds = (BigDecimal JavaDoc) getField(DatatypeConstants.SECONDS);
896         if (hours != null || minutes != null || seconds != null) {
897             buf.append('T');
898             if (hours != null) {
899                 buf.append(hours + "H");
900             }
901             if (minutes != null) {
902                 buf.append(minutes + "M");
903             }
904             if (seconds != null) {
905                 buf.append(toString(seconds) + "S");
906             }
907         }
908         
909         return buf.toString();
910     }
911     
912     /**
913      * <p>Turns {@link BigDecimal} to a string representation.</p>
914      *
915      * <p>Due to a behavior change in the {@link BigDecimal#toString()}
916      * method in JDK 5, this had to be implemented here.</p>
917      *
918      * @param bd <code>BigDecimal</code> to format as a <code>String</code>
919      *
920      * @return <code>String</code> representation of <code>BigDecimal</code>
921      */

922     private String JavaDoc toString(BigDecimal JavaDoc bd) {
923         String JavaDoc intString = bd.unscaledValue().toString();
924         int scale = bd.scale();
925
926         if (scale == 0) {
927             return intString;
928         }
929
930         /* Insert decimal point */
931         StringBuffer JavaDoc buf;
932         int insertionPoint = intString.length() - scale;
933         if (insertionPoint == 0) { /* Point goes right before intVal */
934             return "0." + intString;
935         } else if (insertionPoint > 0) { /* Point goes inside intVal */
936             buf = new StringBuffer JavaDoc(intString);
937             buf.insert(insertionPoint, '.');
938         } else { /* We must insert zeros between point and intVal */
939             buf = new StringBuffer JavaDoc(3 - insertionPoint + intString.length());
940             buf.append("0.");
941             for (int i = 0; i < -insertionPoint; i++) {
942                 buf.append('0');
943             }
944             buf.append(intString);
945         }
946         return buf.toString();
947     }
948     
949         
950     /**
951      * <p>Calls the {@link Calendar#getTimeInMillis} method.
952      * Prior to JDK1.4, this method was protected and therefore
953      * cannot be invoked directly.</p>
954      *
955      * <p>TODO: In future, this should be replaced by <code>cal.getTimeInMillis()</code>.</p>
956      *
957      * @param cal <code>Calendar</code> to get time in milliseconds.
958      *
959      * @return Milliseconds of <code>cal</code>.
960      */

961     private static long getCalendarTimeInMillis(final Calendar JavaDoc cal) {
962         return cal.getTime().getTime();
963     }
964 }
965
966
Popular Tags