| 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.expr.sort.AtomicMatchKey; |
| 12 | import net.sf.saxon.expr.sort.CodepointCollator; |
| 13 | import net.sf.saxon.lib.ConversionRules; |
| 14 | import net.sf.saxon.lib.StringCollator; |
| 15 | import net.sf.saxon.trans.NoDynamicContextException; |
| 16 | import net.sf.saxon.trans.XPathException; |
| 17 | import net.sf.saxon.tree.util.FastStringBuffer; |
| 18 | import net.sf.saxon.type.ConversionResult; |
| 19 | import net.sf.saxon.type.ValidationFailure; |
| 20 | |
| 21 | import javax.xml.datatype.XMLGregorianCalendar; |
| 22 | import java.math.BigDecimal; |
| 23 | import java.util.GregorianCalendar; |
| 24 | |
| 25 | |
| 26 | /** |
| 27 | * Abstract superclass for Date, Time, and DateTime. |
| 28 | */ |
| 29 | |
| 30 | public abstract class CalendarValue extends AtomicValue implements AtomicMatchKey { |
| 31 | |
| 32 | // This is a reimplementation that makes no use of the Java Calendar/Date types except for computations. |
| 33 | |
| 34 | private int tzMinutes = NO_TIMEZONE; // timezone offset in minutes: or the special value NO_TIMEZONE |
| 35 | |
| 36 | /** |
| 37 | * The value NO_TIMEZONE is used in a value that has no timezone, and it can be passed as an argument |
| 38 | * to a comparison operation if a value with no timezone is to be matched. |
| 39 | */ |
| 40 | public static final int NO_TIMEZONE = Integer.MIN_VALUE; |
| 41 | |
| 42 | /** |
| 43 | * The value MISSING_TIMEZONE is returned as the value of implicit-timezone() if the context has no |
| 44 | * known value for the implicit timezone, which typically arises when early (compile-time) evaluation |
| 45 | * is attempted. This makes it impossible to compare values with a timezone against values with |
| 46 | * no timezone |
| 47 | */ |
| 48 | |
| 49 | public static final int MISSING_TIMEZONE = Integer.MAX_VALUE; |
| 50 | |
| 51 | /** |
| 52 | * Parse a string to create a CalendarValue whose actual type will depend on the format of the string |
| 53 | * |
| 54 | * @param s a string in the lexical space of one of the date/time types (date, time, dateTime, |
| 55 | * gYearMonth, gYear, gMonth, gMonthDay, or gDay |
| 56 | * @param rules |
| 57 | * @return either a value of the appropriate type, or a ValidationFailure if the format is invalid |
| 58 | */ |
| 59 | |
| 60 | public static ConversionResult makeCalendarValue(CharSequence s, ConversionRules rules) { |
| 61 | ConversionResult cr = DateTimeValue.makeDateTimeValue(s, rules); |
| 62 | ConversionResult firstError = cr; |
| 63 | if (cr instanceof ValidationFailure) { |
| 64 | cr = DateValue.makeDateValue(s, rules); |
| 65 | } |
| 66 | if (cr instanceof ValidationFailure) { |
| 67 | cr = TimeValue.makeTimeValue(s); |
| 68 | } |
| 69 | if (cr instanceof ValidationFailure) { |
| 70 | cr = GYearValue.makeGYearValue(s, rules); |
| 71 | } |
| 72 | if (cr instanceof ValidationFailure) { |
| 73 | cr = GYearMonthValue.makeGYearMonthValue(s, rules); |
| 74 | } |
| 75 | if (cr instanceof ValidationFailure) { |
| 76 | cr = GMonthValue.makeGMonthValue(s); |
| 77 | } |
| 78 | if (cr instanceof ValidationFailure) { |
| 79 | cr = GMonthDayValue.makeGMonthDayValue(s); |
| 80 | } |
| 81 | if (cr instanceof ValidationFailure) { |
| 82 | cr = GDayValue.makeGDayValue(s); |
| 83 | } |
| 84 | if (cr instanceof ValidationFailure) { |
| 85 | return firstError; |
| 86 | } |
| 87 | return cr; |
| 88 | } |
| 89 | |
| 90 | /** |
| 91 | * Determine whether this value includes a timezone |
| 92 | * |
| 93 | * @return true if there is a timezone in the value, false if not |
| 94 | */ |
| 95 | |
| 96 | public final boolean hasTimezone() { |
| 97 | return tzMinutes != NO_TIMEZONE; |
| 98 | } |
| 99 | |
| 100 | /** |
| 101 | * Modify the timezone value held in this object. This must be done only while the value is being |
| 102 | * constructed. |
| 103 | * |
| 104 | * @param minutes The timezone offset from GMT in minutes, positive or negative; or the special |
| 105 | * value NO_TIMEZONE indicating that the value is not in a timezone (this is the default if this |
| 106 | * method is not called) |
| 107 | */ |
| 108 | |
| 109 | public final void setTimezoneInMinutes(int minutes) { |
| 110 | tzMinutes = minutes; |
| 111 | } |
| 112 | |
| 113 | /** |
| 114 | * Convert the value to a DateTime, retaining all the components that are actually present, and |
| 115 | * substituting conventional values for components that are missing |
| 116 | * |
| 117 | * @return the equivalent DateTimeValue |
| 118 | */ |
| 119 | |
| 120 | public abstract DateTimeValue toDateTime(); |
| 121 | |
| 122 | /** |
| 123 | * Get the timezone value held in this object. |
| 124 | * |
| 125 | * @return The timezone offset from GMT in minutes, positive or negative; or the special |
| 126 | * value NO_TIMEZONE indicating that the value is not in a timezone |
| 127 | */ |
| 128 | |
| 129 | public final int getTimezoneInMinutes() { |
| 130 | return tzMinutes; |
| 131 | } |
| 132 | |
| 133 | /** |
| 134 | * Get a Java Calendar object that represents this date/time value. The Calendar |
| 135 | * object will be newly created for the purpose. This will respect the timezone |
| 136 | * if there is one (provided the timezone is within the range supported by the {@code GregorianCalendar} |
| 137 | * class, which in practice means that it is not -14:00). If there is no timezone or if |
| 138 | * the timezone is out of range, the result will be in GMT. |
| 139 | * |
| 140 | * @return A Calendar object representing the date and time. Note that Java can only |
| 141 | * represent the time to millisecond precision. |
| 142 | */ |
| 143 | |
| 144 | public abstract GregorianCalendar getCalendar(); |
| 145 | |
| 146 | /** |
| 147 | * Get an XMLGregorianCalendar object that represents this date/time value The object |
| 148 | * will be newly created for the purpose |
| 149 | * @return an XMLGregorianCalendar object representing the data and time; specifically, |
| 150 | * the components of the date and time that are actually present in this value |
| 151 | */ |
| 152 | |
| 153 | public XMLGregorianCalendar getXMLGregorianCalendar() { |
| 154 | return new SaxonXMLGregorianCalendar(this); |
| 155 | } |
| 156 | |
| 157 | /** |
| 158 | * Add a duration to this date/time value |
| 159 | * |
| 160 | * @param duration the duration to be added (which might be negative) |
| 161 | * @return a new date/time value representing the result of adding the duration. The original |
| 162 | * object is not modified. |
| 163 | * @throws XPathException |
| 164 | */ |
| 165 | |
| 166 | public abstract CalendarValue add(DurationValue duration) throws XPathException; |
| 167 | |
| 168 | /** |
| 169 | * Determine the difference between two points in time, as a duration |
| 170 | * |
| 171 | * @param other the other point in time |
| 172 | * @param context the dynamic context, used to obtain timezone information. May be set to null |
| 173 | * only if both values contain an explicit timezone, or if neither does so. |
| 174 | * @return the duration as an xs:dayTimeDuration |
| 175 | * @throws net.sf.saxon.trans.XPathException |
| 176 | * for example if one value is a date and the other is a time |
| 177 | */ |
| 178 | |
| 179 | public DayTimeDurationValue subtract(/*@NotNull*/ CalendarValue other, /*@Nullable*/ XPathContext context) throws XPathException { |
| 180 | DateTimeValue dt1 = toDateTime(); |
| 181 | DateTimeValue dt2 = other.toDateTime(); |
| 182 | if (dt1.getTimezoneInMinutes() != dt2.getTimezoneInMinutes()) { |
| 183 | int tz = CalendarValue.NO_TIMEZONE; |
| 184 | if (context == null || (tz = context.getImplicitTimezone()) == CalendarValue.MISSING_TIMEZONE) { |
| 185 | throw new NoDynamicContextException("Implicit timezone required"); |
| 186 | } |
| 187 | dt1 = dt1.adjustToUTC(tz); |
| 188 | dt2 = dt2.adjustToUTC(tz); |
| 189 | } |
| 190 | BigDecimal d1 = dt1.toJulianInstant(); |
| 191 | BigDecimal d2 = dt2.toJulianInstant(); |
| 192 | BigDecimal difference = d1.subtract(d2); |
| 193 | return DayTimeDurationValue.fromSeconds(difference); |
| 194 | } |
| 195 | |
| 196 | /** |
| 197 | * Return a date, time, or dateTime with the same localized value, but |
| 198 | * without the timezone component |
| 199 | * |
| 200 | * @return the result of removing the timezone |
| 201 | */ |
| 202 | |
| 203 | /*@NotNull*/ |
| 204 | public final CalendarValue removeTimezone() { |
| 205 | CalendarValue c = (CalendarValue) copyAsSubType(typeLabel); |
| 206 | c.tzMinutes = NO_TIMEZONE; |
| 207 | return c; |
| 208 | } |
| 209 | |
| 210 | /** |
| 211 | * Return a new date, time, or dateTime with the same normalized value, but |
| 212 | * in a different timezone |
| 213 | * |
| 214 | * @param tz the new timezone offset from UTC, in minutes |
| 215 | * @return the date/time in the new timezone |
| 216 | */ |
| 217 | |
| 218 | public abstract CalendarValue adjustTimezone(int tz); |
| 219 | |
| 220 | /** |
| 221 | * Return a new date, time, or dateTime with the same normalized value, but |
| 222 | * in a different timezone, specified as a dayTimeDuration |
| 223 | * |
| 224 | * @param tz the new timezone, in minutes |
| 225 | * @return the date/time in the new timezone |
| 226 | */ |
| 227 | |
| 228 | public final CalendarValue adjustTimezone(/*@NotNull*/ DayTimeDurationValue tz) throws XPathException { |
| 229 | long microseconds = tz.getLengthInMicroseconds(); |
| 230 | if (microseconds % 60000000 != 0) { |
| 231 | XPathException err = new XPathException("Timezone is not an integral number of minutes"); |
| 232 | err.setErrorCode("FODT0003"); |
| 233 | throw err; |
| 234 | } |
| 235 | int tzminutes = (int) (microseconds / 60000000); |
| 236 | if (Math.abs(tzminutes) > 14 * 60) { |
| 237 | XPathException err = new XPathException("Timezone out of range (-14:00 to +14:00)"); |
| 238 | err.setErrorCode("FODT0003"); |
| 239 | throw err; |
| 240 | } |
| 241 | return adjustTimezone(tzminutes); |
| 242 | } |
| 243 | |
| 244 | |
| 245 | /** |
| 246 | * Get an object value that implements the XPath equality and ordering comparison semantics for this value. |
| 247 | * If the ordered parameter is set to true, the result will be a Comparable and will support a compareTo() |
| 248 | * method with the semantics of the XPath lt/gt operator, provided that the other operand is also obtained |
| 249 | * using the getXPathComparable() method. In all cases the result will support equals() and hashCode() methods |
| 250 | * that support the semantics of the XPath eq operator, again provided that the other operand is also obtained |
| 251 | * using the getXPathComparable() method. A context argument is supplied for use in cases where the comparison |
| 252 | * semantics are context-sensitive, for example where they depend on the implicit timezone or the default |
| 253 | * collation. |
| 254 | * |
| 255 | * @param ordered true if an ordered comparison is required. In this case the result is null if the |
| 256 | * type is unordered; in other cases the returned value will be a Comparable. |
| 257 | * @param collator collation used for strings |
| 258 | * @param implicitTimezone the XPath dynamic evaluation context, used in cases where the comparison is context |
| 259 | */ |
| 260 | |
| 261 | /*@Nullable*/ |
| 262 | public AtomicMatchKey getXPathComparable(boolean ordered, StringCollator collator, int implicitTimezone) |
| 263 | throws NoDynamicContextException { |
| 264 | if (ordered && !(this instanceof Comparable)) { |
| 265 | return null; |
| 266 | } |
| 267 | if (hasTimezone()) { |
| 268 | return this; |
| 269 | } |
| 270 | if (implicitTimezone == MISSING_TIMEZONE) { |
| 271 | throw new NoDynamicContextException("Unknown implicit timezone"); |
| 272 | } |
| 273 | return hasTimezone() ? this : adjustTimezone(implicitTimezone); |
| 274 | } |
| 275 | |
| 276 | /** |
| 277 | * Method retained only because it is used in a test case |
| 278 | */ |
| 279 | public AtomicMatchKey getComparisonKey(XPathContext context) { |
| 280 | try { |
| 281 | return getXPathComparable(false, CodepointCollator.getInstance(), context.getImplicitTimezone()); |
| 282 | } catch (NoDynamicContextException e) { |
| 283 | return null; |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | /** |
| 288 | * Get a value whose equals() method follows the "same key" rules for comparing the keys of a map. |
| 289 | * |
| 290 | * @return a value with the property that the equals() and hashCode() methods follow the rules for comparing |
| 291 | * keys in maps. |
| 292 | */ |
| 293 | @Override |
| 294 | public AtomicMatchKey asMapKey() { |
| 295 | return new CalendarValueMapKey(); |
| 296 | } |
| 297 | |
| 298 | /** |
| 299 | * Compare this value to another value of the same type, using the supplied implicit timezone if required. |
| 300 | * |
| 301 | * @param other the other value to be compared |
| 302 | * @param implicitTimezone the implicit timezone as an offset in minutes |
| 303 | * @return the comparison result |
| 304 | * @throws NoDynamicContextException if the result depends on the implicit timezone and |
| 305 | * the supplied timezone is {@link CalendarValue#MISSING_TIMEZONE} |
| 306 | */ |
| 307 | |
| 308 | public abstract int compareTo(CalendarValue other, int implicitTimezone) throws NoDynamicContextException; |
| 309 | |
| 310 | public boolean isIdentical(/*@NotNull*/ AtomicValue v) { |
| 311 | return super.isIdentical(v) && tzMinutes == ((CalendarValue) v).tzMinutes; |
| 312 | } |
| 313 | |
| 314 | /** |
| 315 | * Get a hashCode that offers the guarantee that if A.isIdentical(B), then A.identityHashCode() == B.identityHashCode() |
| 316 | * |
| 317 | * @return a hashCode suitable for use when testing for identity. |
| 318 | */ |
| 319 | @Override |
| 320 | public int identityHashCode() { |
| 321 | return hashCode() ^ tzMinutes; |
| 322 | } |
| 323 | |
| 324 | /** |
| 325 | * Add a string representation of the timezone, typically |
| 326 | * formatted as "Z" or "+03:00" or "-10:00", to a supplied |
| 327 | * string buffer |
| 328 | * |
| 329 | * @param sb The StringBuffer that will be updated with the resulting string |
| 330 | * representation |
| 331 | */ |
| 332 | |
| 333 | public final void appendTimezone(/*@NotNull*/ FastStringBuffer sb) { |
| 334 | if (hasTimezone()) { |
| 335 | appendTimezone(getTimezoneInMinutes(), sb); |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | /** |
| 340 | * Format a timezone and append it to a buffer |
| 341 | * |
| 342 | * @param tz the timezone |
| 343 | * @param sb the buffer |
| 344 | */ |
| 345 | |
| 346 | public static void appendTimezone(int tz, /*@NotNull*/ FastStringBuffer sb) { |
| 347 | if (tz == 0) { |
| 348 | sb.append("Z"); |
| 349 | } else { |
| 350 | sb.append(tz > 0 ? "+" : "-"); |
| 351 | tz = Math.abs(tz); |
| 352 | appendTwoDigits(sb, tz / 60); |
| 353 | sb.append(':'); |
| 354 | appendTwoDigits(sb, tz % 60); |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | /** |
| 359 | * Append an integer, formatted with leading zeros to a fixed size, to a string buffer |
| 360 | * |
| 361 | * @param sb the string buffer |
| 362 | * @param value the integer to be formatted |
| 363 | * @param size the number of digits required (max 9) |
| 364 | */ |
| 365 | |
| 366 | static void appendString(/*@NotNull*/ FastStringBuffer sb, int value, int size) { |
| 367 | String s = "000000000" + value; |
| 368 | sb.append(s.substring(s.length() - size)); |
| 369 | } |
| 370 | |
| 371 | /** |
| 372 | * Append an integer, formatted as two digits, to a string buffer |
| 373 | * |
| 374 | * @param sb the string buffer |
| 375 | * @param value the integer to be formatted (must be in the range 0..99 |
| 376 | */ |
| 377 | |
| 378 | static void appendTwoDigits(/*@NotNull*/ FastStringBuffer sb, int value) { |
| 379 | sb.append((char) (value / 10 + '0')); |
| 380 | sb.append((char) (value % 10 + '0')); |
| 381 | } |
| 382 | |
| 383 | private class CalendarValueMapKey implements AtomicMatchKey { |
| 384 | /** |
| 385 | * Get an atomic value that encapsulates this match key. Needed to support the collation-key() function. |
| 386 | * |
| 387 | * @return an atomic value that encapsulates this match key |
| 388 | */ |
| 389 | public CalendarValue asAtomic() { |
| 390 | return CalendarValue.this; |
| 391 | } |
| 392 | |
| 393 | @Override |
| 394 | public boolean equals(Object obj) { |
| 395 | if (obj instanceof CalendarValueMapKey) { |
| 396 | CalendarValue a = CalendarValue.this; |
| 397 | CalendarValue b = ((CalendarValueMapKey)obj).asAtomic(); |
| 398 | if (a.hasTimezone() == b.hasTimezone()) { |
| 399 | if (a.hasTimezone()) { |
| 400 | return a.adjustTimezone(b.tzMinutes).isIdentical(b); |
| 401 | } else { |
| 402 | return a.isIdentical(b); |
| 403 | } |
| 404 | } else { |
| 405 | return false; |
| 406 | } |
| 407 | } else { |
| 408 | return false; |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | @Override |
| 413 | public int hashCode() { |
| 414 | return asAtomic().hashCode(); |
| 415 | } |
| 416 | } |
| 417 | } |
| 418 |