Debian Codegraph @

net/sf/saxon/value/TimeValue.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.expr.XPathContext;
11 import net.sf.saxon.functions.AccessorFn;
12 import net.sf.saxon.om.SequenceTool;
13 import net.sf.saxon.trans.Err;
14 import net.sf.saxon.trans.NoDynamicContextException;
15 import net.sf.saxon.trans.XPathException;
16 import net.sf.saxon.tree.util.FastStringBuffer;
17 import net.sf.saxon.type.AtomicType;
18 import net.sf.saxon.type.BuiltInAtomicType;
19 import net.sf.saxon.type.ConversionResult;
20 import net.sf.saxon.type.ValidationFailure;
21
22 import java.math.BigDecimal;
23 import java.math.RoundingMode;
24 import java.util.*;
25
26 /**
27 * A value of type xs:time
28 */
29
30 public final class TimeValue extends CalendarValue implements Comparable {
31
32 private byte hour;
33 private byte minute;
34 private byte second;
35 private int nanosecond;
36
37 private TimeValue() {
38 }
39
40 /**
41 * Construct a time value given the hour, minute, second, and microsecond components.
42 * This constructor performs no validation.
43 *
44 * @param hour the hour value, 0-23
45 * @param minute the minutes value, 0-59
46 * @param second the seconds value, 0-59
47 * @param microsecond the number of microseconds, 0-999999
48 * @param tz the timezone displacement in minutes from UTC. Supply the value
49 * {@link CalendarValue#NO_TIMEZONE} if there is no timezone component.
50 */
51
52 public TimeValue(byte hour, byte minute, byte second, int microsecond, int tz) {
53 this.hour = hour;
54 this.minute = minute;
55 this.second = second;
56 this.nanosecond = microsecond * 1000;
57 setTimezoneInMinutes(tz);
58 typeLabel = BuiltInAtomicType.TIME;
59 }
60
61 /**
62 * Constructor to construct a time value given the hour, minute, second, and nanosecond components.
63 * This constructor performs no validation.
64 *
65 * @param hour the hour value, 0-23
66 * @param minute the minutes value, 0-59
67 * @param second the seconds value, 0-59
68 * @param nanosecond the number of nanoseconds, 0-999999999
69 * @param tz the timezone displacement in minutes from UTC. Supply the value
70 * {@link CalendarValue#NO_TIMEZONE} if there is no timezone component.
71 * @param flag used to disambiguate this constructor. Must be set to "".
72 */
73
74 public TimeValue(byte hour, byte minute, byte second, int nanosecond, int tz, String flag) {
75 if (!flag.isEmpty()) {
76 throw new IllegalArgumentException();
77 }
78 this.hour = hour;
79 this.minute = minute;
80 this.second = second;
81 this.nanosecond = nanosecond;
82 setTimezoneInMinutes(tz);
83 typeLabel = BuiltInAtomicType.TIME;
84 }
85
86 /**
87 * Factory method to construct a time value given the hour, minute, second, and nanosecond components.
88 * This constructor performs no validation.
89 *
90 * @param hour the hour value, 0-23
91 * @param minute the minutes value, 0-59
92 * @param second the seconds value, 0-59
93 * @param nanosecond the number of nanoseconds, 0-999_999_999
94 * @param tz the timezone displacement in minutes from UTC. Supply the value
95 * {@link CalendarValue#NO_TIMEZONE} if there is no timezone component.
96 */
97
98 public static TimeValue makeTimeValue(byte hour, byte minute, byte second, int nanosecond, int tz) {
99 return new TimeValue(hour, minute, second, nanosecond, tz, "");
100 }
101
102
103 /**
104 * Constructor: create a time value given a Java calendar object
105 *
106 * @param calendar holds the date and time
107 * @param tz the timezone offset in minutes, or NO_TIMEZONE indicating that there is no timezone
108 */
109
110 public TimeValue(/*@NotNull*/ GregorianCalendar calendar, int tz) {
111 hour = (byte) calendar.get(Calendar.HOUR_OF_DAY);
112 minute = (byte) calendar.get(Calendar.MINUTE);
113 second = (byte) calendar.get(Calendar.SECOND);
114 nanosecond = calendar.get(Calendar.MILLISECOND) * 1_000_000;
115 setTimezoneInMinutes(tz);
116 typeLabel = BuiltInAtomicType.TIME;
117 }
118
119 /**
120 * Static factory method: create a time value from a supplied string, in
121 * ISO 8601 format
122 *
123 * @param s the time in the lexical format hh:mm:ss[.ffffff] followed optionally by
124 * timezone in the form [+-]hh:mm or Z
125 * @return either a TimeValue corresponding to the xs:time, or a ValidationFailure
126 * if the supplied value was invalid
127 */
128
129 /*@NotNull*/
130 public static ConversionResult makeTimeValue(CharSequence s) {
131 // input must have format hh:mm:ss[.fff*][([+|-]hh:mm | Z)]
132 TimeValue tv = new TimeValue();
133 StringTokenizer tok = new StringTokenizer(Whitespace.trimWhitespace(s).toString(), "-:.+Z", true);
134 if (!tok.hasMoreElements()) {
135 return badTime("too short", s);
136 }
137 String part = (String) tok.nextElement();
138
139 if (part.length() != 2) {
140 return badTime("hour must be two digits", s);
141 }
142 int value = DurationValue.simpleInteger(part);
143 if (value < 0) {
144 return badTime("Non-numeric hour component", s);
145 }
146 tv.hour = (byte) value;
147 if (tv.hour > 24) {
148 return badTime("hour is out of range", s);
149 }
150 if (!tok.hasMoreElements()) {
151 return badTime("too short", s);
152 }
153 if (!":".equals(tok.nextElement())) {
154 return badTime("wrong delimiter after hour", s);
155 }
156
157 if (!tok.hasMoreElements()) {
158 return badTime("too short", s);
159 }
160 part = (String) tok.nextElement();
161 if (part.length() != 2) {
162 return badTime("minute must be two digits", s);
163 }
164 value = DurationValue.simpleInteger(part);
165 if (value < 0) {
166 return badTime("Non-numeric minute component", s);
167 }
168 tv.minute = (byte) value;
169 if (tv.minute > 59) {
170 return badTime("minute is out of range", s);
171 }
172 if (tv.hour == 24 && tv.minute != 0) {
173 return badTime("If hour is 24, minute must be 00", s);
174 }
175 if (!tok.hasMoreElements()) {
176 return badTime("too short", s);
177 }
178 if (!":".equals(tok.nextElement())) {
179 return badTime("wrong delimiter after minute", s);
180 }
181
182 if (!tok.hasMoreElements()) {
183 return badTime("too short", s);
184 }
185 part = (String) tok.nextElement();
186 if (part.length() != 2) {
187 return badTime("second must be two digits", s);
188 }
189 value = DurationValue.simpleInteger(part);
190 if (value < 0) {
191 return badTime("Non-numeric second component", s);
192 }
193 tv.second = (byte) value;
194 if (tv.second > 59) {
195 return badTime("second is out of range", s);
196 }
197 if (tv.hour == 24 && tv.second != 0) {
198 return badTime("If hour is 24, second must be 00", s);
199 }
200
201 int tz = 0;
202 boolean negativeTz = false;
203 int state = 0;
204 while (tok.hasMoreElements()) {
205 if (state == 9) {
206 return badTime("characters after the end", s);
207 }
208 String delim = (String) tok.nextElement();
209 if (".".equals(delim)) {
210 if (state != 0) {
211 return badTime("decimal separator occurs twice", s);
212 }
213 if (!tok.hasMoreElements()) {
214 return badTime("decimal point must be followed by digits", s);
215 }
216 part = (String) tok.nextElement();
217 if (part.length() > 9 && part.matches("^[0-9]+$")) {
218 part = part.substring(0, 9);
219 }
220 value = DurationValue.simpleInteger(part);
221 if (value < 0) {
222 return badTime("Non-numeric fractional seconds component", s);
223 }
224 double fractionalSeconds = Double.parseDouble('.' + part);
225 tv.nanosecond = (int) Math.round(fractionalSeconds * 1_000_000_000);
226 if (tv.hour == 24 && tv.nanosecond != 0) {
227 return badTime("If hour is 24, fractional seconds must be 0", s);
228 }
229 state = 1;
230 } else if ("Z".equals(delim)) {
231 if (state > 1) {
232 return badTime("Z cannot occur here", s);
233 }
234 tz = 0;
235 state = 9; // we've finished
236 tv.setTimezoneInMinutes(0);
237 } else if ("+".equals(delim) || "-".equals(delim)) {
238 if (state > 1) {
239 return badTime(delim + " cannot occur here", s);
240 }
241 state = 2;
242 if (!tok.hasMoreElements()) {
243 return badTime("missing timezone", s);
244 }
245 part = (String) tok.nextElement();
246 if (part.length() != 2) {
247 return badTime("timezone hour must be two digits", s);
248 }
249 value = DurationValue.simpleInteger(part);
250 if (value < 0) {
251 return badTime("Non-numeric timezone hour component", s);
252 }
253 tz = value * 60;
254 if (tz > 14 * 60) {
255 return badTime("timezone hour is out of range", s);
256 }
257 if ("-".equals(delim)) {
258 negativeTz = true;
259 }
260 } else if (":".equals(delim)) {
261 if (state != 2) {
262 return badTime("colon cannot occur here", s);
263 }
264 state = 9;
265 part = (String) tok.nextElement();
266 value = DurationValue.simpleInteger(part);
267 if (value < 0) {
268 return badTime("Non-numeric timezone minute component", s);
269 }
270 int tzminute = value;
271 if (part.length() != 2) {
272 return badTime("timezone minute must be two digits", s);
273 }
274 if (tzminute > 59) {
275 return badTime("timezone minute is out of range", s);
276 }
277
278 tz += tzminute;
279 if (negativeTz) {
280 tz = -tz;
281 }
282 tv.setTimezoneInMinutes(tz);
283 } else {
284 return badTime("timezone format is incorrect", s);
285 }
286 }
287
288 if (state == 2 || state == 3) {
289 return badTime("timezone incomplete", s);
290 }
291
292 if (tv.hour == 24) {
293 tv.hour = 0;
294 }
295
296 tv.typeLabel = BuiltInAtomicType.TIME;
297 return tv;
298 }
299
300 /*@NotNull*/
301 private static ValidationFailure badTime(String msg, CharSequence value) {
302 ValidationFailure err = new ValidationFailure(
303 "Invalid time " + Err.wrap(value, Err.VALUE) + " (" + msg + ")");
304 err.setErrorCode("FORG0001");
305 return err;
306 }
307
308 /**
309 * Determine the primitive type of the value. This delivers the same answer as
310 * getItemType().getPrimitiveItemType(). The primitive types are
311 * the 19 primitive types of XML Schema, plus xs:integer, xs:dayTimeDuration and xs:yearMonthDuration,
312 * and xs:untypedAtomic. For external objects, the result is AnyAtomicType.
313 */
314
315 /*@NotNull*/
316 public BuiltInAtomicType getPrimitiveType() {
317 return BuiltInAtomicType.TIME;
318 }
319
320 /**
321 * Get the hour component, 0-23
322 *
323 * @return the hour
324 */
325
326 public byte getHour() {
327 return hour;
328 }
329
330 /**
331 * Get the minute component, 0-59
332 *
333 * @return the minute
334 */
335
336 public byte getMinute() {
337 return minute;
338 }
339
340 /**
341 * Get the second component, 0-59
342 *
343 * @return the second
344 */
345
346 public byte getSecond() {
347 return second;
348 }
349
350 /**
351 * Get the microsecond component, 0-999_999
352 *
353 * @return the nanoseconds component divided by 1000, rounded towards zero
354 */
355
356 public int getMicrosecond() {
357 return nanosecond / 1000;
358 }
359
360 /**
361 * Get the nanosecond component, 0-999_999
362 *
363 * @return the nanoseconds
364 */
365
366 public int getNanosecond() {
367 return nanosecond;
368 }
369
370
371 /**
372 * Convert to string
373 *
374 * @return ISO 8601 representation, in the localized timezone
375 * (the timezone held within the value).
376 */
377
378 /*@NotNull*/
379 public CharSequence getPrimitiveStringValue() {
380
381 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C16);
382
383 appendTwoDigits(sb, hour);
384 sb.append(':');
385 appendTwoDigits(sb, minute);
386 sb.append(':');
387 appendTwoDigits(sb, second);
388 if (nanosecond != 0) {
389 sb.append('.');
390 int ms = nanosecond;
391 int div = 100_000_000;
392 while (ms > 0) {
393 int d = ms / div;
394 sb.append((char) (d + '0'));
395 ms = ms % div;
396 div /= 10;
397 }
398 }
399
400 if (hasTimezone()) {
401 appendTimezone(sb);
402 }
403
404 return sb;
405
406 }
407
408
409 /**
410 * Get the canonical lexical representation as defined in XML Schema. This is not always the same
411 * as the result of casting to a string according to the XPath rules. For an xs:time it is the
412 * time adjusted to UTC
413 *
414 * @return the canonical lexical representation if defined in XML Schema
415 */
416
417 public CharSequence getCanonicalLexicalRepresentation() {
418 if (hasTimezone() && getTimezoneInMinutes() != 0) {
419 return adjustTimezone(0).getStringValueCS();
420 } else {
421 return getStringValueCS();
422 }
423 }
424
425
426 /**
427 * Convert to a DateTime value. The date components represent a reference date, as defined
428 * in the spec for comparing times.
429 */
430
431 /*@NotNull*/
432 public DateTimeValue toDateTime() {
433 return new DateTimeValue(1972, (byte) 12, (byte) 31, hour, minute, second, nanosecond, getTimezoneInMinutes());
434 }
435
436 /**
437 * Get a Java Calendar object corresponding to this time, on a reference date
438 */
439
440 /*@NotNull*/
441 public GregorianCalendar getCalendar() {
442 // create a calendar using the specified timezone
443 int tz = hasTimezone() ? getTimezoneInMinutes()*60000 : 0;
444 TimeZone zone = new SimpleTimeZone(tz, "LLL");
445 GregorianCalendar calendar = new GregorianCalendar(zone);
446 calendar.setLenient(false);
447 if (tz < calendar.getMinimum(Calendar.ZONE_OFFSET) || tz > calendar.getMaximum(Calendar.ZONE_OFFSET)) {
448 return adjustTimezone(0).getCalendar();
449 }
450
451 // use a reference date of 1972-12-31
452 calendar.set(1972, Calendar.DECEMBER, 31, hour, minute, second);
453 calendar.set(Calendar.MILLISECOND, nanosecond / 1_000_000);
454 calendar.set(Calendar.ZONE_OFFSET, tz);
455 calendar.set(Calendar.DST_OFFSET, 0);
456
457 calendar.getTime();
458 return calendar;
459 }
460
461 /**
462 * Make a copy of this time value,
463 * but with a different type label
464 *
465 * @param typeLabel the new type label. This must be a subtype of xs:time.
466 */
467
468 /*@NotNull*/
469 public AtomicValue copyAsSubType(AtomicType typeLabel) {
470 TimeValue v = new TimeValue(hour, minute, second, nanosecond, getTimezoneInMinutes(), "");
471 v.typeLabel = typeLabel;
472 return v;
473 }
474
475 /**
476 * Return a new time with the same normalized value, but
477 * in a different timezone. This is called only for a TimeValue that has an explicit timezone
478 *
479 * @param timezone the new timezone offset, in minutes
480 * @return the time in the new timezone. This will be a new TimeValue unless no change
481 * was required to the original value
482 */
483
484 /*@NotNull*/
485 public TimeValue adjustTimezone(int timezone) {
486 DateTimeValue dt = toDateTime().adjustTimezone(timezone);
487 return new TimeValue(dt.getHour(), dt.getMinute(), dt.getSecond(),
488 dt.getNanosecond(), dt.getTimezoneInMinutes(), "");
489 }
490
491 /**
492 * Get a component of the value. Returns null if the timezone component is
493 * requested and is not present.
494 * @param component the required component
495 */
496
497 /*@Nullable*/
498 public AtomicValue getComponent(AccessorFn.Component component) throws XPathException {
499 switch (component) {
500 case HOURS:
501 return Int64Value.makeIntegerValue(hour);
502 case MINUTES:
503 return Int64Value.makeIntegerValue(minute);
504 case SECONDS:
505 BigDecimal d = BigDecimal.valueOf(nanosecond);
506 d = d.divide(BigDecimalValue.BIG_DECIMAL_ONE_BILLION, 6, RoundingMode.HALF_UP);
507 d = d.add(BigDecimal.valueOf(second));
508 return new BigDecimalValue(d);
509 case WHOLE_SECONDS: //(internal use only)
510 return Int64Value.makeIntegerValue(second);
511 case MICROSECONDS:
512 return new Int64Value(nanosecond / 1000);
513 case NANOSECONDS:
514 return new Int64Value(nanosecond);
515 case TIMEZONE:
516 if (hasTimezone()) {
517 return DayTimeDurationValue.fromMilliseconds(60000L * getTimezoneInMinutes());
518 } else {
519 return null;
520 }
521 default:
522 throw new IllegalArgumentException("Unknown component for time: " + component);
523 }
524 }
525
526 /**
527 * Compare the value to another dateTime value
528 *
529 * @param other The other dateTime value
530 * @return negative value if this one is the earler, 0 if they are chronologically equal,
531 * positive value if this one is the later. For this purpose, dateTime values with an unknown
532 * timezone are considered to be UTC values (the Comparable interface requires
533 * a total ordering).
534 * @throws ClassCastException if the other value is not a TimeValue (the parameter
535 * is declared as Object to satisfy the Comparable interface)
536 */
537
538 public int compareTo(Object other) {
539 TimeValue otherTime = (TimeValue) other;
540 if (getTimezoneInMinutes() == otherTime.getTimezoneInMinutes()) {
541 if (hour != otherTime.hour) {
542 return IntegerValue.signum(hour - otherTime.hour);
543 } else if (minute != otherTime.minute) {
544 return IntegerValue.signum(minute - otherTime.minute);
545 } else if (second != otherTime.second) {
546 return IntegerValue.signum(second - otherTime.second);
547 } else if (nanosecond != otherTime.nanosecond) {
548 return IntegerValue.signum(nanosecond - otherTime.nanosecond);
549 } else {
550 return 0;
551 }
552 } else {
553 return toDateTime().compareTo(otherTime.toDateTime());
554 }
555 }
556
557 /**
558 * Compare the value to another dateTime value
559 *
560 * @param other The other dateTime value
561 * @param implicitTimezone The implicit timezone assumed for a value with no timezone
562 * @return negative value if this one is the earler, 0 if they are chronologically equal,
563 * positive value if this one is the later. For this purpose, dateTime values with an unknown
564 * timezone are considered to be UTC values (the Comparable interface requires
565 * a total ordering).
566 * @throws ClassCastException if the other value is not a DateTimeValue (the parameter
567 * is declared as Object to satisfy the Comparable interface)
568 * @throws NoDynamicContextException if the implicit timezone is required and is not available
569 * (because the function is called at compile time)
570 */
571
572 public int compareTo(/*@NotNull*/ CalendarValue other, /*@NotNull*/ int implicitTimezone) throws NoDynamicContextException {
573 if (!(other instanceof TimeValue)) {
574 throw new ClassCastException("Time values are not comparable to " + other.getClass());
575 }
576 TimeValue otherTime = (TimeValue) other;
577 if (getTimezoneInMinutes() == otherTime.getTimezoneInMinutes()) {
578 // The values have the same time zone, or neither has a timezone
579 return compareTo(other);
580 } else {
581 return toDateTime().compareTo(otherTime.toDateTime(), implicitTimezone);
582 }
583 }
584
585
586 /*@NotNull*/
587 public Comparable getSchemaComparable() {
588 return new TimeComparable();
589 }
590
591 private class TimeComparable implements Comparable {
592
593 /*@NotNull*/
594 public TimeValue asTimeValue() {
595 return TimeValue.this;
596 }
597
598 public int compareTo(/*@NotNull*/ Object o) {
599 if (o instanceof TimeComparable) {
600 DateTimeValue dt0 = asTimeValue().toDateTime();
601 DateTimeValue dt1 = ((TimeComparable) o).asTimeValue().toDateTime();
602 return dt0.getSchemaComparable().compareTo(dt1.getSchemaComparable());
603 } else {
604 return SequenceTool.INDETERMINATE_ORDERING;
605 }
606 }
607
608 public boolean equals(/*@NotNull*/ Object o) {
609 return compareTo(o) == 0;
610 }
611
612 public int hashCode() {
613 return TimeValue.this.toDateTime().getSchemaComparable().hashCode();
614 }
615 }
616
617
618 public boolean equals(Object other) {
619 return other instanceof TimeValue && compareTo(other) == 0;
620 }
621
622 public int hashCode() {
623 return DateTimeValue.hashCode(
624 1951, (byte) 10, (byte) 11, hour, minute, second, nanosecond, getTimezoneInMinutes());
625 }
626
627 /**
628 * Add a duration to a dateTime
629 *
630 * @param duration the duration to be added (may be negative)
631 * @return the new date
632 * @throws net.sf.saxon.trans.XPathException
633 * if the duration is an xs:duration, as distinct from
634 * a subclass thereof
635 */
636
637 /*@NotNull*/
638 public TimeValue add(/*@NotNull*/ DurationValue duration) throws XPathException {
639 if (duration instanceof DayTimeDurationValue) {
640 DateTimeValue dt = toDateTime().add(duration);
641 return new TimeValue(dt.getHour(), dt.getMinute(), dt.getSecond(),
642 dt.getNanosecond(), getTimezoneInMinutes(), "");
643 } else {
644 XPathException err = new XPathException("Time+Duration arithmetic is supported only for xs:dayTimeDuration");
645 err.setErrorCode("XPTY0004");
646 err.setIsTypeError(true);
647 throw err;
648 }
649 }
650
651 /**
652 * Determine the difference between two points in time, as a duration
653 *
654 * @param other the other point in time
655 * @param context XPath dynamic evaluation context
656 * @return the duration as an xs:dayTimeDuration
657 * @throws XPathException for example if one value is a date and the other is a time
658 */
659
660 public DayTimeDurationValue subtract(/*@NotNull*/ CalendarValue other, XPathContext context) throws XPathException {
661 if (!(other instanceof TimeValue)) {
662 XPathException err = new XPathException("First operand of '-' is a time, but the second is not");
663 err.setIsTypeError(true);
664 throw err;
665 }
666 return super.subtract(other, context);
667 }
668
669
670 }
671