Class DurationImpl

java.lang.Object
com.stimulsoft.lib.utils.DurationImpl

public class DurationImpl extends Object
Copyright Stimulsoft
  • Field Details

    • signum

      protected int signum

      Indicates the sign. -1, 0 or 1 if the duration is negative, zero, or positive.

    • years

      protected BigInteger years
      These were final since DurationImpl is immutable. But new subclasses need to be able to set after conversion. It won't break the immutable nature of them since there's no other way to set new values to them
    • months

      protected BigInteger months

      Months of this DurationImpl.

    • days

      protected BigInteger days

      Days of this DurationImpl.

    • hours

      protected BigInteger hours

      Hours of this DurationImpl.

    • minutes

      protected BigInteger minutes

      Minutes of this DurationImpl.

    • seconds

      protected BigDecimal seconds

      Seconds of this DurationImpl.

  • Constructor Details

    • DurationImpl

      protected DurationImpl(boolean isPositive, BigInteger years, BigInteger months, BigInteger days, BigInteger hours, BigInteger minutes, BigDecimal seconds)

      Constructs a new DurationImpl object by specifying each field individually.

      All the parameters are optional as long as at least one field is present. If specified, parameters have to be zero or positive.

      Parameters:
      isPositive - Set to false to create a negative duration. When the length of the duration is zero, this parameter will be ignored.
      years - of this DurationImpl
      months - of this DurationImpl
      days - of this DurationImpl
      hours - of this DurationImpl
      minutes - of this DurationImpl
      seconds - of this DurationImpl
      Throws:
      IllegalArgumentException - If years, months, days, hours, minutes and seconds parameters are all null. Or if any of those parameters are negative.
    • DurationImpl

      protected DurationImpl(boolean isPositive, int years, int months, int days, int hours, int minutes, int seconds)

      Constructs a new DurationImpl object by specifying each field individually.

      This method is functionally equivalent to invoking another constructor by wrapping all non-zero parameters into BigInteger and BigDecimal. Zero value of int parameter is equivalent of null value of the corresponding field.

      See Also:
    • DurationImpl

      protected DurationImpl(long durationInMilliSeconds)

      Constructs a new DurationImpl object by specifying the duration in milliseconds.

      Parameters:
      durationInMilliSeconds - The length of the duration in milliseconds.
    • DurationImpl

      protected DurationImpl(String lexicalRepresentation) throws IllegalArgumentException
      Constructs a new DurationImpl object by parsing its string representation "PnYnMnDTnHnMnS" as defined in XML Schema 1.0 section 3.2.6.1.

      The string representation may not have any leading and trailing whitespaces.

      For example, this method parses strings like "P1D" (1 day), "-PT100S" (-100 sec.), "P1DT12H" (1 days and 12 hours).

      The parsing is done field by field so that the following holds for any lexically correct string x:

       new DurationImpl(x).toString().equals(x)
       
      Returns a non-null valid duration object that holds the value indicated by the lexicalRepresentation parameter.
      Parameters:
      lexicalRepresentation - Lexical representation of a duration.
      Throws:
      IllegalArgumentException - If the given string does not conform to the aforementioned specification.
      NullPointerException - If the given string is null.
  • Method Details

    • getSign

      public int getSign()
      Returns the sign of this duration in -1,0, or 1.
      Returns:
      -1 if this duration is negative, 0 if the duration is zero, and 1 if the duration is postive.
    • calcSignum

      protected int calcSignum(boolean isPositive)
      TODO: Javadoc
      Parameters:
      isPositive - Sign.
      Returns:
      1 if positive, else -1.
    • testNonNegative

      protected static void testNonNegative(BigInteger n, DatatypeConstants.Field f)

      Makes sure that the given number is non-negative. If it is not, throw IllegalArgumentException.

      Parameters:
      n - Number to test.
      f - Field to test.
    • testNonNegative

      protected static void testNonNegative(BigDecimal n, DatatypeConstants.Field f)

      Makes sure that the given number is non-negative. If it is not, throw IllegalArgumentException.

      Parameters:
      n - Number to test.
      f - Field to test.
    • wrap

      protected static BigInteger wrap(int i)
      TODO: Javadoc
      Parameters:
      i - int to convert to BigInteger.
      Returns:
      BigInteger representation of int.
    • compare

      public int compare(DurationImpl rhs)

      Partial order relation comparison with this DurationImpl instance.

      Comparison result must be in accordance with W3C XML Schema 1.0 Part 2, Section 3.2.7.6.2, Order relation on duration.

      Return:

      Parameters:
      duration - to compare
      Returns:
      the relationship between this DurationImpland duration parameter as DatatypeConstants.LESSER, DatatypeConstants.EQUAL, DatatypeConstants.GREATER or 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.
      NullPointerException - if duration is null.
      See Also:
      • invalid reference
        #isShorterThan(DurationImpl)
      • invalid reference
        #isLongerThan(DurationImpl)
    • hashCode

      public int hashCode()
      Returns a hash code consistent with the definition of the equals method.
      Overrides:
      hashCode in class Object
      See Also:
    • toString

      public String toString()
      Returns a string representation of this duration object.

      The result is formatter according to the XML Schema 1.0 spec and can be always parsed back later into the equivalent duration object by the DurationImpl(String) constructor.

      Formally, the following holds for any DurationImpl object x.

       new DurationImpl(x.toString()).equals(x)
       
      Overrides:
      toString in class Object
      Returns:
      Always return a non-null valid String object.
    • isSet

      public boolean isSet(DatatypeConstants.Field field)
      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.
      Parameters:
      field - one of the six Field constants (YEARS,MONTHS,DAYS,HOURS, MINUTES, or SECONDS.)
      Returns:
      true if the field is present. false if not.
      Throws:
      NullPointerException - If the field parameter is null.
    • getField

      public Number getField(DatatypeConstants.Field field)
      Gets the value of a field. Fields of a duration object may contain arbitrary large value. Therefore this method is designed to return a 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.
      Parameters:
      field - one of the six Field constants (YEARS,MONTHS,DAYS,HOURS, MINUTES, or SECONDS.)
      Returns:
      If the specified field is present, this method returns a non-null non-negative Number object that represents its value. If it is not present, return null. For YEARS, MONTHS, DAYS, HOURS, and MINUTES, this method returns a BigInteger object. For SECONDS, this method returns a BigDecimal.
      Throws:
      NullPointerException - If the field parameter is null.
    • getYears

      public int getYears()
      Obtains the value of the YEARS field as an integer value, or 0 if not present.

      This method is a convenience method around the getField(DatatypeConstants.Field) method.

      Note that since this method returns int, this method will return an incorrect value for DurationImpls with the year field that goes beyond the range of int. Use getField(YEARS) to avoid possible loss of precision.

      Returns:
      If the YEARS field is present, return its value as an integer by using the Number.intValue() method. If the YEARS field is not present, return 0.
    • getMonths

      public int getMonths()
      Obtains the value of the MONTHS field as an integer value, or 0 if not present. This method works just like getYears() except that this method works on the MONTHS field.
      Returns:
      Months of this DurationImpl.
    • getDays

      public int getDays()
      Obtains the value of the DAYS field as an integer value, or 0 if not present. This method works just like getYears() except that this method works on the DAYS field.
      Returns:
      Days of this DurationImpl.
    • getHours

      public int getHours()
      Obtains the value of the HOURS field as an integer value, or 0 if not present. This method works just like getYears() except that this method works on the HOURS field.
      Returns:
      Hours of this DurationImpl.
    • getMinutes

      public int getMinutes()
      Obtains the value of the MINUTES field as an integer value, or 0 if not present. This method works just like getYears() except that this method works on the MINUTES field.
      Returns:
      Minutes of this DurationImpl.
    • getSeconds

      public int getSeconds()
      Obtains the value of the SECONDS field as an integer value, or 0 if not present. This method works just like getYears() except that this method works on the SECONDS field.
      Returns:
      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)
    • getTimeInMillis

      public long getTimeInMillis(Calendar startInstant)

      Returns the length of the duration in milli-seconds.

      If the seconds field carries more digits than milli-second order, those will be simply discarded (or in other words, rounded to zero.) For example, for any Calendar value x,

       new DurationImpl("PT10.00099S").getTimeInMills(x) == 10000.
       new DurationImpl("-PT10.00099S").getTimeInMills(x) == -10000.
       

      Note that this method uses the addTo(Calendar) method, which may work incorectly with DurationImpl objects with very large values in its fields. See the addTo(Calendar) method for details.

      Parameters:
      startInstant - The length of a month/year varies. The startInstant is used to disambiguate this variance. Specifically, this method returns the difference between startInstant and startInstant+duration
      Returns:
      milliseconds between startInstant and startInstant plus this DurationImpl
      Throws:
      NullPointerException - if startInstant parameter is null.
    • getTimeInMillis

      public long getTimeInMillis(Date startInstant)

      Returns the length of the duration in milli-seconds.

      If the seconds field carries more digits than milli-second order, those will be simply discarded (or in other words, rounded to zero.) For example, for any Date value x,

       new DurationImpl("PT10.00099S").getTimeInMills(x) == 10000.
       new DurationImpl("-PT10.00099S").getTimeInMills(x) == -10000.
       

      Note that this method uses the addTo(Date) method, which may work incorectly with DurationImpl objects with very large values in its fields. See the addTo(Date) method for details.

      Parameters:
      startInstant - The length of a month/year varies. The startInstant is used to disambiguate this variance. Specifically, this method returns the difference between startInstant and startInstant+duration.
      Returns:
      milliseconds between startInstant and startInstant plus this DurationImpl
      Throws:
      NullPointerException - If the startInstant parameter is null.
      See Also:
    • normalizeWith

      public DurationImpl normalizeWith(Calendar startTimeInstant)

      Converts the years and months fields into the days field by using a specific time instant as the reference point.

      For example, duration of one month normalizes to 31 days given the start time instance "July 8th 2003, 17:40:32".

      Formally, the computation is done as follows:

      1. The given Calendar object is cloned.
      2. The years, months and days fields will be added to the Calendar object by using the Calendar.add(int,int) method.
      3. The difference between two Calendars are computed in terms of days.
      4. The computed days, along with the hours, minutes and seconds fields of this duration object is used to construct a new DurationImpl object.

      Note that since the Calendar class uses int 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.

      Parameters:
      startTimeInstant - Calendar reference point.
      Returns:
      DurationImpl of years and months of this DurationImpl as days.
      Throws:
      NullPointerException - If the startTimeInstant parameter is null.
    • multiply

      public DurationImpl multiply(int factor)

      Computes a new duration whose value is factor times longer than the value of this duration.

      This method is provided for the convenience. It is functionally equivalent to the following code:

       multiply(new BigDecimal(String.valueOf(factor)))
       
      Parameters:
      factor - Factor times longer of new DurationImpl to create.
      Returns:
      New DurationImpl that is factortimes longer than this DurationImpl.
      See Also:
    • multiply

      public DurationImpl multiply(BigDecimal factor)
      Computes a new duration whose value is factor times longer than the value of this duration.

      For example,

       "P1M" (1 month) * "12" = "P12M" (12 months)
       "PT1M" (1 min) * "0.3" = "PT18S" (18 seconds)
       "P1M" (1 month) * "1.5" = IllegalStateException
       

      Since the DurationImpl class is immutable, this method doesn't change the value of this object. It simply computes a new DurationImpl object and returns it.

      The operation will be performed field by field with the precision of 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 IllegalStateException to be thrown. For example if you multiple one month by 0.5.

      To avoid IllegalStateException, use the normalizeWith(Calendar) method to remove the years and months fields.

      Parameters:
      factor - to multiply by
      Returns:
      returns a non-null valid DurationImpl object
      Throws:
      IllegalStateException - if operation produces fraction in the months field.
      NullPointerException - if the factor parameter is null.
    • add

      public DurationImpl add(DurationImpl rhs)

      Computes a new duration whose value is this+rhs.

      For example,

       "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
       

      Since there's no way to meaningfully subtract 1 day from 1 month, there are cases where the operation fails in IllegalStateException.

      Formally, the computation is defined as follows.

      Firstly, we can assume that two DurationImpls to be added are both positive without losing generality (i.e., (-X)+Y=Y-X, X+(-Y)=X-Y, (-X)+(-Y)=-(X+Y))

      Addition of two positive DurationImpls are simply defined as field by field addition where missing fields are treated as 0.

      A field of the resulting DurationImpl will be unset if and only if respective fields of two input DurationImpls are unset.

      Note that lhs.add(rhs) will be always successful if lhs.signum()*rhs.signum()!=-1 or both of them are normalized.

      Parameters:
      rhs - DurationImpl to add to this DurationImpl
      Returns:
      non-null valid DurationImpl object.
      Throws:
      NullPointerException - If the rhs parameter is null.
      IllegalStateException - If two durations cannot be meaningfully added. For example, adding negative one day to one month causes this exception.
      See Also:
    • subtract

      public DurationImpl subtract(DurationImpl rhs)

      Computes a new duration whose value is this-rhs.

      For example:

       "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"
       

      Since there's no way to meaningfully subtract 1 day from 1 month, there are cases where the operation fails in IllegalStateException.

      Formally the computation is defined as follows. First, we can assume that two DurationImpls are both positive without losing generality. (i.e., (-X)-Y=-(X+Y), X-(-Y)=X+Y, (-X)-(-Y)=-(X-Y))

      Then two durations are subtracted field by field. If the sign of any non-zero field F is different from the sign of the most significant field, 1 (if F is negative) or -1 (otherwise) will be borrowed from the next bigger unit of F.

      This process is repeated until all the non-zero fields have the same sign.

      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 IllegalStateException.

      Parameters:
      rhs - DurationImpl to substract from this DurationImpl.
      Returns:
      New DurationImpl created from subtracting rhs from this DurationImpl.
      Throws:
      IllegalStateException - If two durations cannot be meaningfully subtracted. For example, subtracting one day from one month causes this exception.
      NullPointerException - If the rhs parameter is null.
      See Also:
    • negate

      public DurationImpl negate()
      Returns a new DurationImpl object whose value is -this.

      Since the DurationImpl class is immutable, this method doesn't change the value of this object. It simply computes a new DurationImpl object and returns it.

      Returns:
      always return a non-null valid DurationImpl object.
    • signum

      public int signum()
      Returns the sign of this duration in -1,0, or 1.
      Returns:
      -1 if this duration is negative, 0 if the duration is zero, and 1 if the duration is postive.
    • addTo

      public void addTo(Calendar calendar)
      Adds this duration to a Calendar object.

      Calls Calendar.add(int,int) in the order of YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, and MILLISECONDS if those fields are present. Because the 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.)

      Also, since this duration class is a Gregorian duration, this method will not work correctly if the given Calendar object is based on some other calendar systems.

      Any fractional parts of this DurationImpl 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.

      Note that because Calendar.add(int, int) is using int, DurationImpl with values beyond the range of int in its fields will cause overflow/underflow to the given Calendar. XMLGregorianCalendarImpl.add(DurationImpl) provides the same basic operation as this method while avoiding the overflow/underflow issues.

      Parameters:
      calendar - A calendar object whose value will be modified.
      Throws:
      NullPointerException - if the calendar parameter is null.
    • addTo

      public void addTo(Date date)
      Adds this duration to a Date object.

      The given date is first converted into a GregorianCalendar, then the duration is added exactly like the addTo(Calendar) method.

      The updated time instant is then converted back into a Date object and used to update the given Date object.

      This somewhat redundant computation is necessary to unambiguously determine the duration of months and years.

      Parameters:
      date - A date object whose value will be modified.
      Throws:
      NullPointerException - if the date parameter is null.