Debian Codegraph @

net/sf/saxon/functions/FormatDate.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.functions;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.expr.Callable;
12 import net.sf.saxon.expr.XPathContext;
13 import net.sf.saxon.expr.number.*;
14 import net.sf.saxon.lib.Numberer;
15 import net.sf.saxon.om.Sequence;
16 import net.sf.saxon.om.StructuredQName;
17 import net.sf.saxon.om.ZeroOrOne;
18 import net.sf.saxon.regex.charclass.Categories;
19 import net.sf.saxon.regex.UnicodeString;
20 import net.sf.saxon.trans.Err;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.tree.util.FastStringBuffer;
23 import net.sf.saxon.value.*;
24
25 import java.util.Arrays;
26 import java.util.TimeZone;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29
30 /**
31 * Implement the format-date(), format-time(), and format-dateTime() functions
32 * in XSLT 2.0 and XQuery 1.1.
33 */
34
35 public class FormatDate extends SystemFunction implements Callable {
36
37 static final String[] knownCalendars = {"AD", "AH", "AME", "AM", "AP", "AS", "BE", "CB", "CE", "CL", "CS", "EE", "FE", "ISO", "JE",
38 "KE", "KY", "ME", "MS", "NS", "OS", "RS", "SE", "SH", "SS", "TE", "VE", "VS"};
39
40 private CharSequence adjustCalendar(StringValue calendarVal, CharSequence result, XPathContext context) throws XPathException {
41 StructuredQName cal;
42 try {
43 String c = calendarVal.getStringValue();
44 cal = StructuredQName.fromLexicalQName(c, false, true, getRetainedStaticContext());
45 } catch (XPathException e) {
46 XPathException err = new XPathException("Invalid calendar name. " + e.getMessage());
47 err.setErrorCode("FOFD1340");
48 err.setXPathContext(context);
49 throw err;
50 }
51
52 if (cal.hasURI("")) {
53 String calLocal = cal.getLocalPart();
54 if (calLocal.equals("AD") || calLocal.equals("ISO")) {
55 // no action
56 } else if (Arrays.binarySearch(knownCalendars, calLocal) >= 0) {
57 result = "[Calendar: AD]" + result;
58 } else {
59 XPathException err = new XPathException("Unknown no-namespace calendar: " + calLocal);
60 err.setErrorCode("FOFD1340");
61 err.setXPathContext(context);
62 throw err;
63 }
64 } else {
65 result = "[Calendar: AD]" + result;
66 }
67 return result;
68 }
69
70 /**
71 * This method analyzes the formatting picture and delegates the work of formatting
72 * individual parts of the date.
73 *
74 * @param value the value to be formatted
75 * @param format the supplied format picture
76 * @param language the chosen language
77 * @param place the chosen country
78 * @param context the XPath dynamic evaluation context
79 * @return the formatted date/time
80 * @throws XPathException if a dynamic error occurs
81 */
82
83 private static CharSequence formatDate(CalendarValue value, String format, String language, String place, XPathContext context)
84 throws XPathException {
85
86 Configuration config = context.getConfiguration();
87
88 boolean languageDefaulted = language == null;
89 if (language == null) {
90 language = config.getDefaultLanguage();
91 }
92 if (place == null) {
93 place = config.getDefaultCountry();
94 }
95
96 // if the value has a timezone and the place is a timezone name, the value is adjusted to that timezone
97 if (value.hasTimezone() && place.contains("/")) {
98 TimeZone tz = TimeZone.getTimeZone(place);
99 if (tz != null) {
100 int milliOffset = tz.getOffset(value.toDateTime().getCalendar().getTime().getTime());
101 value = value.adjustTimezone(milliOffset / 60000);
102 }
103 }
104
105 Numberer numberer = config.makeNumberer(language, place);
106 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C64);
107 if (numberer.getClass() == Numberer_en.class && !"en".equals(language) && !languageDefaulted) {
108 sb.append("[Language: en]");
109 }
110 if (numberer.defaultedLocale() != null) {
111 sb.append("[Language: " + numberer.defaultedLocale().getLanguage() + "]");
112 }
113
114
115 int i = 0;
116 while (true) {
117 while (i < format.length() && format.charAt(i) != '[') {
118 sb.append(format.charAt(i));
119 if (format.charAt(i) == ']') {
120 i++;
121 if (i == format.length() || format.charAt(i) != ']') {
122 XPathException e = new XPathException("Closing ']' in date picture must be written as ']]'");
123 e.setErrorCode("FOFD1340");
124 e.setXPathContext(context);
125 throw e;
126 }
127 }
128 i++;
129 }
130 if (i == format.length()) {
131 break;
132 }
133 // look for '[['
134 i++;
135 if (i < format.length() && format.charAt(i) == '[') {
136 sb.append('[');
137 i++;
138 } else {
139 int close = i < format.length() ? format.indexOf("]", i) : -1;
140 if (close == -1) {
141 XPathException e = new XPathException("Date format contains a '[' with no matching ']'");
142 e.setErrorCode("FOFD1340");
143 e.setXPathContext(context);
144 throw e;
145 }
146 String componentFormat = format.substring(i, close);
147 sb.append(formatComponent(value, Whitespace.removeAllWhitespace(componentFormat),
148 numberer, place, context));
149 i = close + 1;
150 }
151 }
152 return sb;
153 }
154
155 private static Pattern componentPattern =
156 Pattern.compile("([YMDdWwFHhmsfZzPCE])\\s*(.*)");
157
158 private static CharSequence formatComponent(CalendarValue value, CharSequence specifier,
159 Numberer numberer, String country, XPathContext context)
160 throws XPathException {
161 boolean ignoreDate = value instanceof TimeValue;
162 boolean ignoreTime = value instanceof DateValue;
163 DateTimeValue dtvalue = value.toDateTime();
164
165 Matcher matcher = componentPattern.matcher(specifier);
166 if (!matcher.matches()) {
167 XPathException error = new XPathException("Unrecognized date/time component [" + specifier + ']');
168 error.setErrorCode("FOFD1340");
169 error.setXPathContext(context);
170 throw error;
171 }
172 String component = matcher.group(1);
173 String format = matcher.group(2);
174 if (format == null) {
175 format = "";
176 }
177 boolean defaultFormat = false;
178 if ("".equals(format) || format.startsWith(",")) {
179 defaultFormat = true;
180 switch (component.charAt(0)) {
181 case 'F':
182 format = "Nn" + format;
183 break;
184 case 'P':
185 format = 'n' + format;
186 break;
187 case 'C':
188 case 'E':
189 format = 'N' + format;
190 break;
191 case 'm':
192 case 's':
193 format = "01" + format;
194 break;
195 case 'z':
196 case 'Z':
197 //format = "00:00" + format;
198 break;
199 default:
200 format = '1' + format;
201 }
202 }
203
204 switch (component.charAt(0)) {
205 case 'Y': // year
206 if (ignoreDate) {
207 XPathException error = new XPathException("In format-time(): an xs:time value does not contain a year component");
208 error.setErrorCode("FOFD1350");
209 error.setXPathContext(context);
210 throw error;
211 } else {
212 int year = dtvalue.getYear();
213 if (year < 0) {
214 year = 0 - year;
215 }
216 return formatNumber(component, year, format, defaultFormat, numberer, context);
217 }
218 case 'M': // month
219 if (ignoreDate) {
220 XPathException error = new XPathException("In format-time(): an xs:time value does not contain a month component");
221 error.setErrorCode("FOFD1350");
222 error.setXPathContext(context);
223 throw error;
224 } else {
225 int month = dtvalue.getMonth();
226 return formatNumber(component, month, format, defaultFormat, numberer, context);
227 }
228 case 'D': // day in month
229 if (ignoreDate) {
230 XPathException error = new XPathException("In format-time(): an xs:time value does not contain a day component");
231 error.setErrorCode("FOFD1350");
232 error.setXPathContext(context);
233 throw error;
234 } else {
235 int day = dtvalue.getDay();
236 return formatNumber(component, day, format, defaultFormat, numberer, context);
237 }
238 case 'd': // day in year
239 if (ignoreDate) {
240 XPathException error = new XPathException("In format-time(): an xs:time value does not contain a day component");
241 error.setErrorCode("FOFD1350");
242 error.setXPathContext(context);
243 throw error;
244 } else {
245 int day = DateValue.getDayWithinYear(dtvalue.getYear(), dtvalue.getMonth(), dtvalue.getDay());
246 return formatNumber(component, day, format, defaultFormat, numberer, context);
247 }
248 case 'W': // week of year
249 if (ignoreDate) {
250 XPathException error = new XPathException("In format-time(): cannot obtain the week number from an xs:time value");
251 error.setErrorCode("FOFD1350");
252 error.setXPathContext(context);
253 throw error;
254 } else {
255 int week = DateValue.getWeekNumber(dtvalue.getYear(), dtvalue.getMonth(), dtvalue.getDay());
256 return formatNumber(component, week, format, defaultFormat, numberer, context);
257 }
258 case 'w': // week in month
259 if (ignoreDate) {
260 XPathException error = new XPathException("In format-time(): cannot obtain the week number from an xs:time value");
261 error.setErrorCode("FOFD1350");
262 error.setXPathContext(context);
263 throw error;
264 } else {
265 int week = DateValue.getWeekNumberWithinMonth(dtvalue.getYear(), dtvalue.getMonth(), dtvalue.getDay());
266 return formatNumber(component, week, format, defaultFormat, numberer, context);
267 }
268 case 'H': // hour in day
269 if (ignoreTime) {
270 XPathException error = new XPathException("In format-date(): an xs:date value does not contain an hour component");
271 error.setErrorCode("FOFD1350");
272 error.setXPathContext(context);
273 throw error;
274 } else {
275 Int64Value hour = (Int64Value) value.getComponent(AccessorFn.Component.HOURS);
276 assert hour != null;
277 return formatNumber(component, (int) hour.longValue(), format, defaultFormat, numberer, context);
278 }
279 case 'h': // hour in half-day (12 hour clock)
280 if (ignoreTime) {
281 XPathException error = new XPathException("In format-date(): an xs:date value does not contain an hour component");
282 error.setErrorCode("FOFD1350");
283 error.setXPathContext(context);
284 throw error;
285 } else {
286 Int64Value hour = (Int64Value) value.getComponent(AccessorFn.Component.HOURS);
287 assert hour != null;
288 int hr = (int) hour.longValue();
289 if (hr > 12) {
290 hr = hr - 12;
291 }
292 if (hr == 0) {
293 hr = 12;
294 }
295 return formatNumber(component, hr, format, defaultFormat, numberer, context);
296 }
297 case 'm': // minutes
298 if (ignoreTime) {
299 XPathException error = new XPathException("In format-date(): an xs:date value does not contain a minutes component");
300 error.setErrorCode("FOFD1350");
301 error.setXPathContext(context);
302 throw error;
303 } else {
304 Int64Value minutes = (Int64Value) value.getComponent(AccessorFn.Component.MINUTES);
305 assert minutes != null;
306 return formatNumber(component, (int) minutes.longValue(), format, defaultFormat, numberer, context);
307 }
308 case 's': // seconds
309 if (ignoreTime) {
310 XPathException error = new XPathException("In format-date(): an xs:date value does not contain a seconds component");
311 error.setErrorCode("FOFD1350");
312 error.setXPathContext(context);
313 throw error;
314 } else {
315 IntegerValue seconds = (IntegerValue) value.getComponent(AccessorFn.Component.WHOLE_SECONDS);
316 assert seconds != null;
317 return formatNumber(component, (int) seconds.longValue(), format, defaultFormat, numberer, context);
318 }
319 case 'f': // fractional seconds
320 // ignore the format
321 if (ignoreTime) {
322 XPathException error = new XPathException("In format-date(): an xs:date value does not contain a fractional seconds component");
323 error.setErrorCode("FOFD1350");
324 error.setXPathContext(context);
325 throw error;
326 } else {
327 Int64Value micros = (Int64Value) value.getComponent(AccessorFn.Component.MICROSECONDS);
328 assert micros != null;
329 return formatNumber(component, (int)micros.longValue(), format, defaultFormat, numberer, context);
330 }
331 case 'z':
332 case 'Z':
333 DateTimeValue dtv;
334 if (value instanceof TimeValue) {
335 // See bug 3761. We need to pad the time with a date. 1972-12-31 or 1970-01-01 won't do because
336 // timezones were different then (Alaska changed in 1983, for example). Today's date isn't ideal
337 // because it's better to choose a date that isn't in summer time. We'll choose the first of
338 // January in the current year, unless that's in summer time in the country in question, in which
339 // case we'll choose first of July.
340 DateTimeValue now = DateTimeValue.getCurrentDateTime(context);
341 int year = now.getYear();
342 int tzoffset = value.getTimezoneInMinutes();
343 DateTimeValue baseDate =
344 new DateTimeValue(year, (byte)1, (byte)1, (byte)0, (byte)0, (byte)0, 0, tzoffset, false);
345 Boolean b = NamedTimeZone.inSummerTime(baseDate, country);
346 if (b != null && b) {
347 baseDate = new DateTimeValue(year, (byte) 7, (byte) 1, (byte) 0, (byte) 0, (byte) 0, 0, tzoffset, false);
348 }
349 dtv = DateTimeValue.makeDateTimeValue(baseDate.toDateValue(), (TimeValue)value);
350 } else {
351 dtv = value.toDateTime();
352 }
353 return formatTimeZone(dtv, component.charAt(0), format, country);
354
355 case 'F': // day of week
356 if (ignoreDate) {
357 XPathException error = new XPathException("In format-time(): an xs:time value does not contain day-of-week component");
358 error.setErrorCode("FOFD1350");
359 error.setXPathContext(context);
360 throw error;
361 } else {
362 int day = DateValue.getDayOfWeek(dtvalue.getYear(), dtvalue.getMonth(), dtvalue.getDay());
363 return formatNumber(component, day, format, defaultFormat, numberer, context);
364 }
365 case 'P': // am/pm marker
366 if (ignoreTime) {
367 XPathException error = new XPathException("In format-date(): an xs:date value does not contain an am/pm component");
368 error.setErrorCode("FOFD1350");
369 error.setXPathContext(context);
370 throw error;
371 } else {
372 int minuteOfDay = dtvalue.getHour() * 60 + dtvalue.getMinute();
373 return formatNumber(component, minuteOfDay, format, defaultFormat, numberer, context);
374 }
375 case 'C': // calendar
376 return numberer.getCalendarName("AD");
377 case 'E': // era
378 if (ignoreDate) {
379 XPathException error = new XPathException("In format-time(): an xs:time value does not contain an AD/BC component");
380 error.setErrorCode("FOFD1350");
381 error.setXPathContext(context);
382 throw error;
383 } else {
384 int year = dtvalue.getYear();
385 return numberer.getEraName(year);
386 }
387 default:
388 XPathException e = new XPathException("Unknown format-date/time component specifier '" + format.charAt(0) + '\'');
389 e.setErrorCode("FOFD1340");
390 e.setXPathContext(context);
391 throw e;
392 }
393 }
394
395 private static Pattern formatPattern =
396 //Pattern.compile("([^ot,]*?)([ot]?)(,.*)?"); // GNU Classpath has problems with this one
397 Pattern.compile("([^,]*)(,.*)?"); // Note, the group numbers are different from above
398
399 private static Pattern widthPattern =
400 Pattern.compile(",(\\*|[0-9]+)(\\-(\\*|[0-9]+))?");
401
402 private static Pattern alphanumericPattern =
403 Pattern.compile("([A-Za-z0-9]|\\p{L}|\\p{N})*");
404 // the first term is redundant, but GNU Classpath can't cope with the others...
405
406 private static Pattern digitsPattern =
407 Pattern.compile("\\p{Nd}+");
408
409 private static Pattern digitsOrOptionalDigitsPattern =
410 Pattern.compile("[#\\p{Nd}]+");
411
412
413 private static Pattern fractionalDigitsPattern =
414 Pattern.compile("\\p{Nd}+#*");
415
416 private static CharSequence formatNumber(String component, int value,
417 String format, boolean defaultFormat, Numberer numberer, XPathContext context)
418 throws XPathException {
419 int comma = format.lastIndexOf(',');
420 String widths = "";
421 if (comma >= 0) {
422 widths = format.substring(comma);
423 format = format.substring(0, comma);
424 }
425 String primary = format;
426 String modifier = null;
427 if (primary.endsWith("t")) {
428 primary = primary.substring(0, primary.length() - 1);
429 modifier = "t";
430 } else if (primary.endsWith("o")) {
431 primary = primary.substring(0, primary.length() - 1);
432 modifier = "o";
433 }
434 String letterValue = "t".equals(modifier) ? "traditional" : null;
435 String ordinal = "o".equals(modifier) ? numberer.getOrdinalSuffixForDateTime(component) : null;
436
437 int min = 1;
438 int max = Integer.MAX_VALUE;
439
440 if (digitsPattern.matcher(primary).matches()) {
441 int len = StringValue.getStringLength(primary);
442 if (len > 1) {
443 // "A format token containing leading zeroes, such as 001, sets the minimum and maximum width..."
444 // We interpret this literally: a format token of "1" does not set a maximum, because it would
445 // cause the year 2006 to be formatted as "6".
446 min = len;
447 max = len;
448 }
449 }
450 if ("Y".equals(component)) {
451 min = max = 0;
452 if (!widths.isEmpty()) {
453 max = getWidths(widths)[1];
454 } else if (digitsPattern.matcher(primary).find()) {
455 UnicodeString uPrimary = UnicodeString.makeUnicodeString(primary);
456 for (int i = 0; i < uPrimary.uLength(); i++) {
457 int c = uPrimary.uCharAt(i);
458 if (c == '#') {
459 max++;
460 } else if ((c >= '0' && c <= '9') || Categories.ESCAPE_d.test(c)) {
461 min++;
462 max++;
463 }
464 }
465 }
466 if (max <= 1) {
467 max = Integer.MAX_VALUE;
468 }
469 if (max < 4 || (max < Integer.MAX_VALUE && value > 9999)) {
470 value = value % (int) Math.pow(10, max);
471 }
472 }
473 if (primary.equals("I") || primary.equals("i")) {
474 int[] range = getWidths(widths);
475 min = range[0];
476 //max = Integer.MAX_VALUE;
477
478 String roman = numberer.format(value, UnicodeString.makeUnicodeString(primary), null, letterValue, ordinal);
479 StringBuilder s = new StringBuilder(roman);
480 int len = StringValue.getStringLength(roman);
481 while (len < min) {
482 s.append(' ');
483 len++;
484 }
485 return s.toString();
486 } else if (!widths.isEmpty()) {
487 int[] range = getWidths(widths);
488 min = Math.max(min, range[0]);
489 if (max == Integer.MAX_VALUE) {
490 max = range[1];
491 } else {
492 max = Math.max(max, range[1]);
493 }
494 if (defaultFormat) {
495 // if format was defaulted, the explicit widths override the implicit format
496 if (primary.endsWith("1") && min != primary.length()) {
497 FastStringBuffer sb = new FastStringBuffer(min + 1);
498 for (int i = 1; i < min; i++) {
499 sb.append('0');
500 }
501 sb.append('1');
502 primary = sb.toString();
503 }
504 }
505 }
506
507 if ("P".equals(component)) {
508 // A.M./P.M. can only be formatted as a name
509 if (!("N".equals(primary) || "n".equals(primary) || "Nn".equals(primary))) {
510 primary = "n";
511 }
512 if (max == Integer.MAX_VALUE) {
513 // if no max specified, use 4. An explicit greater value allows use of "noon" and "midnight"
514 max = 4;
515 }
516 } else if ("Y".equals(component)) {
517 if (max < Integer.MAX_VALUE) {
518 value = value % (int) Math.pow(10, max);
519 }
520 } else if ("f".equals(component)) {
521 // value is supplied as integer number of microseconds
522 UnicodeString uFormat = UnicodeString.makeUnicodeString(format);
523 // If there is no Unicode digit in the pattern, output is implementation defined, so do what comes easily
524 if (!digitsPattern.matcher(primary).find()) {
525 return formatNumber(component, value, "1", defaultFormat, numberer, context);
526 }
527 // if there are grouping separators, handle as a reverse integer as described in the 3.1 spec
528 if (!digitsOrOptionalDigitsPattern.matcher(primary).matches()) {
529 UnicodeString reverseFormat = reverse(uFormat);
530 UnicodeString reverseValue = reverse(UnicodeString.makeUnicodeString("" + value));
531 CharSequence reverseResult = formatNumber("s",
532 Integer.parseInt(reverseValue.toString()), reverseFormat.toString(), false, numberer, context);
533 UnicodeString correctedResult = reverse(UnicodeString.makeUnicodeString(reverseResult));
534 if (correctedResult.uLength() > max) {
535 correctedResult = correctedResult.uSubstring(0, max);
536 }
537 return correctedResult.toString();
538 }
539 if (!fractionalDigitsPattern.matcher(primary).matches()) {
540 throw new XPathException("Invalid picture for fractional seconds: " + primary, "FOFD1340");
541 }
542 StringBuilder s;
543 if (value == 0) {
544 s = new StringBuilder("0");
545 } else {
546 s = new StringBuilder(((1000000 + value) + "").substring(1));
547 if (s.length() > max) {
548 // Spec bug 29749 says we should truncate rather than rounding
549 s = new StringBuilder(s.substring(0, max));
550 }
551 }
552 while (s.length() < min) {
553 s.append('0');
554 }
555 while (s.length() > min && s.charAt(s.length() - 1) == '0') {
556 s = new StringBuilder(s.substring(0, s.length() - 1));
557 }
558 // for non standard decimal digit family
559 int zeroDigit = Alphanumeric.getDigitFamily(uFormat.uCharAt(0));
560 if (zeroDigit >= 0 && zeroDigit != '0') {
561 int[] digits = new int[10];
562 for (int z = 0; z <= 9; z++) {
563 digits[z] = zeroDigit + z;
564 }
565 long n = Long.parseLong(s.toString());
566 int requiredLength = s.length();
567 s = new StringBuilder(AbstractNumberer.convertDigitSystem(n, digits, requiredLength).toString());
568 }
569 return s.toString();
570 }
571
572 if ("N".equals(primary) || "n".equals(primary) || "Nn".equals(primary)) {
573 String s = "";
574 if ("M".equals(component)) {
575 s = numberer.monthName(value, min, max);
576 } else if ("F".equals(component)) {
577 s = numberer.dayName(value, min, max);
578 } else if ("P".equals(component)) {
579 s = numberer.halfDayName(value, min, max);
580 } else {
581 primary = "1";
582 }
583 if ("N".equals(primary)) {
584 return s.toUpperCase();
585 } else if ("n".equals(primary)) {
586 return s.toLowerCase();
587 } else {
588 return s;
589 }
590 }
591
592 // deal with grouping separators, decimal digit family, etc. for numeric values
593 NumericGroupFormatter picGroupFormat;
594 try {
595 picGroupFormat = FormatInteger.getPicSeparators(primary);
596 } catch (XPathException e) {
597 if ("FODF1310".equals(e.getErrorCodeLocalPart())) {
598 e.setErrorCode("FOFD1340");
599 }
600 throw e;
601 }
602 UnicodeString adjustedPicture = picGroupFormat.getAdjustedPicture();
603
604 String s = numberer.format(value, adjustedPicture, picGroupFormat, letterValue, ordinal);
605 int len = StringValue.getStringLength(s);
606 int zeroDigit;
607 if (len < min) {
608 zeroDigit = Alphanumeric.getDigitFamily(adjustedPicture.uCharAt(0));
609 FastStringBuffer fsb = new FastStringBuffer(s);
610 while (len < min) {
611 fsb.prependWideChar(zeroDigit);
612 len = len + 1;
613 }
614 s = fsb.toString();
615 }
616 return s;
617 }
618
619 private static UnicodeString reverse(UnicodeString in) {
620 int[] out = new int[in.uLength()];
621 for (int i = in.uLength() - 1, j = 0; i >= 0; i--, j++) {
622 out[j] = in.uCharAt(i);
623 }
624 return UnicodeString.makeUnicodeString(out);
625 }
626
627 private static int[] getWidths(String widths) throws XPathException {
628 try {
629 int min = -1;
630 int max = -1;
631
632 if (!"".equals(widths)) {
633 Matcher widthMatcher = widthPattern.matcher(widths);
634 if (widthMatcher.matches()) {
635 String smin = widthMatcher.group(1);
636 if (smin == null || "".equals(smin) || "*".equals(smin)) {
637 min = 1;
638 } else {
639 min = Integer.parseInt(smin);
640 }
641 String smax = widthMatcher.group(3);
642 if (smax == null || "".equals(smax) || "*".equals(smax)) {
643 max = Integer.MAX_VALUE;
644 } else {
645 max = Integer.parseInt(smax);
646 }
647 if (min < 1) {
648 throw new XPathException("Invalid min value in format picture " + Err.wrap(widths, Err.VALUE), "FOFD1340");
649 }
650 if (max < 1 || max < min) {
651 throw new XPathException("Invalid max value in format picture " + Err.wrap(widths, Err.VALUE), "FOFD1340");
652 }
653 } else {
654 throw new XPathException("Unrecognized width specifier in format picture " + Err.wrap(widths, Err.VALUE), "FOFD1340");
655 }
656 }
657
658 if (min > max) {
659 XPathException e = new XPathException("Minimum width in date/time picture exceeds maximum width");
660 e.setErrorCode("FOFD1340");
661 throw e;
662 }
663 int[] result = new int[2];
664 result[0] = min;
665 result[1] = max;
666 return result;
667 } catch (NumberFormatException err) {
668 XPathException e = new XPathException("Invalid integer used as width in date/time picture");
669 e.setErrorCode("FOFD1340");
670 throw e;
671 }
672 }
673
674 private static String formatTimeZone(DateTimeValue value, char component, String format, String country) throws XPathException {
675 int comma = format.lastIndexOf(',');
676 String widthModifier = "";
677 if (comma >= 0) {
678 widthModifier = format.substring(comma);
679 format = format.substring(0, comma);
680 }
681 if (!value.hasTimezone()) {
682 if (format.equals("Z")) {
683 return "J"; // military "local time"
684 } else {
685 return "";
686 }
687 }
688 if (format.isEmpty() && !widthModifier.isEmpty()) {
689 int[] widths = getWidths(widthModifier);
690 int min = widths[0];
691 int max = widths[1];
692 if (min <= 1) {
693 format = max >= 4 ? "0:00" : "0";
694 } else if (min <= 4) {
695 format = max >= 5 ? "00:00" : "00";
696 } else {
697 format = "00:00";
698 }
699 }
700 if (format.isEmpty()) {
701 format = "00:00";
702 }
703 int tz = value.getTimezoneInMinutes();
704 boolean useZforZero = format.endsWith("t");
705 if (useZforZero && tz == 0) {
706 return "Z";
707 }
708 if (useZforZero) {
709 format = format.substring(0, format.length() - 1);
710 }
711 int digits = 0;
712 int separators = 0;
713 int separatorChar = ':';
714 int zeroDigit = -1;
715 int[] expandedFormat = StringValue.expand(format);
716 for (int ch : expandedFormat) {
717 if (Character.isDigit(ch)) {
718 digits++;
719 if (zeroDigit < 0) {
720 zeroDigit = Alphanumeric.getDigitFamily(ch);
721 }
722 } else {
723 separators++;
724 separatorChar = ch;
725 }
726 }
727 int[] buffer = new int[10];
728 int used = 0;
729 if (digits > 0) {
730 // Numeric timezone formatting
731 if (component == 'z') {
732 buffer[0] = 'G';
733 buffer[1] = 'M';
734 buffer[2] = 'T';
735 used = 3;
736 }
737 boolean negative = tz < 0;
738 tz = java.lang.Math.abs(tz);
739 buffer[used++] = negative ? '-' : '+';
740
741 int hour = tz / 60;
742 int minute = tz % 60;
743
744 boolean includeMinutes = minute != 0 || digits >= 3 || separators > 0;
745 boolean includeSep = (minute != 0 && digits <= 2) || (separators > 0 && (minute != 0 || digits >= 3));
746
747 int hourDigits = digits <= 2 ? digits : digits - 2;
748
749 if (hour > 9 || hourDigits >= 2) {
750 buffer[used++] = zeroDigit + hour / 10;
751 }
752 buffer[used++] = (hour % 10) + zeroDigit;
753
754 if (includeSep) {
755 buffer[used++] = separatorChar;
756 }
757 if (includeMinutes) {
758 buffer[used++] = minute / 10 + zeroDigit;
759 buffer[used++] = minute % 10 + zeroDigit;
760 }
761
762 return StringValue.contract(buffer, used).toString();
763 } else if (format.equals("Z")) {
764 // military timezone formatting
765 int hour = tz / 60;
766 int minute = tz % 60;
767 if (hour < -12 || hour > 12 || minute != 0) {
768 return formatTimeZone(value, 'Z', "00:00", country);
769 } else {
770 return Character.toString("YXWVUTSRQPONZABCDEFGHIKLM".charAt(hour + 12));
771 }
772 } else if (format.charAt(0) == 'N' || format.charAt(0) == 'n') {
773 return getNamedTimeZone(value, country, format);
774 } else {
775 return formatTimeZone(value, 'Z', "00:00", country);
776 }
777
778 }
779
780 private static String getNamedTimeZone(DateTimeValue value, String country, String format) throws XPathException {
781
782 int min = 1;
783 int comma = format.indexOf(',');
784 if (comma > 0) {
785 String widths = format.substring(comma);
786 int[] range = getWidths(widths);
787 min = range[0];
788 }
789 if (format.charAt(0) == 'N' || format.charAt(0) == 'n') {
790 if (min <= 5) {
791 String tzname = NamedTimeZone.getTimeZoneNameForDate(value, country);
792 if (format.charAt(0) == 'n') {
793 tzname = tzname.toLowerCase();
794 }
795 return tzname;
796 } else {
797 return NamedTimeZone.getOlsenTimeZoneName(value, country);
798 }
799 }
800 FastStringBuffer sbz = new FastStringBuffer(8);
801 value.appendTimezone(sbz);
802 return sbz.toString();
803 }
804
805
806 public ZeroOrOne<StringValue> call(XPathContext context, Sequence[] arguments) throws XPathException {
807 CalendarValue value = (CalendarValue) arguments[0].head();
808 if (value == null) {
809 return ZeroOrOne.empty();
810 }
811 String format = arguments[1].head().getStringValue();
812
813 StringValue calendarVal = null;
814 StringValue countryVal = null;
815 StringValue languageVal = null;
816 if (getArity() > 2) {
817 languageVal = (StringValue) arguments[2].head();
818 calendarVal = (StringValue) arguments[3].head();
819 countryVal = (StringValue) arguments[4].head();
820 }
821
822 String language = languageVal == null ? null : languageVal.getStringValue();
823 String place = countryVal == null ? null : countryVal.getStringValue();
824 if (place != null && place.contains("/") && value.hasTimezone() && !(value instanceof TimeValue)) {
825 TimeZone zone = NamedTimeZone.getNamedTimeZone(place);
826 if (zone != null) {
827 int offset = zone.getOffset(value.toDateTime().getCalendar().getTimeInMillis());
828 value = value.adjustTimezone(offset / 60000);
829 }
830 }
831 CharSequence result = formatDate(value, format, language, place, context);
832 if (calendarVal != null) {
833 result = adjustCalendar(calendarVal, result, context);
834 }
835 return new ZeroOrOne<>(new StringValue(result));
836 }
837
838 }
839