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