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