Debian Codegraph @

net/sf/saxon/value/SaxonDuration.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.value;
9
10 import net.sf.saxon.functions.AccessorFn;
11 import net.sf.saxon.lib.NamespaceConstant;
12 import net.sf.saxon.trans.XPathException;
13
14 import javax.xml.datatype.DatatypeConstants;
15 import javax.xml.datatype.Duration;
16 import javax.xml.namespace.QName;
17 import java.math.BigDecimal;
18 import java.math.BigInteger;
19 import java.util.Calendar;
20
21 /**
22 * Saxon implementation of the JAXP class javax.xml.datatype.Duration. This is currently used only by the XQJ
23 * interface for XQuery: the normal representation of a duration in Saxon is the class {@link DurationValue}.
24 * <p>The JAXP specification for this class defines it in terms of XML Schema 1.0 semantics. This defines a structure
25 * with six independent components (year, month, day, hour, minute, second). This implementation is more aligned
26 * to the XPath 2.0 semantics of the data type, which essentially defines duration as an integer number of months plus
27 * a decimal number of seconds.</p>
28 */
29 public class SaxonDuration extends Duration {
30
31 private DurationValue duration;
32
33 /**
34 * Create a SaxonDuration that wraps a supplied DurationValue
35 *
36 * @param duration the value to be wrapped.
37 */
38
39 public SaxonDuration(DurationValue duration) {
40 this.duration = duration;
41 }
42
43 /**
44 * Get the underlying DurationValue
45 *
46 * @return the underlying DurationValue
47 */
48
49 public DurationValue getDurationValue() {
50 return duration;
51 }
52
53 /**
54 * Get the type of this duration, as one of the values xs:duration, xs:dayTimeDuration, or
55 * xs:yearMonthDuration. (Note that the XML Schema namespace URI is used, whereas the current
56 * implementation of the superclass uses a provisional URI allocated in a 2003 W3C working draft)
57 *
58 * @return the type of this duration, as one of the values xs:duration, xs:dayTimeDuration, or
59 * xs:yearMonthDuration
60 */
61
62 public QName getXMLSchemaType() {
63 if (duration instanceof DayTimeDurationValue) {
64 return new QName(NamespaceConstant.SCHEMA, "dayTimeDuration");
65 } else if (duration instanceof YearMonthDurationValue) {
66 return new QName(NamespaceConstant.SCHEMA, "yearMonthDuration");
67 } else {
68 return new QName(NamespaceConstant.SCHEMA, "duration");
69 }
70 }
71
72 /**
73 * Returns the sign of this duration in -1,0, or 1.
74 *
75 * @return -1 if this duration is negative, 0 if the duration is zero,
76 * and 1 if the duration is positive.
77 */
78 public int getSign() {
79 return duration.signum();
80 }
81
82 /**
83 * Gets the value of a field.
84 * <p>Fields of a duration object may contain arbitrary large value.
85 * Therefore this method is designed to return a {@link Number} object.</p>
86 * <p>In case of YEARS, MONTHS, DAYS, HOURS, and MINUTES, the returned
87 * number will be a non-negative integer. In case of seconds,
88 * the returned number may be a non-negative decimal value.</p>
89 * <p>The Saxon implementation of duration uses normalized values. This means
90 * that the YEARS and DAYS fields may be arbitrarily large, but other
91 * components will be limited in size: for example MINUTES will never
92 * exceed 60 and MONTHS will never exceed 12.</p>
93 *
94 * @param field one of the six Field constants (YEARS, MONTHS, DAYS, HOURS,
95 * MINUTES, or SECONDS.)
96 * @return If the specified field is present, this method returns
97 * a non-null non-negative {@link Number} object that
98 * represents its value. If it is not present, return null.
99 * For YEARS, MONTHS, DAYS, HOURS, and MINUTES, this method
100 * returns a {@link java.math.BigInteger} object. For SECONDS, this
101 * method returns a {@link java.math.BigDecimal}.
102 * @throws NullPointerException If the <code>field</code> is <code>null</code>.
103 */
104 public Number getField(DatatypeConstants.Field field) {
105 if (field == DatatypeConstants.YEARS) {
106 return BigInteger.valueOf(((Int64Value) duration.getComponent(AccessorFn.Component.YEAR)).longValue());
107 } else if (field == DatatypeConstants.MONTHS) {
108 return BigInteger.valueOf(((Int64Value) duration.getComponent(AccessorFn.Component.MONTH)).longValue());
109 } else if (field == DatatypeConstants.DAYS) {
110 return BigInteger.valueOf(((Int64Value) duration.getComponent(AccessorFn.Component.DAY)).longValue());
111 } else if (field == DatatypeConstants.HOURS) {
112 return BigInteger.valueOf(((Int64Value) duration.getComponent(AccessorFn.Component.HOURS)).longValue());
113 } else if (field == DatatypeConstants.MINUTES) {
114 return BigInteger.valueOf(((Int64Value) duration.getComponent(AccessorFn.Component.MINUTES)).longValue());
115 } else if (field == DatatypeConstants.SECONDS) {
116 return ((BigDecimalValue) duration.getComponent(AccessorFn.Component.SECONDS)).getDecimalValue();
117 } else {
118 throw new IllegalArgumentException("Invalid field");
119 }
120 }
121
122 /**
123 * Checks if a field is set. In this implementation, all fields are always set.
124 *
125 * @param field one of the six Field constants (YEARS, MONTHS, DAYS, HOURS,
126 * MINUTES, or SECONDS.)
127 * @return This implementation always returns true.
128 */
129 public boolean isSet(DatatypeConstants.Field field) {
130 return true;
131 }
132
133 /**
134 * <p>Computes a new duration whose value is <code>this+rhs</code>.</p>
135 * <p>This implementation follows the XPath semantics. This means that the operation will fail
136 * if the duration is not a yearMonthDuration or a dayTimeDuration
137 *
138 * @param rhs <code>Duration</code> to add to this <code>Duration</code>
139 * @return non-null valid Duration object.
140 * @throws NullPointerException If the rhs parameter is null.
141 * @throws IllegalStateException If the durations are not both dayTimeDurations, or
142 * both yearMonthDurations.
143 * @see #subtract(javax.xml.datatype.Duration)
144 */
145 public Duration add(Duration rhs) {
146 try {
147 return new SaxonDuration(duration.add(((SaxonDuration) rhs).duration));
148 } catch (XPathException e) {
149 throw new IllegalStateException(e.getMessage());
150 }
151 }
152
153 /**
154 * <p>Computes a new duration whose value is <code>this-rhs</code>.</p>
155 * <p>This implementation follows the XPath semantics. This means that the operation will fail
156 * if the duration is not a yearMonthDuration or a dayTimeDuration.
157 *
158 * @param rhs <code>Duration</code> to subtract from this <code>Duration</code>
159 * @return non-null valid Duration object.
160 * @throws NullPointerException If the rhs parameter is null.
161 * @throws IllegalStateException If the durations are not both dayTimeDurations, or
162 * both yearMonthDurations.
163 * @see #add(javax.xml.datatype.Duration)
164 */
165 public Duration subtract(Duration rhs) {
166 try {
167 return new SaxonDuration(duration.subtract(((SaxonDuration) rhs).duration));
168 } catch (XPathException e) {
169 throw new IllegalStateException(e.getMessage());
170 }
171 }
172
173 /**
174 * Adds this duration to a {@link java.util.Calendar} object.
175 * <p>Calls {@link java.util.Calendar#add(int, int)} in the
176 * order of YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, and MILLISECONDS
177 * if those fields are present. Because the {@link java.util.Calendar} class
178 * uses int to hold values, there are cases where this method
179 * won't work correctly (for example if values of fields
180 * exceed the range of int.)</p>
181 * <p>Also, since this duration class is a Gregorian duration, this
182 * method will not work correctly if the given {@link java.util.Calendar}
183 * object is based on some other calendar systems.</p>
184 * <p>Any fractional parts of this <code>Duration</code> object
185 * beyond milliseconds will be simply ignored. For example, if
186 * this duration is "P1.23456S", then 1 is added to SECONDS,
187 * 234 is added to MILLISECONDS, and the rest will be unused.</p>
188 * <p>Note that because {@link java.util.Calendar#add(int, int)} is using
189 * <tt>int</tt>, <code>Duration</code> with values beyond the
190 * range of <tt>int</tt> in its fields
191 * will cause overflow/underflow to the given {@link java.util.Calendar}.
192 * {@link javax.xml.datatype.XMLGregorianCalendar#add(javax.xml.datatype.Duration)} provides the same
193 * basic operation as this method while avoiding
194 * the overflow/underflow issues.</p>
195 *
196 * @param calendar A calendar object whose value will be modified.
197 * @throws NullPointerException if the calendar parameter is null.
198 */
199 public void addTo(Calendar calendar) {
200 int sign = getSign();
201 if (sign == 0) {
202 return;
203 }
204 calendar.add(Calendar.YEAR, getYears() * sign);
205 calendar.add(Calendar.MONTH, getMonths() * sign);
206 calendar.add(Calendar.DAY_OF_MONTH, getDays() * sign);
207 calendar.add(Calendar.HOUR_OF_DAY, getHours() * sign);
208 calendar.add(Calendar.MINUTE, getMinutes() * sign);
209 calendar.add(Calendar.SECOND, (int) ((Int64Value) duration.getComponent(AccessorFn.Component.WHOLE_SECONDS)).longValue() * sign);
210 calendar.add(Calendar.MILLISECOND, (int) ((Int64Value) duration.getComponent(AccessorFn.Component.MICROSECONDS)).longValue() * sign / 1000);
211 }
212
213 /**
214 * Computes a new duration whose value is <code>factor</code> times
215 * longer than the value of this duration.
216 * <p>This implementation follows the XPath semantics. This means that it is defined
217 * only on yearMonthDuration and dayTimeDuration. Other cases produce an IllegalStateException.</p>
218 *
219 * @param factor to multiply by
220 * @return returns a non-null valid <code>Duration</code> object
221 * @throws IllegalStateException if operation produces fraction in
222 * the months field.
223 * @throws NullPointerException if the <code>factor</code> parameter is
224 * <code>null</code>.
225 */
226 public Duration multiply(BigDecimal factor) {
227 try {
228 return new SaxonDuration(duration.multiply(factor.doubleValue()));
229 } catch (XPathException e) {
230 throw new IllegalStateException(e.getMessage());
231 }
232 }
233
234 /**
235 * Returns a new <code>Duration</code> object whose
236 * value is <code>-this</code>.
237 * <p>Since the <code>Duration</code> class is immutable, this method
238 * doesn't change the value of this object. It simply computes
239 * a new Duration object and returns it.</p>
240 *
241 * @return always return a non-null valid <code>Duration</code> object.
242 */
243 public Duration negate() {
244 return new SaxonDuration(duration.negate());
245 }
246
247 /**
248 * <p>Converts the years and months fields into the days field
249 * by using a specific time instant as the reference point.</p>
250 * <p>This implementation does not support this method</p>
251 *
252 * @param startTimeInstant <code>Calendar</code> reference point.
253 * @return <code>Duration</code> of years and months of this <code>Duration</code> as days.
254 * @throws NullPointerException If the startTimeInstant parameter is null.
255 * @throws UnsupportedOperationException Always thrown by this implementation.
256 */
257 public Duration normalizeWith(Calendar startTimeInstant) {
258 throw new UnsupportedOperationException();
259 }
260
261 /**
262 * <p>Partial order relation comparison with this <code>Duration</code> instance.</p>
263 * <p>This implementation follows the XPath semantics. This means that the result is defined only
264 * for dayTimeDuration and yearMonthDuration values, and the result is never indeterminate.</p>
265 * <p>Return:</p>
266 * <ul>
267 * <li>{@link javax.xml.datatype.DatatypeConstants#LESSER}
268 * if this <code>Duration</code> is shorter than <code>duration</code> parameter</li>
269 * <li>{@link javax.xml.datatype.DatatypeConstants#EQUAL}
270 * if this <code>Duration</code> is equal to <code>duration</code> parameter</li>
271 * <li>{@link javax.xml.datatype.DatatypeConstants#GREATER}
272 * if this <code>Duration</code> is longer than <code>duration</code> parameter</li>
273 * <li>{@link javax.xml.datatype.DatatypeConstants#INDETERMINATE}
274 * if a conclusive partial order relation cannot be determined</li>
275 * </ul>
276 *
277 * @param rhs duration to compare
278 * @return the relationship between <code>this</code> <code>Duration</code>and <code>duration</code> parameter as
279 * {@link javax.xml.datatype.DatatypeConstants#LESSER},
280 * {@link javax.xml.datatype.DatatypeConstants#EQUAL},
281 * {@link javax.xml.datatype.DatatypeConstants#GREATER}
282 * or {@link javax.xml.datatype.DatatypeConstants#INDETERMINATE}.
283 * @throws UnsupportedOperationException If the underlying implementation
284 * cannot reasonably process the request, e.g. W3C XML Schema allows for
285 * arbitrarily large/small/precise values, the request may be beyond the
286 * implementations capability.
287 * @throws NullPointerException if <code>duration</code> is <code>null</code>.
288 * @throws IllegalArgumentException if the operands are not dayTimeDuration or yearMonthDuration values.
289 * @see #isShorterThan(javax.xml.datatype.Duration)
290 * @see #isLongerThan(javax.xml.datatype.Duration)
291 */
292 public int compare(/*@NotNull*/ Duration rhs) {
293 if (!(rhs instanceof SaxonDuration)) {
294 throw new IllegalArgumentException("Supplied duration is not a SaxonDuration");
295 }
296 Comparable c0 = duration.getSchemaComparable();
297 Comparable c1 = ((SaxonDuration) rhs).duration.getSchemaComparable();
298 return c0.compareTo(c1);
299 }
300
301 /**
302 * Returns a hash code consistent with the definition of the equals method.
303 *
304 * @see Object#hashCode()
305 */
306 public int hashCode() {
307 return duration.hashCode();
308 }
309 }