-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathCLDRConverter.java
More file actions
1569 lines (1408 loc) · 63.3 KB
/
CLDRConverter.java
File metadata and controls
1569 lines (1408 loc) · 63.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package build.tools.cldrconverter;
import build.tools.cldrconverter.BundleGenerator.BundleType;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.*;
import java.time.*;
import java.util.*;
import java.util.ResourceBundle.Control;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
/**
* Converts locale data from "Locale Data Markup Language" format to
* JRE resource bundle format. LDML is the format used by the Common
* Locale Data Repository maintained by the Unicode Consortium.
*/
public class CLDRConverter {
static final String LDML_DTD_SYSTEM_ID = "http://www.unicode.org/cldr/dtd/2.0/ldml.dtd";
static final String SPPL_LDML_DTD_SYSTEM_ID = "http://www.unicode.org/cldr/dtd/2.0/ldmlSupplemental.dtd";
static final String BCP47_LDML_DTD_SYSTEM_ID = "http://www.unicode.org/cldr/dtd/2.0/ldmlBCP47.dtd";
private static String CLDR_BASE;
static String LOCAL_LDML_DTD;
static String LOCAL_SPPL_LDML_DTD;
static String LOCAL_BCP47_LDML_DTD;
private static String SOURCE_FILE_DIR;
private static String SPPL_SOURCE_FILE;
private static String SPPL_META_SOURCE_FILE;
private static String NUMBERING_SOURCE_FILE;
private static String METAZONES_SOURCE_FILE;
private static String LIKELYSUBTAGS_SOURCE_FILE;
private static String TIMEZONE_SOURCE_FILE;
private static String WINZONES_SOURCE_FILE;
private static String PLURALS_SOURCE_FILE;
private static String DAYPERIODRULE_SOURCE_FILE;
private static String COVERAGELEVELS_FILE;
static String DESTINATION_DIR = "build/gensrc";
static final String LOCALE_NAME_PREFIX = "locale.displayname.";
static final String LOCALE_SEPARATOR = LOCALE_NAME_PREFIX + "separator";
static final String LOCALE_KEYTYPE = LOCALE_NAME_PREFIX + "keytype";
static final String LOCALE_KEY_PREFIX = LOCALE_NAME_PREFIX + "key.";
static final String LOCALE_TYPE_PREFIX = LOCALE_NAME_PREFIX + "type.";
static final String LOCALE_TYPE_PREFIX_CA = LOCALE_TYPE_PREFIX + "ca.";
static final String CURRENCY_SYMBOL_PREFIX = "currency.symbol.";
static final String CURRENCY_NAME_PREFIX = "currency.displayname.";
static final String CALENDAR_NAME_PREFIX = "calendarname.";
static final String CALENDAR_FIRSTDAY_PREFIX = "firstDay.";
static final String CALENDAR_MINDAYS_PREFIX = "minDays.";
static final String TIMEZONE_ID_PREFIX = "timezone.id.";
static final String EXEMPLAR_CITY_PREFIX = "timezone.excity.";
static final String ZONE_NAME_PREFIX = "timezone.displayname.";
static final String METAZONE_ID_PREFIX = "metazone.id.";
static final String METAZONE_DSTOFFSET_PREFIX = "metazone.dstoffset.";
static final String PARENT_LOCALE_PREFIX = "parentLocale.";
static final String LIKELY_SCRIPT_PREFIX = "likelyScript.";
static final String META_EMPTY_ZONE_NAME = "EMPTY_ZONE";
static final String[] EMPTY_ZONE = {"", "", "", "", "", ""};
static final String META_ETCUTC_ZONE_NAME = "ETC_UTC";
// constants used for TZDB short names
private static final String NBSP = "\u00A0";
private static final String STD = "std";
private static final String DST = "dst";
private static final String NO_SUBST = "-";
private static SupplementalDataParseHandler handlerSuppl;
private static LikelySubtagsParseHandler handlerLikelySubtags;
private static WinZonesParseHandler handlerWinZones;
static PluralsParseHandler handlerPlurals;
static SupplementalMetadataParseHandler handlerSupplMeta;
static NumberingSystemsParseHandler handlerNumbering;
static MetaZonesParseHandler handlerMetaZones;
static TimeZoneParseHandler handlerTimeZone;
static DayPeriodRuleParseHandler handlerDayPeriodRule;
private static BundleGenerator bundleGenerator;
// java.base module related
static boolean isBaseModule = false;
static final Set<Locale> BASE_LOCALES = new HashSet<>();
// "parentLocales" map
private static final Map<String, SortedSet<String>> parentLocalesMap = new HashMap<>();
static boolean nonlikelyScript;
private static final ResourceBundle.Control defCon =
ResourceBundle.Control.getControl(ResourceBundle.Control.FORMAT_DEFAULT);
// "likelyScript" map
private static final Map<String, SortedSet<String>> likelyScriptMap = new HashMap<>();
private static Set<String> AVAILABLE_TZIDS;
static int copyrightYear;
static String jdkHeaderTemplate;
private static String zoneNameTempFile;
private static String tzDataDir;
private static final Map<String, String> canonicalTZMap = new HashMap<>();
// rules maps
static Map<String, String> pluralRules;
static Map<String, String> dayPeriodRules;
// TZDB maps
private static final Map<String, String> tzdbShortNamesMap = HashMap.newHashMap(512);
private static final Map<String, String> tzdbSubstLetters = HashMap.newHashMap(512);
private static final Map<String, String> tzdbLinks = HashMap.newHashMap(512);
// Map of explicit dst offsets for metazones
// key: time zone ID
// value: explicit dstOffset for the corresponding metazone name
static final Map<String, String> explicitDstOffsets = HashMap.newHashMap(32);
static enum DraftType {
UNCONFIRMED,
PROVISIONAL,
CONTRIBUTED,
APPROVED;
private static final Map<String, DraftType> map = new HashMap<>();
static {
for (DraftType dt : values()) {
map.put(dt.getKeyword(), dt);
}
}
static private DraftType defaultType = CONTRIBUTED;
private final String keyword;
private DraftType() {
keyword = this.name().toLowerCase(Locale.ROOT);
}
static DraftType forKeyword(String keyword) {
return map.get(keyword);
}
static DraftType getDefault() {
return defaultType;
}
static void setDefault(String keyword) {
defaultType = Objects.requireNonNull(forKeyword(keyword));
}
String getKeyword() {
return keyword;
}
}
static boolean USE_UTF8 = false;
private static boolean verbose;
private CLDRConverter() {
// no instantiation
}
@SuppressWarnings("AssignmentToForLoopParameter")
public static void main(String[] args) throws Exception {
if (args.length != 0) {
String currentArg = null;
try {
for (int i = 0; i < args.length; i++) {
currentArg = args[i];
switch (currentArg) {
case "-draft":
String draftDataType = args[++i];
try {
DraftType.setDefault(draftDataType);
} catch (NullPointerException e) {
severe("Error: incorrect draft value: %s%n", draftDataType);
System.exit(1);
}
info("Using the specified data type: %s%n", draftDataType);
break;
case "-base":
// base directory for input files
CLDR_BASE = args[++i];
if (!CLDR_BASE.endsWith("/")) {
CLDR_BASE += "/";
}
break;
case "-baselocales":
// base locales
setupBaseLocales(args[++i]);
break;
case "-basemodule":
// indicates java.base module resource generation
isBaseModule = true;
break;
case "-o":
// output directory
DESTINATION_DIR = args[++i];
break;
case "-utf8":
USE_UTF8 = true;
break;
case "-verbose":
verbose = true;
break;
case "-year":
copyrightYear = Integer.parseInt(args[++i]);
break;
case "-zntempfile":
zoneNameTempFile = args[++i];
break;
case "-tzdatadir":
tzDataDir = args[++i];
break;
case "-jdk-header-template":
jdkHeaderTemplate = Files.readString(Paths.get(args[++i]));
break;
case "-help":
usage();
System.exit(0);
break;
default:
throw new RuntimeException();
}
}
} catch (RuntimeException e) {
severe("unknown or incomplete arg(s): " + currentArg);
usage();
System.exit(1);
}
}
// Set up path names
LOCAL_LDML_DTD = CLDR_BASE + "/dtd/ldml.dtd";
LOCAL_SPPL_LDML_DTD = CLDR_BASE + "/dtd/ldmlSupplemental.dtd";
LOCAL_BCP47_LDML_DTD = CLDR_BASE + "/dtd/ldmlBCP47.dtd";
SOURCE_FILE_DIR = CLDR_BASE + "/main";
SPPL_SOURCE_FILE = CLDR_BASE + "/supplemental/supplementalData.xml";
LIKELYSUBTAGS_SOURCE_FILE = CLDR_BASE + "/supplemental/likelySubtags.xml";
NUMBERING_SOURCE_FILE = CLDR_BASE + "/supplemental/numberingSystems.xml";
METAZONES_SOURCE_FILE = CLDR_BASE + "/supplemental/metaZones.xml";
TIMEZONE_SOURCE_FILE = CLDR_BASE + "/bcp47/timezone.xml";
SPPL_META_SOURCE_FILE = CLDR_BASE + "/supplemental/supplementalMetadata.xml";
WINZONES_SOURCE_FILE = CLDR_BASE + "/supplemental/windowsZones.xml";
PLURALS_SOURCE_FILE = CLDR_BASE + "/supplemental/plurals.xml";
DAYPERIODRULE_SOURCE_FILE = CLDR_BASE + "/supplemental/dayPeriods.xml";
COVERAGELEVELS_FILE = CLDR_BASE + "/properties/coverageLevels.txt";
if (BASE_LOCALES.isEmpty()) {
setupBaseLocales("en-US");
}
if (copyrightYear == 0) {
copyrightYear = ZonedDateTime.now(ZoneId.of("America/Los_Angeles")).getYear();
}
bundleGenerator = new ResourceBundleGenerator();
// Parse data independent of locales
// parseBCP47() must precede parseSupplemental(). The latter depends
// on IANA alias map, which is produced by the former.
parseBCP47();
parseSupplemental();
// rules maps
pluralRules = generateRules(handlerPlurals);
dayPeriodRules = generateRules(handlerDayPeriodRule);
// TZDB short names map
generateTZDBShortNamesMap();
List<Bundle> bundles = readBundleList();
convertBundles(bundles);
if (isBaseModule) {
// Generate java.time.format.ZoneName.java
generateZoneName();
// Generate Windows tzmappings
generateWindowsTZMappings();
}
}
private static void usage() {
errout("Usage: java CLDRConverter [options]%n"
+ "\t-help output this usage message and exit%n"
+ "\t-verbose output information%n"
+ "\t-draft [contributed | approved | provisional | unconfirmed]%n"
+ "\t\t draft level for using data (default: contributed)%n"
+ "\t-base dir base directory for CLDR input files%n"
+ "\t-basemodule generates bundles that go into java.base module%n"
+ "\t-baselocales loc(,loc)* locales that go into the base module%n"
+ "\t-o dir output directory (default: ./build/gensrc)%n"
+ "\t-year year copyright year in output%n"
+ "\t-zntempfile template file for java.time.format.ZoneName.java%n"
+ "\t-tzdatadir tzdata directory for java.time.format.ZoneName.java%n"
+ "\t-utf8 use UTF-8 rather than \\uxxxx (for debug)%n"
+ "\t-jdk-header-template <file>%n"
+ "\t\t override default GPL header with contents of file%n");
}
static void info(String fmt, Object... args) {
if (verbose) {
System.out.printf(fmt, args);
}
}
static void info(String msg) {
if (verbose) {
System.out.println(msg);
}
}
static void warning(String fmt, Object... args) {
System.err.print("Warning: ");
System.err.printf(fmt, args);
}
static void warning(String msg) {
System.err.print("Warning: ");
errout(msg);
}
static void severe(String fmt, Object... args) {
System.err.print("Error: ");
System.err.printf(fmt, args);
}
static void severe(String msg) {
System.err.print("Error: ");
errout(msg);
}
private static void errout(String msg) {
if (msg.contains("%n")) {
System.err.printf(msg);
} else {
System.err.println(msg);
}
}
/**
* Configure the parser to allow access to DTDs on the file system.
*/
private static void enableFileAccess(SAXParser parser) throws SAXNotSupportedException {
try {
parser.setProperty("http://javax.xml.XMLConstants/property/accessExternalDTD", "file");
} catch (SAXNotRecognizedException ignore) {
// property requires >= JAXP 1.5
}
}
private static List<Bundle> readBundleList() throws Exception {
List<Bundle> retList = new ArrayList<>();
Path path = FileSystems.getDefault().getPath(SOURCE_FILE_DIR);
var coverageMap = coverageLevelsMap();
try (DirectoryStream<Path> dirStr = Files.newDirectoryStream(path)) {
for (Path entry : dirStr) {
String fileName = entry.getFileName().toString();
if (fileName.endsWith(".xml")) {
String id = fileName.substring(0, fileName.indexOf('.'));
Locale cldrLoc = Locale.forLanguageTag(toLanguageTag(id));
List<Locale> candList = getCandidateLocales(cldrLoc);
if (!"root".equals(id) && candList.stream().noneMatch(coverageMap::containsKey)) {
continue;
}
StringBuilder sb = getCandLocales(candList);
if (sb.indexOf("root") == -1) {
sb.append("root");
}
retList.add(new Bundle(id, sb.toString(), null, null));
}
}
}
// Sort the bundles based on id. This will make sure all the parent bundles are
// processed first, e.g., for en_GB bundle, en_001, and "root" comes before
// en_GB. In order for "root" to come at the beginning, "root" is replaced with
// empty string on comparison.
retList.sort((o1, o2) -> {
String id1 = o1.getID();
String id2 = o2.getID();
if(id1.equals("root")) {
id1 = "";
}
if(id2.equals("root")) {
id2 = "";
}
return id1.compareTo(id2);
});
return retList;
}
private static final Map<String, Map<String, Object>> cldrBundles = new HashMap<>();
private static Map<String, SortedSet<String>> metaInfo = new HashMap<>();
static {
// For generating information on supported locales.
metaInfo.put("AvailableLocales", new TreeSet<>());
}
static Map<String, Object> getCLDRBundle(String id) throws Exception {
Map<String, Object> bundle = cldrBundles.get(id);
if (bundle != null) {
return bundle;
}
File file = new File(SOURCE_FILE_DIR + File.separator + id + ".xml");
if (!file.exists()) {
// Skip if the file doesn't exist.
return Collections.emptyMap();
}
info("..... main directory .....");
LDMLParseHandler handler = new LDMLParseHandler(id);
parseLDMLFile(file, handler);
bundle = handler.getData();
cldrBundles.put(id, bundle);
if (id.equals("root")) {
// Calendar data (firstDayOfWeek & minDaysInFirstWeek)
bundle = handlerSuppl.getData("root");
if (bundle != null) {
//merge two maps into one map
Map<String, Object> temp = cldrBundles.remove(id);
bundle.putAll(temp);
cldrBundles.put(id, bundle);
}
}
return bundle;
}
// Parsers for data in "supplemental" directory
//
private static void parseSupplemental() throws Exception {
// Parse SupplementalData file and store the information in the HashMap
// Calendar information such as firstDay and minDay are stored in
// supplementalData.xml as of CLDR1.4. Individual territory is listed
// with its ISO 3166 country code while default is listed using UNM49
// region and composition numerical code (001 for World.)
//
// SupplementalData file also provides the "parent" locales which
// are othrwise not to be fallen back. Process them here as well.
//
handlerSuppl = new SupplementalDataParseHandler();
parseLDMLFile(new File(SPPL_SOURCE_FILE), handlerSuppl);
Map<String, Object> parentData = handlerSuppl.getData("root");
parentData.keySet().stream()
.filter(key -> key.startsWith(PARENT_LOCALE_PREFIX))
.forEach(key -> {
parentLocalesMap.put(key, new TreeSet<String>(
Arrays.asList(((String)parentData.get(key)).split(" "))));
});
// Parse numberingSystems to get digit zero character information.
handlerNumbering = new NumberingSystemsParseHandler();
parseLDMLFile(new File(NUMBERING_SOURCE_FILE), handlerNumbering);
// Parse metaZones to create mappings between Olson tzids and CLDR meta zone names
handlerMetaZones = new MetaZonesParseHandler();
parseLDMLFile(new File(METAZONES_SOURCE_FILE), handlerMetaZones);
// Parse likelySubtags
handlerLikelySubtags = new LikelySubtagsParseHandler();
parseLDMLFile(new File(LIKELYSUBTAGS_SOURCE_FILE), handlerLikelySubtags);
handlerLikelySubtags.getData().forEach((from, to) -> {
if (!from.contains("-")) { // look for language-only tag
var script = to.split("-")[1];
var key = LIKELY_SCRIPT_PREFIX + script;
var prev = likelyScriptMap.putIfAbsent(key, new TreeSet<String>(Set.of(from)));
if (prev != null) {
prev.add(from);
}
}
});
// Parse supplementalMetadata
// Currently interested in deprecated time zone ids and language aliases.
handlerSupplMeta = new SupplementalMetadataParseHandler();
parseLDMLFile(new File(SPPL_META_SOURCE_FILE), handlerSupplMeta);
// Parse windowsZones
handlerWinZones = new WinZonesParseHandler();
parseLDMLFile(new File(WINZONES_SOURCE_FILE), handlerWinZones);
// Parse plurals
handlerPlurals = new PluralsParseHandler();
parseLDMLFile(new File(PLURALS_SOURCE_FILE), handlerPlurals);
// Parse day period rules
handlerDayPeriodRule = new DayPeriodRuleParseHandler();
parseLDMLFile(new File(DAYPERIODRULE_SOURCE_FILE), handlerDayPeriodRule);
}
// Parsers for data in "bcp47" directory
//
private static void parseBCP47() throws Exception {
// Parse timezone
handlerTimeZone = new TimeZoneParseHandler();
parseLDMLFile(new File(TIMEZONE_SOURCE_FILE), handlerTimeZone);
// canonical tz name map
// alias -> primary
//
// Note that CLDR meta zones do not necessarily align with IANA's
// current time zone identifiers. For example, the CLDR "India"
// meta zone maps to "Asia/Calcutta", whereas IANA now uses
// "Asia/Kolkata" for the zone. Accordingly, "canonical" here is
// defined in terms of CLDR's zone mappings.
handlerTimeZone.getData().forEach((k, v) -> {
String[] ids = ((String)v).split("\\s");
for (int i = 1; i < ids.length; i++) {
canonicalTZMap.put(ids[i], ids[0]);
}
});
}
private static void parseLDMLFile(File srcfile, AbstractLDMLHandler<?> handler) throws Exception {
info("..... Parsing " + srcfile.getName() + " .....");
SAXParserFactory pf = SAXParserFactory.newInstance();
pf.setValidating(true);
SAXParser parser = pf.newSAXParser();
enableFileAccess(parser);
parser.parse(srcfile, handler);
}
private static StringBuilder getCandLocales(List<Locale> candList) {
StringBuilder sb = new StringBuilder();
for (Locale loc : candList) {
if (!loc.equals(Locale.ROOT)) {
sb.append(toLocaleName(loc.toLanguageTag()));
sb.append(",");
}
}
return sb;
}
private static List<Locale> getCandidateLocales(Locale cldrLoc) {
List<Locale> candList = new ArrayList<>();
candList = applyParentLocales("", defCon.getCandidateLocales("", cldrLoc));
return candList;
}
private static void convertBundles(List<Bundle> bundles) throws Exception {
var availableLangTags = metaInfo.get("AvailableLocales");
// parent locales map. The mappings are put in base metaInfo file
// for now.
if (isBaseModule) {
metaInfo.putAll(parentLocalesMap);
metaInfo.putAll(likelyScriptMap);
}
for (Bundle bundle : bundles) {
// Get the target map, which contains all the data that should be
// visible for the bundle's locale
Map<String, Object> targetMap = bundle.getTargetMap();
EnumSet<Bundle.Type> bundleTypes = bundle.getBundleTypes();
var id = bundle.getID();
if (bundle.isRoot()) {
// Add DateTimePatternChars because CLDR no longer supports localized patterns.
targetMap.put("DateTimePatternChars", "GyMdkHmsSEDFwWahKzZ");
}
// Now the map contains just the entries that need to be in the resources bundles.
// Go ahead and generate them.
if (bundleTypes.contains(Bundle.Type.LOCALENAMES)) {
Map<String, Object> localeNamesMap = extractLocaleNames(targetMap, id);
if (!localeNamesMap.isEmpty() || bundle.isRoot()) {
bundleGenerator.generateBundle("util", "LocaleNames", id, true, localeNamesMap, BundleType.OPEN);
}
}
if (bundleTypes.contains(Bundle.Type.CURRENCYNAMES)) {
Map<String, Object> currencyNamesMap = extractCurrencyNames(targetMap, id, bundle.getCurrencies());
if (!currencyNamesMap.isEmpty() || bundle.isRoot()) {
bundleGenerator.generateBundle("util", "CurrencyNames", id, true, currencyNamesMap, BundleType.OPEN);
}
}
if (bundleTypes.contains(Bundle.Type.TIMEZONENAMES)) {
Map<String, Object> zoneNamesMap = extractZoneNames(targetMap, id);
if (!zoneNamesMap.isEmpty() || bundle.isRoot()) {
bundleGenerator.generateBundle("util", "TimeZoneNames", id, true, zoneNamesMap, BundleType.TIMEZONE);
}
}
if (bundleTypes.contains(Bundle.Type.CALENDARDATA)) {
Map<String, Object> calendarDataMap = extractCalendarData(targetMap, id);
if (!calendarDataMap.isEmpty() || bundle.isRoot()) {
bundleGenerator.generateBundle("util", "CalendarData", id, true, calendarDataMap, BundleType.PLAIN);
}
}
if (bundleTypes.contains(Bundle.Type.FORMATDATA)) {
Map<String, Object> formatDataMap = extractFormatData(targetMap, id);
if (!formatDataMap.isEmpty() || bundle.isRoot()) {
bundleGenerator.generateBundle("text", "FormatData", id, true, formatDataMap, BundleType.PLAIN);
}
}
// For AvailableLocales
var langTag = toLanguageTag(id);
availableLangTags.add(langTag);
addLikelySubtags(langTag);
}
// Add extra language tags from likely subtags that meet the following conditions
// 1. Its likely subtag is supported (already in the available langtag set)
// 2. Neither of old obsolete ones (in/iw/ji)
handlerLikelySubtags.getData().entrySet().stream()
.filter(e -> availableLangTags.contains(e.getValue()))
.map(Map.Entry::getKey)
.filter(t -> !t.equals("in") && !t.equals("iw") && !t.equals("ji"))
.forEach(availableLangTags::add);
bundleGenerator.generateMetaInfo(metaInfo);
}
static final Map<String, String> aliases = new HashMap<>();
/**
* Translate the aliases into the real entries in the bundle map.
*/
static void handleAliases(Map<String, Object> bundleMap) {
for (String key : aliases.keySet()) {
var sourceKey = aliases.get(key);
if (key.startsWith("ListPatterns_")) {
String k;
while ((k = aliases.get(sourceKey)) != null) {
sourceKey = k;
}
}
var source = bundleMap.get(sourceKey);
if (source != null) {
if (bundleMap.get(key) instanceof String[] sa) {
// fill missing elements in case of String array
for (int i = 0; i < sa.length; i++) {
if (sa[i] == null && ((String[])source)[i] != null) {
sa[i] = ((String[])source)[i];
}
}
}
bundleMap.putIfAbsent(key, source);
}
}
}
/*
* Returns the language portion of the given id.
* If id is "root", "" is returned.
*/
static String getLanguageCode(String id) {
return "root".equals(id) ? "" : Locale.forLanguageTag(id.replaceAll("_", "-")).getLanguage();
}
/**
* Examine if the id includes the country (territory) code. If it does, it returns
* the country code.
* Otherwise, it returns null. eg. when the id is "zh_Hans_SG", it returns "SG".
* It does NOT return UN M.49 code, e.g., '001', as those three digit numbers cannot
* be translated into package names.
*/
static String getCountryCode(String id) {
String rgn = getRegionCode(id);
return rgn.length() == 2 ? rgn: null;
}
/**
* Examine if the id includes the region code. If it does, it returns
* the region code.
* Otherwise, it returns null. eg. when the id is "zh_Hans_SG", it returns "SG".
* It DOES return UN M.49 code, e.g., '001', as well as ISO 3166 two letter country codes.
*/
static String getRegionCode(String id) {
return Locale.forLanguageTag(id.replaceAll("_", "-")).getCountry();
}
/**
* Examine if the id includes the script code. If it does, it returns
* the script code.
*/
static String getScriptCode(String id) {
return Locale.forLanguageTag(id.replaceAll("_", "-")).getScript();
}
private static class KeyComparator implements Comparator<String> {
static KeyComparator INSTANCE = new KeyComparator();
private KeyComparator() {
}
@Override
public int compare(String o1, String o2) {
int len1 = o1.length();
int len2 = o2.length();
if (!isDigit(o1.charAt(0)) && !isDigit(o2.charAt(0))) {
// Shorter string comes first unless either starts with a digit.
if (len1 < len2) {
return -1;
}
if (len1 > len2) {
return 1;
}
}
return o1.compareTo(o2);
}
private boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
}
private static Map<String, Object> extractLocaleNames(Map<String, Object> map, String id) {
Map<String, Object> localeNames = new TreeMap<>(KeyComparator.INSTANCE);
for (String key : map.keySet()) {
if (key.startsWith(LOCALE_NAME_PREFIX)) {
switch (key) {
case LOCALE_SEPARATOR:
localeNames.put("ListCompositionPattern", map.get(key));
break;
case LOCALE_KEYTYPE:
localeNames.put("ListKeyTypePattern", map.get(key));
break;
default:
localeNames.put(key.substring(LOCALE_NAME_PREFIX.length()), map.get(key));
break;
}
}
}
if (id.equals("root")) {
// Add display name pattern, which is not in CLDR
localeNames.put("DisplayNamePattern", "{0,choice,0#|1#{1}|2#{1} ({2})}");
}
return localeNames;
}
@SuppressWarnings("AssignmentToForLoopParameter")
private static Map<String, Object> extractCurrencyNames(Map<String, Object> map, String id, String names)
throws Exception {
Map<String, Object> currencyNames = new TreeMap<>(KeyComparator.INSTANCE);
for (String key : map.keySet()) {
if (key.startsWith(CURRENCY_NAME_PREFIX)) {
currencyNames.put(key.substring(CURRENCY_NAME_PREFIX.length()), map.get(key));
} else if (key.startsWith(CURRENCY_SYMBOL_PREFIX)) {
currencyNames.put(key.substring(CURRENCY_SYMBOL_PREFIX.length()), map.get(key));
}
}
return currencyNames;
}
private static Map<String, Object> extractZoneNames(Map<String, Object> map, String id) {
Map<String, Object> names = new TreeMap<>(KeyComparator.INSTANCE);
var availableIds = getAvailableZoneIds();
availableIds.forEach(tzid -> {
// If the tzid is deprecated, get the data for the replacement id
String tzKey = Optional.ofNullable((String)handlerSupplMeta.get(tzid))
.orElse(tzid);
// Follow link, if needed
String tzLink = null;
for (var k = tzKey; tzdbLinks.containsKey(k);) {
k = tzLink = tzdbLinks.get(k);
}
if (tzLink == null && tzdbLinks.containsValue(tzKey)) {
// reverse link search
// this is needed as in tzdb, "America/Buenos_Aires" links to
// "America/Argentina/Buenos_Aires", but CLDR contains metaZone
// "Argentina" only for "America/Buenos_Aires" (as of CLDR 44)
// Both tzids should have "Argentina" meta zone names
tzLink = tzdbLinks.entrySet().stream()
.filter(e -> e.getValue().equals(tzKey))
.map(Map.Entry::getKey)
.findAny()
.orElse(null);
}
Object data = map.get(TIMEZONE_ID_PREFIX + tzKey);
if (data == null && tzLink != null) {
// data for tzLink
data = map.get(TIMEZONE_ID_PREFIX + tzLink);
}
if (data instanceof String[] tznames) {
// Hack for UTC. UTC is an alias to Etc/UTC in CLDR
if (tzid.equals("Etc/UTC") && !map.containsKey(TIMEZONE_ID_PREFIX + "UTC")) {
names.put(METAZONE_ID_PREFIX + META_ETCUTC_ZONE_NAME, tznames);
names.put(tzid, META_ETCUTC_ZONE_NAME);
names.put("UTC", META_ETCUTC_ZONE_NAME);
} else {
// TZDB short names
tznames = Arrays.copyOf(tznames, tznames.length);
fillTZDBShortNames(tzid, tznames);
names.put(tzid, tznames);
}
} else {
String meta = handlerMetaZones.get(tzKey);
if (meta == null && tzLink != null) {
// Check for tzLink
meta = handlerMetaZones.get(tzLink);
}
if (meta != null) {
String metaKey = METAZONE_ID_PREFIX + meta;
data = map.get(metaKey);
if (data instanceof String[] tznames) {
// TZDB short names
tznames = Arrays.copyOf((String[])names.getOrDefault(metaKey, tznames), 6);
fillTZDBShortNames(tzid, tznames);
// Keep the metazone prefix here.
names.putIfAbsent(metaKey, tznames);
names.put(tzid, meta);
if (tzLink != null && availableIds.contains(tzLink)) {
names.put(tzLink, meta);
}
}
} else if (id.equals("root")) {
// supply TZDB short names if available
if (tzdbShortNamesMap.containsKey(tzid)) {
var tznames = new String[6];
fillTZDBShortNames(tzid, tznames);
names.put(tzid, tznames);
}
}
}
});
// exemplar cities.
Map<String, Object> exCities = map.entrySet().stream()
.filter(e -> e.getKey().startsWith(CLDRConverter.EXEMPLAR_CITY_PREFIX))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
names.putAll(exCities);
// Explicit metazone offsets
if (id.equals("root")) {
explicitDstOffsets.forEach((k, v) ->
names.put(METAZONE_DSTOFFSET_PREFIX + k, v));
}
// If there's no UTC entry at this point, add an empty one
if (!names.isEmpty() && !names.containsKey("UTC")) {
names.putIfAbsent(METAZONE_ID_PREFIX + META_EMPTY_ZONE_NAME, EMPTY_ZONE);
names.put("UTC", META_EMPTY_ZONE_NAME);
}
// Finally some compatibility stuff
ZoneId.SHORT_IDS.entrySet().stream()
.filter(e -> !names.containsKey(e.getKey()) && names.containsKey(e.getValue()))
.forEach(e -> {
names.put(e.getKey(), names.get(e.getValue()));
});
return names;
}
/**
* Extracts the language independent calendar data. Each of the two keys,
* "firstDayOfWeek" and "minimalDaysInFirstWeek" has a string value consists of
* one or multiple occurrences of:
* i: rg1 rg2 ... rgn;
* where "i" is the data for the following regions (delimited by a space) after
* ":", and ends with a ";".
*/
private static Map<String, Object> extractCalendarData(Map<String, Object> map, String id) {
Map<String, Object> calendarData = new LinkedHashMap<>();
if (id.equals("root")) {
calendarData.put("firstDayOfWeek",
IntStream.range(1, 8)
.mapToObj(String::valueOf)
.filter(d -> map.keySet().contains(CALENDAR_FIRSTDAY_PREFIX + d))
.map(d -> d + ": " + map.get(CALENDAR_FIRSTDAY_PREFIX + d))
.collect(Collectors.joining(";")));
calendarData.put("minimalDaysInFirstWeek",
IntStream.range(0, 7)
.mapToObj(String::valueOf)
.filter(d -> map.keySet().contains(CALENDAR_MINDAYS_PREFIX + d))
.map(d -> d + ": " + map.get(CALENDAR_MINDAYS_PREFIX + d))
.collect(Collectors.joining(";")));
}
return calendarData;
}
static final String[] FORMAT_DATA_ELEMENTS = {
"MonthNames",
"standalone.MonthNames",
"MonthAbbreviations",
"standalone.MonthAbbreviations",
"MonthNarrows",
"standalone.MonthNarrows",
"DayNames",
"standalone.DayNames",
"DayAbbreviations",
"standalone.DayAbbreviations",
"DayNarrows",
"standalone.DayNarrows",
"QuarterNames",
"standalone.QuarterNames",
"QuarterAbbreviations",
"standalone.QuarterAbbreviations",
"QuarterNarrows",
"standalone.QuarterNarrows",
"AmPmMarkers",
"narrow.AmPmMarkers",
"abbreviated.AmPmMarkers",
"long.Eras",
"Eras",
"narrow.Eras",
"field.era",
"field.year",
"field.month",
"field.week",
"field.weekday",
"field.dayperiod",
"field.hour",
"timezone.hourFormat",
"timezone.gmtFormat",
"timezone.gmtZeroFormat",
"timezone.regionFormat",
"timezone.regionFormat.daylight",
"timezone.regionFormat.standard",
"field.minute",
"field.second",
"field.zone",
"TimePatterns",
"DatePatterns",
"DateTimePatterns",
"DateTimePatternChars",
"PluralRules",
"DayPeriodRules",
"DateFormatItemInputRegions.allowed",
"DateFormatItemInputRegions.preferred",
"ListPatterns",
};
static final Set<String> availableSkeletons = new HashSet<>();
private static Map<String, Object> extractFormatData(Map<String, Object> map, String id) {
Map<String, Object> formatData = new LinkedHashMap<>();
for (CalendarType calendarType : CalendarType.values()) {
String prefix = calendarType.keyElementName();
Arrays.stream(FORMAT_DATA_ELEMENTS)
.forEach(elem -> {
var key = prefix + elem;
copyIfPresent(map, "java.time." + key, formatData);
copyIfPresent(map, key, formatData);
});
availableSkeletons.forEach(s ->
copyIfPresent(map, prefix + "DateFormatItem." + s, formatData));
}
for (String key : map.keySet()) {
// Copy available calendar names
if (key.startsWith(CLDRConverter.LOCALE_TYPE_PREFIX_CA)) {
String type = key.substring(CLDRConverter.LOCALE_TYPE_PREFIX_CA.length());
for (CalendarType calendarType : CalendarType.values()) {
if (type.equals(calendarType.lname())) {
Object value = map.get(key);
String dataKey = key.replace(LOCALE_TYPE_PREFIX_CA,