Debian Codegraph @

net/sf/saxon/value/GDateValue.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.om.SequenceTool;
12 import net.sf.saxon.trans.Err;
13 import net.sf.saxon.trans.NoDynamicContextException;
14 import net.sf.saxon.trans.XPathException;
15 import net.sf.saxon.type.ConversionResult;
16 import net.sf.saxon.type.ValidationFailure;
17
18 import java.util.*;
19
20 /**
21 * Abstract superclass for the primitive types containing date components: xs:date, xs:gYear,
22 * xs:gYearMonth, xs:gMonth, xs:gMonthDay, xs:gDay
23 */
24 public abstract class GDateValue extends CalendarValue {
25 protected int year; // unlike the lexical representation, includes a year zero
26 protected byte month;
27 protected byte day;
28 protected boolean hasNoYearZero;
29 /**
30 * Test whether a candidate date is actually a valid date in the proleptic Gregorian calendar
31 */
32
33 /*@NotNull*/ protected static byte[] daysPerMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
34 /*@NotNull*/ protected static final short[] monthData = {306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275};
35
36 /**
37 * Get the year component of the date (in local form)
38 *
39 * @return the year component, as represented internally (allowing a year zero)
40 */
41
42 public int getYear() {
43 return year;
44 }
45
46 /**
47 * Get the month component of the date (in local form)
48 *
49 * @return the month component (1-12)
50 */
51
52 public byte getMonth() {
53 return month;
54 }
55
56 /**
57 * Get the day component of the date (in local form)
58 *
59 * @return the day component (1-31)
60 */
61
62 public byte getDay() {
63 return day;
64 }
65
66 /*@NotNull*/
67 public GregorianCalendar getCalendar() {
68
69 int tz = hasTimezone() ? getTimezoneInMinutes() * 60000 : 0;
70 TimeZone zone = new SimpleTimeZone(tz, "LLL");
71 GregorianCalendar calendar = new GregorianCalendar(zone);
72 calendar.setGregorianChange(new Date(Long.MIN_VALUE));
73 if (tz < calendar.getMinimum(Calendar.ZONE_OFFSET) || tz > calendar.getMaximum(Calendar.ZONE_OFFSET)) {
74 return adjustTimezone(0).getCalendar();
75 }
76 calendar.clear();
77 calendar.setLenient(false);
78 int yr = year;
79 if (year <= 0) {
80 yr = hasNoYearZero ? 1 - year : 0 - year;
81 calendar.set(Calendar.ERA, GregorianCalendar.BC);
82 }
83 //noinspection MagicConstant
84 calendar.set(yr, month - 1, day);
85 calendar.set(Calendar.ZONE_OFFSET, tz);
86 calendar.set(Calendar.DST_OFFSET, 0);
87 calendar.getTime();
88 return calendar;
89 }
90
91 /**
92 * Initialize the DateValue using a character string in the format yyyy-mm-dd and an optional time zone.
93 * Input must have format [-]yyyy-mm-dd[([+|-]hh:mm | Z)]
94 *
95 * @param d the "raw" DateValue to be populated
96 * @param s the supplied string value
97 * @param allowYearZero true if (as in XSD 1.1) there is a year zero, false if (as in XSD 1.0) there is not
98 * @return either the supplied GDateValue, with its data initialized; or a ValidationFailure
99 */
100
101 /*@NotNull*/
102 protected static ConversionResult setLexicalValue(GDateValue d, CharSequence s, boolean allowYearZero) {
103 d.hasNoYearZero = !allowYearZero;
104 StringTokenizer tok = new StringTokenizer(Whitespace.trimWhitespace(s).toString(), "-:+TZ", true);
105 try {
106 if (!tok.hasMoreElements()) {
107 return badDate("Too short", s);
108 }
109 String part = (String) tok.nextElement();
110 int era = +1;
111 if ("+".equals(part)) {
112 return badDate("Date must not start with '+' sign", s);
113 } else if ("-".equals(part)) {
114 era = -1;
115 if (!tok.hasMoreElements()) {
116 return badDate("No year after '-'", s);
117 }
118 part = (String) tok.nextElement();
119 }
120
121 if (part.length() < 4) {
122 return badDate("Year is less than four digits", s);
123 }
124 if (part.length() > 4 && part.charAt(0) == '0') {
125 return badDate("When year exceeds 4 digits, leading zeroes are not allowed", s);
126 }
127 int value = DurationValue.simpleInteger(part);
128 if (value < 0) {
129 if (value == -1) {
130 return badDate("Non-numeric year component", s);
131 } else {
132 return badDate("Year is outside the range that Saxon can handle", s, "FODT0001");
133 }
134 }
135 d.year = value * era;
136 if (d.year == 0 && !allowYearZero) {
137 return badDate("Year zero is not allowed", s);
138 }
139 if (era < 0 && !allowYearZero) {
140 d.year++; // if year zero not allowed, -0001 is the year before +0001, represented as 0 internally.
141 }
142 if (!tok.hasMoreElements()) {
143 return badDate("Too short", s);
144 }
145 if (!"-".equals(tok.nextElement())) {
146 return badDate("Wrong delimiter after year", s);
147 }
148
149 if (!tok.hasMoreElements()) {
150 return badDate("Too short", s);
151 }
152 part = (String) tok.nextElement();
153 if (part.length() != 2) {
154 return badDate("Month must be two digits", s);
155 }
156 value = DurationValue.simpleInteger(part);
157 if (value < 0) {
158 return badDate("Non-numeric month component", s);
159 }
160 d.month = (byte) value;
161 if (d.month < 1 || d.month > 12) {
162 return badDate("Month is out of range", s);
163 }
164 if (!tok.hasMoreElements()) {
165 return badDate("Too short", s);
166 }
167 if (!"-".equals(tok.nextElement())) {
168 return badDate("Wrong delimiter after month", s);
169 }
170
171 if (!tok.hasMoreElements()) {
172 return badDate("Too short", s);
173 }
174 part = (String) tok.nextElement();
175 if (part.length() != 2) {
176 return badDate("Day must be two digits", s);
177 }
178 value = DurationValue.simpleInteger(part);
179 if (value < 0) {
180 return badDate("Non-numeric day component", s);
181 }
182 d.day = (byte) value;
183 if (d.day < 1 || d.day > 31) {
184 return badDate("Day is out of range", s);
185 }
186
187 int tzOffset;
188 if (tok.hasMoreElements()) {
189
190 String delim = (String) tok.nextElement();
191
192 if ("T".equals(delim)) {
193 return badDate("Value includes time", s);
194 } else if ("Z".equals(delim)) {
195 tzOffset = 0;
196 if (tok.hasMoreElements()) {
197 return badDate("Continues after 'Z'", s);
198 }
199 d.setTimezoneInMinutes(tzOffset);
200
201 } else if (!(!"+".equals(delim) && !"-".equals(delim))) {
202 if (!tok.hasMoreElements()) {
203 return badDate("Missing timezone", s);
204 }
205 part = (String) tok.nextElement();
206 value = DurationValue.simpleInteger(part);
207 if (value < 0) {
208 return badDate("Non-numeric timezone hour component", s);
209 }
210 int tzhour = value;
211 if (part.length() != 2) {
212 return badDate("Timezone hour must be two digits", s);
213 }
214 if (tzhour > 14) {
215 return badDate("Timezone hour is out of range", s);
216 }
217 if (!tok.hasMoreElements()) {
218 return badDate("No minutes in timezone", s);
219 }
220 if (!":".equals(tok.nextElement())) {
221 return badDate("Wrong delimiter after timezone hour", s);
222 }
223
224 if (!tok.hasMoreElements()) {
225 return badDate("No minutes in timezone", s);
226 }
227 part = (String) tok.nextElement();
228 value = DurationValue.simpleInteger(part);
229 if (value < 0) {
230 return badDate("Non-numeric timezone minute component", s);
231 }
232 int tzminute = value;
233 if (part.length() != 2) {
234 return badDate("Timezone minute must be two digits", s);
235 }
236 if (tzminute > 59) {
237 return badDate("Timezone minute is out of range", s);
238 }
239 if (tok.hasMoreElements()) {
240 return badDate("Continues after timezone", s);
241 }
242
243 tzOffset = tzhour * 60 + tzminute;
244 if ("-".equals(delim)) {
245 tzOffset = -tzOffset;
246 }
247 d.setTimezoneInMinutes(tzOffset);
248
249 } else {
250 return badDate("Timezone format is incorrect", s);
251 }
252 }
253
254 if (!isValidDate(d.year, d.month, d.day)) {
255 return badDate("Non-existent date", s);
256 }
257
258 } catch (NumberFormatException err) {
259 return badDate("Non-numeric component", s);
260 }
261 return d;
262 }
263
264 private static ValidationFailure badDate(String msg, CharSequence value) {
265 ValidationFailure err = new ValidationFailure(
266 "Invalid date " + Err.wrap(value, Err.VALUE) + " (" + msg + ")");
267 err.setErrorCode("FORG0001");
268 return err;
269 }
270
271 private static ValidationFailure badDate(String msg, CharSequence value, String errorCode) {
272 ValidationFailure err = new ValidationFailure(
273 "Invalid date " + Err.wrap(value, Err.VALUE) + " (" + msg + ")");
274 err.setErrorCode(errorCode);
275 return err;
276 }
277
278
279 /**
280 * Determine whether a given date is valid
281 *
282 * @param year the year (permitting year zero)
283 * @param month the month (1-12)
284 * @param day the day (1-31)
285 * @return true if this is a valid date
286 */
287
288 public static boolean isValidDate(int year, int month, int day) {
289 return month > 0 && month <= 12 && day > 0 && day <= daysPerMonth[month - 1]
290 || month == 2 && day == 29 && isLeapYear(year);
291 }
292
293 /**
294 * Test whether a year is a leap year
295 *
296 * @param year the year (permitting year zero)
297 * @return true if the supplied year is a leap year
298 */
299
300 public static boolean isLeapYear(int year) {
301 return (year % 4 == 0) && !(year % 100 == 0 && !(year % 400 == 0));
302 }
303
304 /**
305 * Check that the value can be handled in Saxon-JS
306 *
307 * @throws XPathException if it can't be handled in Saxon-JS
308 */
309
310 @Override
311 public void checkValidInJavascript() throws XPathException {
312 if (year <= 0 || year > 9999) {
313 throw new XPathException("Year out of range for Saxon-JS", "FODT0001");
314 }
315 }
316
317 /**
318 * The equals() methods on atomic values is defined to follow the semantics of eq when applied
319 * to two atomic values. When the other operand is not an atomic value, the result is undefined
320 * (may be false, may be an exception). When the other operand is an atomic value that cannot be
321 * compared with this one, the method returns false.
322 * <p>The hashCode() method is consistent with equals().</p>
323 * <p>This implementation performs a context-free comparison: it fails with ClassCastException
324 * if one value has a timezone and the other does not.</p>
325 *
326 * @param o the other value
327 * @return true if the other operand is an atomic value and the two values are equal as defined
328 * by the XPath eq operator
329 * @throws ClassCastException if the values are not comparable
330 */
331
332 public boolean equals(Object o) {
333 if (o instanceof GDateValue) {
334 GDateValue gdv = (GDateValue) o;
335 return getPrimitiveType() == gdv.getPrimitiveType() && toDateTime().equals(gdv.toDateTime());
336 } else {
337 return false;
338 }
339 }
340
341 public int hashCode() {
342 return DateTimeValue.hashCode(year, month, day, (byte) 12, (byte) 0, (byte) 0, 0, getTimezoneInMinutes());
343 }
344
345 /**
346 * Compare this value to another value of the same type, using the supplied context object
347 * to get the implicit timezone if required. This method implements the XPath comparison semantics.
348 *
349 * @param other the value to be compared
350 * @param implicitTimezone the implicit timezone to be used for a value with no timezone
351 * @return -1 if this value is less, 0 if equal, +1 if greater
352 */
353
354 public int compareTo(/*@NotNull*/ CalendarValue other, int implicitTimezone) throws NoDynamicContextException {
355 if (getPrimitiveType() != other.getPrimitiveType()) {
356 throw new ClassCastException("Cannot compare dates of different types");
357 // covers, for example, comparing a gYear to a gYearMonth
358 }
359 GDateValue v2 = (GDateValue) other;
360 if (getTimezoneInMinutes() == other.getTimezoneInMinutes()) {
361 // both values are in the same timezone (explicitly or implicitly)
362 if (year != v2.year) {
363 return IntegerValue.signum(year - v2.year);
364 }
365 if (month != v2.month) {
366 return IntegerValue.signum(month - v2.month);
367 }
368 if (day != v2.day) {
369 return IntegerValue.signum(day - v2.day);
370 }
371 return 0;
372 }
373 return toDateTime().compareTo(other.toDateTime(), implicitTimezone);
374 }
375
376 /**
377 * Convert to DateTime.
378 *
379 * @return the starting instant of the GDateValue (with the same timezone)
380 */
381
382 /*@NotNull*/
383 public DateTimeValue toDateTime() {
384 return new DateTimeValue(year, month, day, (byte) 0, (byte) 0, (byte) 0, 0, getTimezoneInMinutes(), hasNoYearZero);
385 }
386
387
388 /*@NotNull*/
389 public Comparable getSchemaComparable() {
390 return new GDateComparable();
391 }
392
393 /**
394 * Get a component of the value. Returns null if the timezone component is
395 * requested and is not present.
396 * @param component the required component
397 */
398
399 /*@Nullable*/
400 public AtomicValue getComponent(AccessorFn.Component component) throws XPathException {
401 switch (component) {
402 case YEAR_ALLOWING_ZERO:
403 return Int64Value.makeIntegerValue(year);
404 case YEAR:
405 return Int64Value.makeIntegerValue(year > 0 || !hasNoYearZero ? year : year - 1);
406 case MONTH:
407 return Int64Value.makeIntegerValue(month);
408 case DAY:
409 return Int64Value.makeIntegerValue(day);
410 case TIMEZONE:
411 if (hasTimezone()) {
412 return DayTimeDurationValue.fromMilliseconds(60000L * getTimezoneInMinutes());
413 } else {
414 return null;
415 }
416 default:
417 throw new IllegalArgumentException("Unknown component for date: " + component);
418 }
419 }
420
421 private class GDateComparable implements Comparable {
422
423 /*@NotNull*/
424 public GDateValue asGDateValue() {
425 return GDateValue.this;
426 }
427
428 public int compareTo(/*@NotNull*/ Object o) {
429 if (o instanceof GDateComparable) {
430 if (asGDateValue().getPrimitiveType() != ((GDateComparable) o).asGDateValue().getPrimitiveType()) {
431 return SequenceTool.INDETERMINATE_ORDERING;
432 }
433 DateTimeValue dt0 = GDateValue.this.toDateTime();
434 DateTimeValue dt1 = ((GDateComparable) o).asGDateValue().toDateTime();
435 return dt0.getSchemaComparable().compareTo(dt1.getSchemaComparable());
436 } else {
437 return SequenceTool.INDETERMINATE_ORDERING;
438 }
439 }
440
441 public boolean equals(/*@NotNull*/ Object o) {
442 return compareTo(o) == 0;
443 }
444
445 public int hashCode() {
446 return GDateValue.this.toDateTime().getSchemaComparable().hashCode();
447 }
448 }
449
450 }
451