idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
5,200
private static void createCurrencies ( TypeSpec . Builder type , List < String > currencies ) { TypeSpec . Builder currencyType = TypeSpec . enumBuilder ( "Currency" ) . addModifiers ( PUBLIC , STATIC ) ; List < String > codes = new ArrayList < > ( ) ; codes . addAll ( currencies ) ; Collections . sort ( codes ) ; StringBuilder buf = new StringBuilder ( "$T.unmodifiableList($T.asList(\n" ) ; for ( int i = 0 ; i < codes . size ( ) ; i ++ ) { if ( i > 0 ) { buf . append ( ",\n" ) ; } currencyType . addEnumConstant ( codes . get ( i ) ) ; buf . append ( " Currency.$L" ) ; } buf . append ( "))" ) ; MethodSpec . Builder method = MethodSpec . methodBuilder ( "fromString" ) . addModifiers ( PUBLIC , STATIC ) . addParameter ( STRING , "code" ) . returns ( Types . CLDR_CURRENCY_ENUM ) ; method . beginControlFlow ( "if (code != null)" ) ; method . beginControlFlow ( "switch (code)" ) ; for ( int i = 0 ; i < codes . size ( ) ; i ++ ) { method . addStatement ( "case $S: return $L" , codes . get ( i ) , codes . get ( i ) ) ; } method . addStatement ( "default: break" ) ; method . endControlFlow ( ) ; method . endControlFlow ( ) ; method . addStatement ( "return null" ) ; currencyType . addMethod ( method . build ( ) ) ; type . addType ( currencyType . build ( ) ) ; List < Object > arguments = new ArrayList < > ( ) ; arguments . add ( Collections . class ) ; arguments . add ( Arrays . class ) ; arguments . addAll ( codes ) ; }
Create top - level container to hold currency constants .
5,201
protected static Unit selectExactUnit ( String compact , UnitConverter converter ) { if ( compact != null ) { switch ( compact ) { case "consumption" : return converter . consumptionUnit ( ) ; case "light" : return Unit . LUX ; case "speed" : return converter . speedUnit ( ) ; case "temp" : case "temperature" : return converter . temperatureUnit ( ) ; default : break ; } } return null ; }
Some categories only have a single possible unit depending the locale .
5,202
protected static Unit inputFromExactUnit ( Unit exact , UnitConverter converter ) { switch ( exact ) { case TERABIT : case GIGABIT : case MEGABIT : case KILOBIT : case BIT : return Unit . BIT ; case TERABYTE : case GIGABYTE : case MEGABYTE : case KILOBYTE : case BYTE : return Unit . BYTE ; default : break ; } UnitCategory category = exact . category ( ) ; switch ( category ) { case CONSUMPTION : return converter . consumptionUnit ( ) ; case ELECTRIC : return Unit . AMPERE ; case FREQUENCY : return Unit . HERTZ ; case LIGHT : return Unit . LUX ; case PRESSURE : return Unit . MILLIBAR ; case SPEED : return converter . speedUnit ( ) ; case TEMPERATURE : return converter . temperatureUnit ( ) ; default : UnitFactorSet factorSet = getDefaultFactorSet ( category , converter ) ; if ( factorSet != null ) { return factorSet . base ( ) ; } break ; } return null ; }
Based on the unit we re converting to guess the input unit . For example if we re converting to MEGABIT and no input unit was specified assume BIT .
5,203
protected static UnitFactorSet getDefaultFactorSet ( UnitCategory category , UnitConverter converter ) { switch ( category ) { case ANGLE : return UnitFactorSets . ANGLE ; case AREA : return converter . areaFactors ( ) ; case DURATION : return UnitFactorSets . DURATION ; case ELECTRIC : return UnitFactorSets . ELECTRIC ; case ENERGY : return converter . energyFactors ( ) ; case FREQUENCY : return UnitFactorSets . FREQUENCY ; case LENGTH : return converter . lengthFactors ( ) ; case MASS : return converter . massFactors ( ) ; case POWER : return UnitFactorSets . POWER ; case VOLUME : return converter . volumeFactors ( ) ; default : break ; } return null ; }
Default conversion factors for each category . Some of these differ based on the locale of the converter .
5,204
public String render ( ) { StringBuilder buf = new StringBuilder ( ) ; for ( Node node : parsed ) { if ( node instanceof Symbol ) { switch ( ( Symbol ) node ) { case MINUS : buf . append ( '-' ) ; break ; case CURRENCY : buf . append ( CURRENCY_SYM ) ; break ; case PERCENT : buf . append ( '%' ) ; break ; } } else if ( node instanceof Text ) { String text = ( ( Text ) node ) . text ; int len = text . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char ch = text . charAt ( i ) ; switch ( ch ) { case '.' : case '#' : case ',' : case '-' : buf . append ( '\'' ) . append ( ch ) . append ( '\'' ) ; break ; default : buf . append ( ch ) ; break ; } } } else if ( node instanceof Format ) { Format format = ( Format ) node ; format . render ( buf ) ; } } return buf . toString ( ) ; }
Render a parseable representation of this pattern .
5,205
public String dump ( ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( " LOCALE MATCHED BUNDLE\n" ) ; buf . append ( " ====== ==============\n" ) ; List < MetaLocale > keys = availableBundlesMap . keySet ( ) . stream ( ) . map ( k -> ( MetaLocale ) k ) . collect ( Collectors . toList ( ) ) ; Collections . sort ( keys ) ; for ( CLDR . Locale key : keys ) { buf . append ( String . format ( "%20s -> %s\n" , key , availableBundlesMap . get ( key ) ) ) ; } return buf . toString ( ) ; }
Inspect the mapping between permutations of locale fields and bundle identifiers .
5,206
private void buildMap ( List < CLDR . Locale > availableBundles ) { List < MetaLocale > maxBundleIds = new ArrayList < > ( ) ; for ( CLDR . Locale locale : availableBundles ) { MetaLocale source = ( MetaLocale ) locale ; if ( source . isRoot ( ) ) { continue ; } MetaLocale maxBundleId = languageResolver . addLikelySubtags ( source ) ; maxBundleIds . add ( maxBundleId ) ; availableBundlesMap . put ( source . copy ( ) , source ) ; if ( ! source . equals ( maxBundleId ) ) { availableBundlesMap . putIfAbsent ( maxBundleId . copy ( ) , source ) ; } } for ( MetaLocale bundleId : maxBundleIds ) { indexPermutations ( bundleId ) ; } }
Iterate over the available bundle identifiers expand them and index all permutations to enable a fast direct lookup .
5,207
private void indexPermutations ( MetaLocale bundleId ) { MetaLocale key = bundleId . copy ( ) ; for ( int flags : LanguageResolver . MATCH_ORDER ) { LanguageResolver . set ( bundleId , key , flags ) ; MetaLocale maxBundleId = languageResolver . addLikelySubtags ( key ) ; MetaLocale source = availableBundlesMap . get ( maxBundleId ) ; if ( source != null ) { availableBundlesMap . putIfAbsent ( key . copy ( ) , source ) ; } else if ( maxBundleId . hasVariant ( ) ) { maxBundleId . setVariant ( null ) ; source = availableBundlesMap . get ( maxBundleId ) ; if ( source != null ) { availableBundlesMap . putIfAbsent ( key . copy ( ) , source ) ; } } } }
Index permutations of the given bundle identifier . We iterate over the field permutations and expand each to the maximum bundle identifier then query to see if that max bundle identifier matches a bundle . Then we index the permutation to that bundle . This creates a static mapping mimicking a dynamic lookup .
5,208
public Map < LocaleID , ClassName > generate ( Path outputDir , DataReader reader ) throws IOException { Map < LocaleID , ClassName > dateClasses = new TreeMap < > ( ) ; List < DateTimeData > dateTimeDataList = new ArrayList < > ( ) ; for ( Map . Entry < LocaleID , DateTimeData > entry : reader . calendars ( ) . entrySet ( ) ) { DateTimeData dateTimeData = entry . getValue ( ) ; LocaleID localeId = entry . getKey ( ) ; String className = "_CalendarFormatter_" + localeId . safe ; TimeZoneData timeZoneData = reader . timezones ( ) . get ( localeId ) ; TypeSpec type = createFormatter ( dateTimeData , timeZoneData , className ) ; CodeGenerator . saveClass ( outputDir , Types . PACKAGE_CLDR_DATES , className , type ) ; ClassName cls = ClassName . get ( Types . PACKAGE_CLDR_DATES , className ) ; dateClasses . put ( localeId , cls ) ; dateTimeDataList . add ( dateTimeData ) ; } String className = "_CalendarUtils" ; TypeSpec . Builder utilsType = TypeSpec . classBuilder ( className ) . addModifiers ( PUBLIC ) ; addSkeletonClassifierMethod ( utilsType , dateTimeDataList ) ; addMetaZones ( utilsType , reader . metazones ( ) ) ; buildTimeZoneAliases ( utilsType , reader . timezoneAliases ( ) ) ; CodeGenerator . saveClass ( outputDir , Types . PACKAGE_CLDR_DATES , "_CalendarUtils" , utilsType . build ( ) ) ; return dateClasses ; }
Generates the date - time classes into the given output directory .
5,209
private void addSkeletonClassifierMethod ( TypeSpec . Builder type , List < DateTimeData > dataList ) { Set < String > dates = new LinkedHashSet < > ( ) ; Set < String > times = new LinkedHashSet < > ( ) ; for ( DateTimeData data : dataList ) { for ( Skeleton skeleton : data . dateTimeSkeletons ) { if ( isDateSkeleton ( skeleton . skeleton ) ) { dates . add ( skeleton . skeleton ) ; } else { times . add ( skeleton . skeleton ) ; } } } MethodSpec . Builder method = buildSkeletonType ( dates , times ) ; type . addMethod ( method . build ( ) ) ; }
Create a helper class to classify skeletons as either DATE or TIME .
5,210
private void addMetaZones ( TypeSpec . Builder type , Map < String , MetaZone > metazones ) { ClassName metazoneType = ClassName . get ( Types . PACKAGE_CLDR_DATES , "MetaZone" ) ; TypeName mapType = ParameterizedTypeName . get ( MAP , STRING , metazoneType ) ; FieldSpec . Builder field = FieldSpec . builder ( mapType , "metazones" , PROTECTED , STATIC , FINAL ) ; CodeBlock . Builder code = CodeBlock . builder ( ) ; code . beginControlFlow ( "new $T<$T, $T>() {" , HashMap . class , String . class , metazoneType ) ; for ( Map . Entry < String , MetaZone > entry : metazones . entrySet ( ) ) { String zoneId = entry . getKey ( ) ; MetaZone zone = entry . getValue ( ) ; code . beginControlFlow ( "\nput($S, new $T($S,\n new $T.Entry[] " , zoneId , metazoneType , zoneId , metazoneType ) ; int size = zone . metazones . size ( ) ; Collections . reverse ( zone . metazones ) ; for ( int i = 0 ; i < size ; i ++ ) { MetaZoneEntry meta = zone . metazones . get ( i ) ; if ( i > 0 ) { code . add ( ",\n" ) ; } code . add ( " new $T.Entry($S, " , metazoneType , meta . metazone ) ; if ( meta . from != null ) { code . add ( "/* $L */ $L, " , meta . fromString , meta . from . toEpochSecond ( ) ) ; } else { code . add ( "-1, " ) ; } if ( meta . to != null ) { code . add ( "/* $L */ $L)" , meta . toString , meta . to . toEpochSecond ( ) ) ; } else { code . add ( "-1)" ) ; } } code . endControlFlow ( "))" ) ; } code . endControlFlow ( "\n}" ) ; field . initializer ( code . build ( ) ) ; type . addField ( field . build ( ) ) ; MethodSpec . Builder method = MethodSpec . methodBuilder ( "getMetazone" ) . addModifiers ( PUBLIC , STATIC ) . addParameter ( String . class , "zoneId" ) . addParameter ( ZonedDateTime . class , "date" ) . returns ( String . class ) ; method . addStatement ( "$T zone = metazones.get(zoneId)" , metazoneType ) ; method . addStatement ( "return zone == null ? null : zone.applies(date)" ) ; type . addMethod ( method . build ( ) ) ; }
Populate the metaZone mapping .
5,211
private void buildTimeZoneAliases ( TypeSpec . Builder type , Map < String , String > map ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "getTimeZoneAlias" ) . addModifiers ( PUBLIC , STATIC ) . addParameter ( String . class , "zoneId" ) . returns ( String . class ) ; method . beginControlFlow ( "switch (zoneId)" ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { method . addStatement ( "case $S: return $S" , entry . getKey ( ) , entry . getValue ( ) ) ; } method . addStatement ( "default: return null" ) ; method . endControlFlow ( ) ; type . addMethod ( method . build ( ) ) ; }
Creates a switch table to resolve a retired time zone to a valid one .
5,212
private TypeSpec createFormatter ( DateTimeData dateTimeData , TimeZoneData timeZoneData , String className ) { LocaleID id = dateTimeData . id ; MethodSpec . Builder constructor = MethodSpec . constructorBuilder ( ) . addModifiers ( PUBLIC ) ; constructor . addStatement ( "this.bundleId = $T.$L" , CLDR_LOCALE_IF , id . safe ) ; constructor . addStatement ( "this.firstDay = $L" , dateTimeData . firstDay ) ; constructor . addStatement ( "this.minDays = $L" , dateTimeData . minDays ) ; variantsFieldInit ( constructor , "this.eras" , dateTimeData . eras ) ; variantsFieldInit ( constructor , "this.quartersFormat" , dateTimeData . quartersFormat ) ; variantsFieldInit ( constructor , "this.quartersStandalone" , dateTimeData . quartersStandalone ) ; variantsFieldInit ( constructor , "this.monthsFormat" , dateTimeData . monthsFormat ) ; variantsFieldInit ( constructor , "this.monthsStandalone" , dateTimeData . monthsStandalone ) ; variantsFieldInit ( constructor , "this.weekdaysFormat" , dateTimeData . weekdaysFormat ) ; variantsFieldInit ( constructor , "this.weekdaysStandalone" , dateTimeData . weekdaysStandalone ) ; variantsFieldInit ( constructor , "this.dayPeriodsFormat" , dateTimeData . dayPeriodsFormat ) ; variantsFieldInit ( constructor , "this.dayPeriodsStandalone" , dateTimeData . dayPeriodsStandalone ) ; buildTimeZoneExemplarCities ( constructor , timeZoneData ) ; buildTimeZoneNames ( constructor , timeZoneData ) ; buildMetaZoneNames ( constructor , timeZoneData ) ; TypeSpec . Builder type = TypeSpec . classBuilder ( className ) . superclass ( CALENDAR_FORMATTER ) . addModifiers ( PUBLIC ) . addJavadoc ( "Locale \"" + dateTimeData . id + "\"\n" + "See http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table\n" ) . addMethod ( constructor . build ( ) ) ; MethodSpec dateMethod = buildTypedPatternMethod ( "formatDate" , CALENDAR_FORMAT , dateTimeData . dateFormats ) ; MethodSpec timeMethod = buildTypedPatternMethod ( "formatTime" , CALENDAR_FORMAT , dateTimeData . timeFormats ) ; MethodSpec wrapperMethod = buildWrapperMethod ( dateTimeData . dateTimeFormats ) ; MethodSpec skeletonMethod = buildSkeletonFormatter ( dateTimeData . dateTimeSkeletons ) ; MethodSpec intervalMethod = buildIntervalMethod ( dateTimeData . intervalFormats , dateTimeData . intervalFallbackFormat ) ; MethodSpec gmtMethod = buildWrapTimeZoneGMTMethod ( timeZoneData ) ; MethodSpec regionFormatMethod = buildWrapTimeZoneRegionMethod ( timeZoneData ) ; return type . addMethod ( dateMethod ) . addMethod ( timeMethod ) . addMethod ( wrapperMethod ) . addMethod ( skeletonMethod ) . addMethod ( intervalMethod ) . addMethod ( gmtMethod ) . addMethod ( regionFormatMethod ) . build ( ) ; }
Create a Java class that captures all data formats for a given locale .
5,213
private void addTypedPattern ( MethodSpec . Builder method , String formatType , String pattern ) { method . beginControlFlow ( "case $L:" , formatType ) ; method . addComment ( "$S" , pattern ) ; addPattern ( method , pattern ) ; method . addStatement ( "break" ) ; method . endControlFlow ( ) ; }
Adds the pattern builder statements for a typed pattern .
5,214
private void addPattern ( MethodSpec . Builder method , String pattern ) { for ( Node node : DATETIME_PARSER . parse ( pattern ) ) { if ( node instanceof Text ) { method . addStatement ( "b.append($S)" , ( ( Text ) node ) . text ( ) ) ; } else if ( node instanceof Field ) { Field field = ( Field ) node ; method . addStatement ( "formatField(d, '$L', $L, b)" , field . ch ( ) , field . width ( ) ) ; } } }
Add a named date - time pattern adding statements to the formatting and indexing methods . Returns true if the pattern corresponds to a date ; false if a time .
5,215
private MethodSpec buildSkeletonFormatter ( List < Skeleton > skeletons ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "formatSkeleton" ) . addAnnotation ( Override . class ) . addModifiers ( PUBLIC ) . addParameter ( String . class , "skeleton" ) . addParameter ( ZonedDateTime . class , "d" ) . addParameter ( StringBuilder . class , "b" ) . returns ( boolean . class ) ; method . beginControlFlow ( "if (skeleton == null)" ) ; method . addStatement ( "return false" ) ; method . endControlFlow ( ) ; method . beginControlFlow ( "switch (skeleton)" ) ; for ( Skeleton skeleton : skeletons ) { method . beginControlFlow ( "case $S:" , skeleton . skeleton ) . addComment ( "Pattern: $S" , skeleton . pattern ) ; addPattern ( method , skeleton . pattern ) ; method . addStatement ( "break" ) ; method . endControlFlow ( ) ; } method . beginControlFlow ( "default:" ) ; method . addStatement ( "return false" ) ; method . endControlFlow ( ) ; method . endControlFlow ( ) ; method . addStatement ( "return true" ) ; return method . build ( ) ; }
Implements the formatSkeleton method .
5,216
private MethodSpec buildIntervalMethod ( Map < String , Map < String , String > > intervalFormats , String fallback ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "formatInterval" ) . addAnnotation ( Override . class ) . addModifiers ( PUBLIC ) . addParameter ( ZonedDateTime . class , "s" ) . addParameter ( ZonedDateTime . class , "e" ) . addParameter ( String . class , "k" ) . addParameter ( DateTimeField . class , "f" ) . addParameter ( StringBuilder . class , "b" ) ; method . beginControlFlow ( "if (k != null && f != null)" ) ; method . beginControlFlow ( "switch (k)" ) ; for ( Map . Entry < String , Map < String , String > > format : intervalFormats . entrySet ( ) ) { String skeleton = format . getKey ( ) ; method . beginControlFlow ( "case $S:" , skeleton ) ; method . beginControlFlow ( "switch (f)" ) ; for ( Map . Entry < String , String > entry : format . getValue ( ) . entrySet ( ) ) { String field = entry . getKey ( ) ; Pair < List < Node > , List < Node > > patterns = DATETIME_PARSER . splitIntervalPattern ( entry . getValue ( ) ) ; method . beginControlFlow ( "case $L:" , DateTimeField . fromString ( field ) ) ; method . addComment ( "$S" , DateTimePatternParser . render ( patterns . _1 ) ) ; addIntervalPattern ( method , patterns . _1 , "s" ) ; method . addComment ( "$S" , DateTimePatternParser . render ( patterns . _2 ) ) ; addIntervalPattern ( method , patterns . _2 , "e" ) ; method . addStatement ( "return" ) ; method . endControlFlow ( ) ; } method . addStatement ( "default: break" ) ; method . endControlFlow ( ) ; method . addStatement ( "break" ) ; method . endControlFlow ( ) ; } method . addStatement ( "default: break" ) ; method . endControlFlow ( ) ; addIntervalFallback ( method , fallback ) ; method . endControlFlow ( ) ; return method . build ( ) ; }
Build methods to format date time intervals using the field of greatest difference .
5,217
private void addIntervalPattern ( MethodSpec . Builder method , List < Node > pattern , String which ) { for ( Node node : pattern ) { if ( node instanceof Text ) { method . addStatement ( "b.append($S)" , ( ( Text ) node ) . text ( ) ) ; } else if ( node instanceof Field ) { Field field = ( Field ) node ; method . addStatement ( "formatField($L, '$L', $L, b)" , which , field . ch ( ) , field . width ( ) ) ; } } }
Adds code to format a date time interval pattern which may be the start or end date time signified by the which parameter .
5,218
private void addIntervalFallback ( MethodSpec . Builder method , String pattern ) { method . addComment ( "$S" , pattern ) ; for ( Node node : WRAPPER_PARSER . parseWrapper ( pattern ) ) { if ( node instanceof Text ) { method . addStatement ( "b.append($S)" , ( ( Text ) node ) . text ( ) ) ; } else if ( node instanceof Field ) { Field field = ( Field ) node ; String which = "s" ; if ( field . ch ( ) == '1' ) { which = "e" ; } method . addStatement ( "formatSkeleton(k, $L, b)" , which ) ; } } }
Adds code to render the fallback pattern .
5,219
private boolean isDateSkeleton ( String skeleton ) { List < String > parts = Splitter . on ( '-' ) . splitToList ( skeleton ) ; if ( parts . size ( ) > 1 ) { skeleton = parts . get ( 0 ) ; } for ( Node node : DATETIME_PARSER . parse ( skeleton ) ) { if ( node instanceof Field ) { Field field = ( Field ) node ; switch ( field . ch ( ) ) { case 'H' : case 'h' : case 'm' : case 's' : return false ; } } } return true ; }
Indicates a skeleton represents a date based on the fields it contains . Any time - related field will cause this to return false .
5,220
private MethodSpec . Builder buildSkeletonType ( Set < String > dateSkeletons , Set < String > timeSkeletons ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "skeletonType" ) . addJavadoc ( "Indicates whether a given skeleton pattern is a DATE or TIME.\n" ) . addModifiers ( PUBLIC , STATIC ) . addParameter ( String . class , "skeleton" ) . returns ( SKELETON ) ; method . beginControlFlow ( "switch (skeleton)" ) ; for ( String skel : dateSkeletons ) { method . addCode ( "case $S:\n" , skel ) ; } method . addStatement ( " return $T.DATE" , SKELETON ) ; for ( String skel : timeSkeletons ) { method . addCode ( "case $S:\n" , skel ) ; } method . addStatement ( " return $T.TIME" , SKELETON ) ; method . addCode ( "default:\n" ) ; method . addStatement ( " return null" ) ; method . endControlFlow ( ) ; return method ; }
Constructs a method to indicate if the skeleton is a DATE or TIME or null if unsupported .
5,221
private void variantsFieldInit ( MethodSpec . Builder method , String fieldName , Variants v ) { Stmt b = new Stmt ( ) ; b . append ( "$L = new $T(" , fieldName , FIELD_VARIANTS ) ; b . append ( "\n " ) . append ( v . abbreviated ) . comma ( ) ; b . append ( "\n " ) . append ( v . narrow ) . comma ( ) ; b . append ( "\n " ) . append ( v . short_ ) . comma ( ) ; b . append ( "\n " ) . append ( v . wide ) ; b . append ( ")" ) ; method . addStatement ( b . format ( ) , b . args ( ) ) ; }
Appends a statement that initializes a FieldVariants field in the superclass .
5,222
private void buildTimeZoneExemplarCities ( MethodSpec . Builder method , TimeZoneData data ) { CodeBlock . Builder code = CodeBlock . builder ( ) ; code . beginControlFlow ( "this.exemplarCities = new $T<$T, $T>() {" , HashMap . class , String . class , String . class ) ; for ( TimeZoneInfo info : data . timeZoneInfo ) { code . addStatement ( "put($S, $S)" , info . zone , info . exemplarCity ) ; } code . endControlFlow ( "}" ) ; method . addCode ( code . build ( ) ) ; }
Mapping locale identifiers to their localized exemplar cities .
5,223
private void buildMetaZoneNames ( MethodSpec . Builder method , TimeZoneData data ) { CodeBlock . Builder code = CodeBlock . builder ( ) ; code . beginControlFlow ( "\nthis.$L = new $T<$T, $T>() {" , "metazoneNames" , HASHMAP , STRING , TIMEZONE_NAMES ) ; for ( MetaZoneInfo info : data . metaZoneInfo ) { if ( info . nameLong == null && info . nameShort == null ) { continue ; } code . add ( "\nput($S, new $T($S, " , info . zone , TIMEZONE_NAMES , info . zone ) ; if ( info . nameLong == null ) { code . add ( "\n null," ) ; } else { code . add ( "\n new $T.Name($S, $S, $S)," , TIMEZONE_NAMES , info . nameLong . generic , info . nameLong . standard , info . nameLong . daylight ) ; } if ( info . nameShort == null ) { code . add ( "\n null" ) ; } else { code . add ( "\n new $T.Name($S, $S, $S)" , TIMEZONE_NAMES , info . nameShort . generic , info . nameShort . standard , info . nameShort . daylight ) ; } code . add ( "));\n" ) ; } code . endControlFlow ( "}" ) ; method . addCode ( code . build ( ) ) ; }
Builds localized metazone name mapping .
5,224
private MethodSpec buildWrapTimeZoneGMTMethod ( TimeZoneData data ) { String [ ] hourFormat = data . hourFormat . split ( ";" ) ; List < Node > positive = DATETIME_PARSER . parse ( hourFormat [ 0 ] ) ; List < Node > negative = DATETIME_PARSER . parse ( hourFormat [ 1 ] ) ; List < Node > format = WRAPPER_PARSER . parseWrapper ( data . gmtFormat ) ; MethodSpec . Builder method = MethodSpec . methodBuilder ( "wrapTimeZoneGMT" ) . addModifiers ( PROTECTED ) . addParameter ( StringBuilder . class , "b" ) . addParameter ( boolean . class , "neg" ) . addParameter ( int . class , "hours" ) . addParameter ( int . class , "mins" ) . addParameter ( boolean . class , "_short" ) ; method . beginControlFlow ( "if (hours == 0 && mins == 0)" ) ; method . addStatement ( "b.append($S)" , data . gmtZeroFormat ) ; method . addStatement ( "return" ) ; method . endControlFlow ( ) ; method . addStatement ( "boolean emitMins = !_short || mins > 0" ) ; for ( Node node : format ) { if ( node instanceof Text ) { Text text = ( Text ) node ; method . addStatement ( "b.append($S)" , text . text ( ) ) ; } else { method . beginControlFlow ( "if (neg)" ) ; appendHourFormat ( method , negative ) ; method . endControlFlow ( ) ; method . beginControlFlow ( "else" ) ; appendHourFormat ( method , positive ) ; method . endControlFlow ( ) ; } } return method . build ( ) ; }
Builds a method to format the timezone as hourFormat with a GMT wrapper .
5,225
private MethodSpec buildWrapTimeZoneRegionMethod ( TimeZoneData data ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( "wrapTimeZoneRegion" ) . addModifiers ( PROTECTED ) . addParameter ( StringBuilder . class , "b" ) . addParameter ( String . class , "region" ) ; List < Node > format = WRAPPER_PARSER . parseWrapper ( data . regionFormat ) ; for ( Node node : format ) { if ( node instanceof Text ) { Text text = ( Text ) node ; method . addStatement ( "b.append($S)" , text . text ( ) ) ; } else { method . addStatement ( "b.append(region)" ) ; } } return method . build ( ) ; }
Build a method to wrap a region in the regionFormat .
5,226
private void appendHourFormat ( MethodSpec . Builder method , List < Node > fmt ) { for ( Node n : fmt ) { if ( n instanceof Text ) { String t = ( ( Text ) n ) . text ( ) ; boolean minute = t . equals ( ":" ) || t . equals ( "." ) ; if ( minute ) { method . beginControlFlow ( "if (emitMins)" ) ; } method . addStatement ( "b.append($S)" , t ) ; if ( minute ) { method . endControlFlow ( ) ; } } else { Field f = ( Field ) n ; if ( f . ch ( ) == 'H' ) { if ( f . width ( ) == 1 ) { method . addStatement ( "zeroPad2(b, hours, 1)" ) ; } else { method . addStatement ( "zeroPad2(b, hours, _short ? 1 : $L)" , f . width ( ) ) ; } } else { method . beginControlFlow ( "if (emitMins)" ) ; method . addStatement ( "zeroPad2(b, mins, $L)" , f . width ( ) ) ; method . endControlFlow ( ) ; } } } }
Appends code to emit the hourFormat for positive or negative .
5,227
public static Map < String , List < String > > deduplicateFormats ( Format format ) { Map < String , List < String > > res = new LinkedHashMap < > ( ) ; mapAdd ( res , format . short_ , "SHORT" ) ; mapAdd ( res , format . medium , "MEDIUM" ) ; mapAdd ( res , format . long_ , "LONG" ) ; mapAdd ( res , format . full , "FULL" ) ; return res ; }
De - duplication of formats .
5,228
public static List < Path > listResources ( String ... prefixes ) throws IOException { List < Path > result = new ArrayList < > ( ) ; ClassPath classPath = ClassPath . from ( Utils . class . getClassLoader ( ) ) ; for ( ResourceInfo info : classPath . getResources ( ) ) { String path = info . getResourceName ( ) ; for ( String prefix : prefixes ) { if ( path . startsWith ( prefix ) ) { result . add ( Paths . get ( path ) ) ; } } } return result ; }
Recursively list all resources under the given path prefixes .
5,229
public static Node < PluralType > findChild ( Struct < PluralType > parent , PluralType type ) { for ( Node < PluralType > n : parent . nodes ( ) ) { if ( n . type ( ) == type ) { return n ; } } return null ; }
Find a child node of a given type in a parent struct or return null .
5,230
public static Maybe < Pair < Node < PluralType > , CharSequence > > parse ( String input ) { return P_RULE . parse ( input ) ; }
Parse a plural rule into an abstract syntax tree .
5,231
public static UnitConverter get ( CLDR . Locale locale ) { MeasurementSystem system = MeasurementSystem . fromLocale ( locale ) ; return SYSTEMS . getOrDefault ( system , METRIC_SYSTEM ) ; }
Retrieves the correct measurement system for a given locale .
5,232
public void reset ( ) { this . formatMode = null ; this . roundMode = NumberRoundMode . ROUND ; this . grouping = null ; this . minimumIntegerDigits = null ; this . maximumFractionDigits = null ; this . minimumFractionDigits = null ; this . maximumSignificantDigits = null ; this . minimumSignificantDigits = null ; }
Reset the options to their defaults .
5,233
public void setFormat ( String format ) { this . format = format ; Scanner scanner = new Scanner ( format ) ; this . streams [ 0 ] = scanner . stream ( ) ; this . streams [ 1 ] = scanner . stream ( ) ; for ( int i = 2 ; i < this . streams . length ; i ++ ) { this . streams [ i ] = null ; } this . tag = scanner . stream ( ) ; this . choice = scanner . stream ( ) ; }
Sets the message format .
5,234
public void format ( MessageArgs args , StringBuilder buf ) { this . args = args ; this . buf = buf ; this . reset ( ) ; format ( streams [ 0 ] , null ) ; }
Formats the message using the given arguments and writing the output to the buffer .
5,235
private void recurse ( Stream bounds , String arg ) { streamIndex ++ ; if ( streamIndex == streams . length ) { return ; } bounds . pos ++ ; bounds . end -- ; if ( streams [ streamIndex ] == null ) { streams [ streamIndex ] = bounds . copy ( ) ; } else { streams [ streamIndex ] . setFrom ( bounds ) ; } format ( streams [ streamIndex ] , arg ) ; streamIndex -- ; }
Push a stream onto the stack and format it .
5,236
private void evaluateTag ( StringBuilder buf ) { tag . pos ++ ; tag . end -- ; if ( tag . peek ( ) == Chars . MINUS_SIGN ) { tag . pos ++ ; buf . append ( '{' ) ; buf . append ( tag . token ( ) ) ; buf . append ( '}' ) ; return ; } List < MessageArg > args = getArgs ( ) ; if ( args == null || args . size ( ) == 0 ) { return ; } MessageArg arg = args . get ( 0 ) ; if ( tag . peek ( ) == Chars . EOF ) { if ( arg . resolve ( ) ) { buf . append ( arg . asString ( ) ) ; } return ; } if ( tag . seek ( FORMATTER , choice ) ) { String formatter = choice . token ( ) . toString ( ) ; tag . jump ( choice ) ; switch ( formatter ) { case PLURAL : evalPlural ( arg , true ) ; break ; case SELECTORDINAL : evalPlural ( arg , false ) ; break ; case SELECT : evalSelect ( arg ) ; break ; case CURRENCY : case MONEY : evalCurrency ( arg ) ; break ; case DATETIME : evalDateTime ( arg ) ; break ; case DATETIME_INTERVAL : evalDateTimeInterval ( args ) ; break ; case DECIMAL : case NUMBER : evalNumber ( arg ) ; break ; case UNIT : evalUnit ( arg ) ; break ; } } }
Parse and evaluate a tag .
5,237
private void evalPlural ( MessageArg arg , boolean cardinal ) { tag . skip ( COMMA_WS ) ; if ( ! arg . resolve ( ) ) { return ; } String value = arg . asString ( ) ; String offsetValue = value ; long offset = 0 ; if ( tag . seek ( PLURAL_OFFSET , choice ) ) { tag . jump ( choice ) ; tag . skip ( COMMA_WS ) ; offset = toLong ( format , choice . pos + 7 , choice . end ) ; long newValue = toLong ( value , 0 , value . length ( ) ) - offset ; offsetValue = Long . toString ( newValue ) ; operands . set ( offsetValue ) ; } else { operands . set ( value ) ; } String language = locale . language ( ) ; PluralCategory category = cardinal ? PLURAL_RULES . evalCardinal ( language , operands ) : PLURAL_RULES . evalOrdinal ( language , operands ) ; Recognizer matcher = PLURAL_MATCHERS [ category . ordinal ( ) ] ; char ch ; while ( ( ch = tag . peek ( ) ) != Chars . EOF ) { if ( ch == '=' && tag . seek ( PLURAL_EXPLICIT , choice ) ) { tag . jump ( choice ) ; choice . pos ++ ; String repr = choice . token ( ) . toString ( ) ; if ( repr . equals ( value ) && tag . seekBounds ( choice , '{' , '}' ) ) { recurse ( choice , offsetValue ) ; return ; } } else if ( tag . seek ( matcher , choice ) ) { tag . jump ( choice ) ; tag . skipWs ( ) ; if ( tag . peek ( ) == '{' && tag . seekBounds ( choice , '{' , '}' ) ) { recurse ( choice , offsetValue ) ; } return ; } if ( ! tag . seekBounds ( choice , '{' , '}' ) ) { return ; } tag . jump ( choice ) ; tag . skip ( COMMA_WS ) ; } }
PLURAL - Evaluate the argument as a plural either cardinal or ordinal .
5,238
private void evalSelect ( MessageArg arg ) { tag . skip ( COMMA_WS ) ; int pos = - 1 ; int end = - 1 ; String value = arg . asString ( ) ; while ( tag . peek ( ) != Chars . EOF ) { if ( ! tag . seek ( NON_WS , choice ) ) { break ; } String token = choice . token ( ) . toString ( ) ; tag . jump ( choice ) ; tag . skip ( COMMA_WS ) ; if ( ! tag . seekBounds ( choice , '{' , '}' ) ) { break ; } if ( token . equals ( value ) ) { recurse ( choice , value ) ; return ; } else if ( token . equals ( "other" ) ) { pos = choice . pos ; end = choice . end ; } else { tag . jump ( choice ) ; tag . skip ( COMMA_WS ) ; } } if ( pos != - 1 && end != - 1 ) { choice . set ( pos , end ) ; recurse ( choice , value ) ; } }
SELECT - Evaluate the tag that matches the argument s value .
5,239
private void evalNumber ( MessageArg arg ) { initDecimalArgsParser ( ) ; parseArgs ( decimalArgsParser ) ; BigDecimal number = arg . asBigDecimal ( ) ; NumberFormatter formatter = CLDR_INSTANCE . getNumberFormatter ( locale ) ; formatter . formatDecimal ( number , buf , decimalArgsParser . options ( ) ) ; }
NUMBER - Evaluate the argument as a number with options specified as key = value .
5,240
private void evalCurrency ( MessageArg arg ) { String currencyCode = arg . currency ( ) ; if ( currencyCode == null ) { return ; } CLDR . Currency currency = CLDR . Currency . fromString ( currencyCode ) ; if ( currency == null ) { return ; } initCurrencyArgsParser ( ) ; parseArgs ( currencyArgsParser ) ; BigDecimal number = arg . asBigDecimal ( ) ; NumberFormatter formatter = CLDR_INSTANCE . getNumberFormatter ( locale ) ; formatter . formatCurrency ( number , currency , buf , currencyArgsParser . options ( ) ) ; }
CURRENCY - Evaluate the argument as a currency with options specified as key = value .
5,241
private void evalDateTime ( MessageArg arg ) { if ( ! arg . resolve ( ) ) { return ; } initCalendarArgsParser ( ) ; parseArgs ( calendarArgsParser ) ; ZonedDateTime datetime = parseDateTime ( arg ) ; CalendarFormatter formatter = CLDR_INSTANCE . getCalendarFormatter ( locale ) ; formatter . format ( datetime , calendarArgsParser . options ( ) , buf ) ; }
DATETIME - Evaluate the argument as a datetime with options specified as key = value .
5,242
private void evalDateTimeInterval ( List < MessageArg > args ) { int size = args . size ( ) ; if ( size != 2 ) { return ; } for ( int i = 0 ; i < size ; i ++ ) { if ( ! args . get ( i ) . resolve ( ) ) { return ; } } ZonedDateTime start = parseDateTime ( args . get ( 0 ) ) ; ZonedDateTime end = parseDateTime ( args . get ( 1 ) ) ; DateTimeIntervalSkeleton skeleton = null ; tag . skip ( COMMA_WS ) ; if ( tag . seek ( SKELETON , choice ) ) { String skel = choice . toString ( ) ; tag . jump ( choice ) ; skeleton = DateTimeIntervalSkeleton . fromString ( skel ) ; } CalendarFormatter formatter = CLDR_INSTANCE . getCalendarFormatter ( locale ) ; formatter . format ( start , end , skeleton , buf ) ; }
DATETIME - INTERVAL - Evaluate the argument as a date - time interval with an optional skeleton argument .
5,243
private ZonedDateTime parseDateTime ( MessageArg arg ) { long instant = arg . asLong ( ) ; ZoneId timeZone = arg . timeZone ( ) != null ? arg . timeZone ( ) : this . timeZone ; return ZonedDateTime . ofInstant ( Instant . ofEpochMilli ( instant ) , timeZone ) ; }
Parse the argument as a date - time with the format - wide time zone .
5,244
private void emit ( int pos , int end , String arg ) { while ( pos < end ) { char ch = format . charAt ( pos ) ; if ( ch == '#' ) { buf . append ( arg == null ? ch : arg ) ; } else { buf . append ( ch ) ; } pos ++ ; } }
Append characters from raw in the range [ pos end ) to the output buffer .
5,245
public V get ( K key ) { Entry < V > entry = classMap . get ( key ) ; return entry == null ? null : entry . get ( ) ; }
Gets a new instance of the class corresponding to the key .
5,246
public void put ( K key , Class < ? extends V > cls ) { classMap . put ( key , new Entry < > ( cls ) ) ; }
Puts a class into the map .
5,247
protected MetaLocale addLikelySubtags ( MetaLocale src ) { MetaLocale dst = src . copy ( ) ; if ( src . hasAll ( ) ) { return dst ; } MetaLocale temp = src . copy ( ) ; temp . setVariant ( null ) ; for ( int flags : MATCH_ORDER ) { set ( src , temp , flags ) ; MetaLocale match = likelySubtagsMap . get ( temp ) ; if ( match != null ) { if ( ! dst . hasLanguage ( ) ) { dst . setLanguage ( match . _language ( ) ) ; } if ( ! dst . hasScript ( ) ) { dst . setScript ( match . _script ( ) ) ; } if ( ! dst . hasTerritory ( ) ) { dst . setTerritory ( match . _territory ( ) ) ; } break ; } } return dst ; }
Add likely subtags producing the max bundle ID .
5,248
protected MetaLocale removeLikelySubtags ( MetaLocale src ) { MetaLocale temp = new MetaLocale ( ) ; temp . setLanguage ( src . _language ( ) ) ; MetaLocale match = addLikelySubtags ( temp ) ; if ( match . equals ( src ) ) { return temp ; } temp . setTerritory ( src . _territory ( ) ) ; match = addLikelySubtags ( temp ) ; if ( match . equals ( src ) ) { temp . setLanguage ( src . _language ( ) ) ; return temp ; } temp . setTerritory ( null ) ; temp . setScript ( temp . _script ( ) ) ; match = addLikelySubtags ( temp ) ; if ( match . equals ( src ) ) { return temp ; } return src . copy ( ) ; }
Removes all subtags that would be added by addLikelySubtags . This produces the min bundle ID .
5,249
protected static void set ( MetaLocale src , MetaLocale dst , int flags ) { dst . setLanguage ( ( flags & LANGUAGE ) == 0 ? null : src . _language ( ) ) ; dst . setScript ( ( flags & SCRIPT ) == 0 ? null : src . _script ( ) ) ; dst . setTerritory ( ( flags & TERRITORY ) == 0 ? null : src . _territory ( ) ) ; }
Set or clear fields on the destination locale according to the flags .
5,250
private String getPartition ( Set < String > variables ) { String key = buildKey ( variables ) ; return partitionIds . computeIfAbsent ( key , k -> Character . toString ( ( char ) ( BASE_ID + idSequence ++ ) ) ) ; }
Retrieve the partition identifier for this set of matching variables .
5,251
private static String buildKey ( Set < String > variables ) { return variables . stream ( ) . sorted ( ) . collect ( Collectors . joining ( ", " ) ) ; }
Sort the set of variables and join to a comma - delimited string .
5,252
private static < K , V > void makeSetsImmutable ( Map < K , Set < V > > map ) { Set < K > keys = map . keySet ( ) ; for ( K key : keys ) { Set < V > value = map . get ( key ) ; map . put ( key , Collections . unmodifiableSet ( value ) ) ; } }
Convert values to immutable sets .
5,253
public UnitValue convert ( UnitValue value ) { Unit src = value . unit ( ) ; switch ( src . category ( ) ) { case CONCENTR : case LIGHT : break ; case ACCELERATION : return convert ( value , Unit . METER_PER_SECOND_SQUARED , UnitFactors . ACCELERATION ) ; case ANGLE : return convert ( value , UnitFactorSets . ANGLE ) ; case AREA : return convert ( value , areaFactors ( ) ) ; case CONSUMPTION : return convert ( value , consumptionUnit ( ) ) ; case DIGITAL : return convert ( value , UnitFactorSets . DIGITAL_BYTES ) ; case DURATION : return convert ( value , UnitFactorSets . DURATION ) ; case ELECTRIC : return convert ( value , UnitFactorSets . ELECTRIC ) ; case ENERGY : return convert ( value , energyFactors ( ) ) ; case FREQUENCY : return convert ( value , UnitFactorSets . FREQUENCY ) ; case LENGTH : return convert ( value , lengthFactors ( ) ) ; case MASS : return convert ( value , massFactors ( ) ) ; case POWER : return convert ( value , UnitFactorSets . POWER ) ; case PRESSURE : return convert ( value , Unit . MILLIBAR ) ; case SPEED : return convert ( value , speedUnit ( ) ) ; case TEMPERATURE : return convert ( value , temperatureUnit ( ) ) ; case VOLUME : return convert ( value , volumeFactors ( ) ) ; } return value ; }
Convert the given unit value into the best unit for its category relative to the current measurement system .
5,254
public UnitValue convert ( UnitValue value , Unit target ) { Unit src = value . unit ( ) ; UnitCategory category = src . category ( ) ; if ( src == target || category != target . category ( ) ) { return value ; } switch ( category ) { case CONCENTR : case LIGHT : break ; case CONSUMPTION : return consumption ( value , target ) ; case TEMPERATURE : return temperature ( value , target ) ; case VOLUME : if ( measurementSystem == MeasurementSystem . UK ) { return convert ( value , target , UnitFactors . VOLUME_UK ) ; } return convert ( value , target , UnitFactors . VOLUME ) ; default : UnitFactorMap factors = FACTORS_MAP . get ( category ) ; if ( factors != null ) { return convert ( value , target , factors ) ; } break ; } return value ; }
Convert the given unit value into the target unit relative to the current measurement system .
5,255
public UnitValue convert ( UnitValue value , UnitFactorSet factorSet ) { value = convert ( value , factorSet . base ( ) ) ; BigDecimal n = value . amount ( ) ; boolean negative = false ; if ( n . signum ( ) == - 1 ) { negative = true ; n = n . abs ( ) ; } List < UnitValue > factors = factorSet . factors ( ) ; int size = factors . size ( ) ; int last = size - 1 ; for ( int i = 0 ; i < size ; i ++ ) { UnitValue factor = factors . get ( i ) ; BigDecimal divisor = factor . amount ( ) ; if ( divisor == null ) { continue ; } if ( divisor . compareTo ( n ) <= 0 || i == last ) { int scale = n . precision ( ) + divisor . precision ( ) ; n = n . divide ( divisor , scale , RoundingMode . HALF_EVEN ) ; if ( negative ) { n = n . negate ( ) ; } return new UnitValue ( n . stripTrailingZeros ( ) , factor . unit ( ) ) ; } } return value ; }
Convert to the best display unit among the available factors . By best we mean the most compact representation .
5,256
public List < UnitValue > sequence ( UnitValue value , UnitFactorSet factorSet ) { value = convert ( value , factorSet . base ( ) ) ; boolean negative = false ; BigDecimal n = value . amount ( ) ; if ( n . signum ( ) == - 1 ) { negative = true ; n = n . abs ( ) ; } List < UnitValue > result = new ArrayList < > ( ) ; List < UnitValue > factors = factorSet . factors ( ) ; int size = factors . size ( ) ; int last = size - 1 ; for ( int i = 0 ; i < size ; i ++ ) { UnitValue factor = factors . get ( i ) ; BigDecimal divisor = factor . amount ( ) ; if ( divisor == null ) { continue ; } if ( i == last && ( n . compareTo ( BigDecimal . ZERO ) != 0 || result . isEmpty ( ) ) ) { int scale = n . precision ( ) + divisor . precision ( ) ; BigDecimal res = n . divide ( divisor , scale , RoundingMode . HALF_EVEN ) ; if ( negative && result . isEmpty ( ) ) { res = res . negate ( ) ; } result . add ( new UnitValue ( res . stripTrailingZeros ( ) , factor . unit ( ) ) ) ; } else if ( divisor . compareTo ( n ) <= 0 ) { BigDecimal [ ] res = n . divideAndRemainder ( divisor ) ; if ( negative && result . isEmpty ( ) ) { res [ 0 ] = res [ 0 ] . negate ( ) ; } result . add ( new UnitValue ( res [ 0 ] . stripTrailingZeros ( ) , factor . unit ( ) ) ) ; n = res [ 1 ] ; } } return result ; }
Breaks down the unit value into a sequence of units using the given divisors and allowed units .
5,257
private static UnitValue temperature ( UnitValue value , Unit target ) { BigDecimal n = value . amount ( ) ; if ( target == Unit . TEMPERATURE_GENERIC ) { return new UnitValue ( n , Unit . TEMPERATURE_GENERIC ) ; } switch ( value . unit ( ) ) { case FAHRENHEIT : if ( target == Unit . CELSIUS ) { n = n . subtract ( THIRTY_TWO ) ; n = new Rational ( n , BigDecimal . ONE ) . multiply ( FIVE_NINTHS ) . compute ( RoundingMode . HALF_EVEN ) ; } else if ( target == Unit . KELVIN ) { n = n . add ( KELVIN_FAHRENHEIT ) ; n = new Rational ( n , BigDecimal . ONE ) . multiply ( FIVE_NINTHS ) . compute ( RoundingMode . HALF_EVEN ) ; } break ; case CELSIUS : if ( target == Unit . FAHRENHEIT ) { Rational r = new Rational ( n , BigDecimal . ONE ) ; n = r . multiply ( NINE_FIFTHS ) . compute ( RoundingMode . HALF_EVEN ) . add ( THIRTY_TWO ) ; } else if ( target == Unit . KELVIN ) { n = n . add ( KELVIN_CELSIUS ) ; } break ; case KELVIN : if ( target == Unit . CELSIUS ) { n = n . subtract ( KELVIN_CELSIUS ) ; } else if ( target == Unit . FAHRENHEIT ) { Rational r = new Rational ( n , BigDecimal . ONE ) . multiply ( NINE_FIFTHS ) ; n = r . compute ( RoundingMode . HALF_EVEN ) . subtract ( KELVIN_FAHRENHEIT ) ; } break ; default : return new UnitValue ( n , Unit . TEMPERATURE_GENERIC ) ; } return new UnitValue ( n . stripTrailingZeros ( ) , target ) ; }
Temperature conversions .
5,258
public MessageArg get ( int index ) { return index < args . size ( ) ? args . get ( index ) : null ; }
Return a positional argument using a zero - based index or null if not enough arguments exist .
5,259
public MessageArg get ( String name ) { return map == null ? null : map . get ( name ) ; }
Return a named argument or null if does not exist .
5,260
public void add ( String name , MessageArg arg ) { args . add ( arg ) ; if ( map == null ) { map = new HashMap < > ( ) ; } map . put ( name , arg ) ; }
Add a named argument . Also accessible by index .
5,261
public Map < LocaleID , ClassName > generate ( Path outputDir , DataReader reader ) throws IOException { Map < LocaleID , ClassName > numberClasses = new TreeMap < > ( ) ; Map < LocaleID , UnitData > unitMap = reader . units ( ) ; for ( Map . Entry < LocaleID , NumberData > entry : reader . numbers ( ) . entrySet ( ) ) { NumberData data = entry . getValue ( ) ; LocaleID localeId = entry . getKey ( ) ; String className = "_NumberFormatter_" + localeId . safe ; UnitData unitData = unitMap . get ( localeId ) ; TypeSpec type = create ( data , unitData , className ) ; CodeGenerator . saveClass ( outputDir , PACKAGE_CLDR_NUMBERS , className , type ) ; ClassName cls = ClassName . get ( PACKAGE_CLDR_NUMBERS , className ) ; numberClasses . put ( localeId , cls ) ; } String className = "_CurrencyUtil" ; TypeSpec type = createCurrencyUtil ( className , reader . currencies ( ) ) ; CodeGenerator . saveClass ( outputDir , PACKAGE_CLDR_NUMBERS , className , type ) ; return numberClasses ; }
Generate all number formatting classes .
5,262
private TypeSpec create ( NumberData data , UnitData unitData , String className ) { LocaleID id = data . id ( ) ; TypeSpec . Builder type = TypeSpec . classBuilder ( className ) . superclass ( NUMBER_FORMATTER_BASE ) . addModifiers ( Modifier . PUBLIC ) ; String fmt = "super(\n" ; List < Object > args = new ArrayList < > ( ) ; fmt += "$T.$L,\n" ; args . add ( CLDR_LOCALE_IF ) ; args . add ( id . safe ) ; fmt += "new _Params(),\n" ; fmt += "// decimal standard\n" ; fmt += "patterns($S, $S),\n" ; args . addAll ( getPatterns ( data . decimalFormatStandard ) ) ; fmt += "// percent standard\n" ; fmt += "patterns($S, $S),\n" ; args . addAll ( getPatterns ( data . percentFormatStandard ) ) ; fmt += "// currency standard\n" ; fmt += "patterns($S, $S),\n" ; args . addAll ( getPatterns ( data . currencyFormatStandard ) ) ; fmt += "// currency accounting\n" ; fmt += "patterns($S, $S),\n" ; args . addAll ( getPatterns ( data . currencyFormatAccounting ) ) ; fmt += "// units standard\n" ; fmt += "patterns($S, $S)\n" ; List < NumberPattern > unitPatterns = data . decimalFormatStandard . stream ( ) . map ( p -> { p = NUMBER_PARSER . parse ( p . render ( ) ) ; p . format ( ) . setMaximumFractionDigits ( 1 ) ; p . format ( ) . setMinimumFractionDigits ( 0 ) ; return p ; } ) . collect ( Collectors . toList ( ) ) ; args . addAll ( getPatterns ( unitPatterns ) ) ; fmt += ")" ; MethodSpec . Builder code = MethodSpec . constructorBuilder ( ) . addModifiers ( PUBLIC ) . addStatement ( fmt , args . toArray ( ) ) ; type . addMethod ( code . build ( ) ) ; addParams ( type , id , data ) ; addCompactPattern ( type , "DECIMAL_SHORT" , data . decimalFormatShort , false , data ) ; addCompactPattern ( type , "DECIMAL_LONG" , data . decimalFormatLong , false , data ) ; addCompactPattern ( type , "CURRENCY_SHORT" , data . currencyFormatShort , true , data ) ; addUnitPattern ( type , "UNITS_LONG" , unitData . long_ ) ; addUnitPattern ( type , "UNITS_NARROW" , unitData . narrow ) ; addUnitPattern ( type , "UNITS_SHORT" , unitData . short_ ) ; addCurrencyInfo ( type , data ) ; addUnitWrappers ( type , data ) ; return type . build ( ) ; }
Creates a number formatter class .
5,263
public TypeSpec createCurrencyUtil ( String className , Map < String , CurrencyData > currencies ) { TypeSpec . Builder type = TypeSpec . classBuilder ( className ) . addModifiers ( Modifier . PUBLIC ) ; CurrencyData defaultData = currencies . get ( "DEFAULT" ) ; currencies . remove ( "DEFAULT" ) ; MethodSpec . Builder code = MethodSpec . methodBuilder ( "getCurrencyDigits" ) . addModifiers ( PUBLIC , STATIC ) . addParameter ( Types . CLDR_CURRENCY_ENUM , "code" ) . returns ( int . class ) ; code . beginControlFlow ( "switch (code)" ) ; for ( Map . Entry < String , CurrencyData > entry : currencies . entrySet ( ) ) { CurrencyData data = entry . getValue ( ) ; code . addStatement ( "case $L: return $L" , entry . getKey ( ) , data . digits ) ; } code . addStatement ( "default: return $L" , defaultData . digits ) ; code . endControlFlow ( ) ; type . addMethod ( code . build ( ) ) ; return type . build ( ) ; }
Create class to hold global currency information .
5,264
private List < String > getPatterns ( List < NumberPattern > patterns ) { return patterns . stream ( ) . map ( p -> p . render ( ) ) . collect ( Collectors . toList ( ) ) ; }
Return a list of the string patterns embedded in the NumberPattern instances .
5,265
private void addParams ( TypeSpec . Builder parent , LocaleID id , NumberData data ) { MethodSpec . Builder code = MethodSpec . constructorBuilder ( ) ; code . addStatement ( "this.decimal = $S" , data . decimal ) ; code . addStatement ( "this.group = $S" , data . group ) ; code . addStatement ( "this.percent = $S" , data . percent ) ; code . addStatement ( "this.minus = $S" , data . minus ) ; code . addStatement ( "this.plus = $S" , data . plus ) ; code . addStatement ( "this.exponential = $S" , data . exponential ) ; code . addStatement ( "this.superscriptingExponent = $S" , data . superscriptingExponent ) ; code . addStatement ( "this.perMille = $S" , data . perMille ) ; code . addStatement ( "this.infinity = $S" , data . infinity ) ; code . addStatement ( "this.nan = $S" , data . nan ) ; code . addStatement ( "this.currencyDecimal = $S" , data . currencyDecimal ) ; code . addStatement ( "this.currencyGroup = $S" , data . currencyGroup ) ; TypeSpec . Builder params = TypeSpec . classBuilder ( "_Params" ) . superclass ( NumberFormatterParams . class ) . addModifiers ( PRIVATE , STATIC ) . addMethod ( code . build ( ) ) ; parent . addType ( params . build ( ) ) ; }
Construct s the locale s number formatter params .
5,266
private void addCurrencyInfo ( TypeSpec . Builder type , NumberData data ) { addCurrencyInfoMethod ( type , "getCurrencySymbol" , data . currencySymbols ) ; addCurrencyInfoMethod ( type , "getNarrowCurrencySymbol" , data . narrowCurrencySymbols ) ; addCurrencyInfoMethod ( type , "getCurrencyDisplayName" , data . currencyDisplayName ) ; MethodSpec . Builder method = MethodSpec . methodBuilder ( "getCurrencyPluralName" ) . addModifiers ( PROTECTED ) . addParameter ( Types . CLDR_CURRENCY_ENUM , "code" ) . addParameter ( PluralCategory . class , "category" ) . returns ( String . class ) ; method . beginControlFlow ( "switch (code)" ) ; for ( Map . Entry < String , Map < String , String > > currencyMap : data . currencyDisplayNames . entrySet ( ) ) { String code = currencyMap . getKey ( ) ; Map < String , String > mapping = currencyMap . getValue ( ) ; if ( mapping . isEmpty ( ) ) { continue ; } method . beginControlFlow ( "case $L:" , code ) ; method . beginControlFlow ( "switch (category)" ) ; for ( Map . Entry < String , String > entry : mapping . entrySet ( ) ) { String [ ] parts = entry . getKey ( ) . split ( "-" ) ; PluralCategory category = PluralCategory . fromString ( parts [ 2 ] ) ; if ( category == PluralCategory . OTHER ) { method . addStatement ( "case $L:\ndefault: return $S" , category , entry . getValue ( ) ) ; } else { method . addStatement ( "case $L: return $S" , category , entry . getValue ( ) ) ; } } method . endControlFlow ( ) ; method . endControlFlow ( ) ; } method . addStatement ( "default: return $S" , "" ) ; method . endControlFlow ( ) ; type . addMethod ( method . build ( ) ) ; method = MethodSpec . methodBuilder ( "getCurrencyDigits" ) . addModifiers ( PUBLIC ) . addParameter ( Types . CLDR_CURRENCY_ENUM , "code" ) . returns ( int . class ) ; method . addStatement ( "return _CurrencyUtil.getCurrencyDigits(code)" ) ; type . addMethod ( method . build ( ) ) ; }
Adds methods to return information about a currency .
5,267
private void addCurrencyInfoMethod ( TypeSpec . Builder type , String name , Map < String , String > mapping ) { MethodSpec . Builder method = MethodSpec . methodBuilder ( name ) . addModifiers ( PUBLIC ) . addParameter ( Types . CLDR_CURRENCY_ENUM , "code" ) . returns ( String . class ) ; method . beginControlFlow ( "if (code == null)" ) ; method . addStatement ( "return $S" , "" ) ; method . endControlFlow ( ) ; method . beginControlFlow ( "switch (code)" ) ; for ( Map . Entry < String , String > entry : mapping . entrySet ( ) ) { String key = entry . getKey ( ) ; String val = entry . getValue ( ) ; if ( ! key . equals ( val ) ) { method . addStatement ( "case $L: return $S" , key , val ) ; } } method . addStatement ( "default: return code.name()" ) ; method . endControlFlow ( ) ; type . addMethod ( method . build ( ) ) ; }
Adds a method to return the symbol or display name for a currency .
5,268
private static void buildMatchVariables ( TypeSpec . Builder type , Map < String , Set < String > > territoryData , LanguageMatchingData data ) { Map < String , Set < String > > territories = flatten ( territoryData ) ; CodeBlock . Builder code = CodeBlock . builder ( ) ; code . add ( "new $T<$T, $T<$T>>() {{\n" , HASHMAP , STRING , SET , STRING ) ; for ( Map . Entry < String , Set < String > > entry : territories . entrySet ( ) ) { code . add ( " put($S, new $T<>(" , entry . getKey ( ) , HASHSET ) ; List < String > list = new ArrayList < > ( entry . getValue ( ) ) ; Collections . sort ( list ) ; addStringList ( code , list , " " ) ; code . add ( "));\n" ) ; } code . add ( "\n}}" ) ; TypeName typeName = ParameterizedTypeName . get ( MAP , STRING , SET_STRING ) ; type . addField ( FieldSpec . builder ( typeName , "TERRITORIES" , PROTECTED , STATIC , FINAL ) . initializer ( code . build ( ) ) . build ( ) ) ; Map < String , Set < String > > variables = new LinkedHashMap < > ( ) ; for ( Pair < String , String > pair : data . matchVariables ) { String variable = pair . _1 ; Set < String > countries = new HashSet < > ( ) ; for ( String regionId : pair . _2 . split ( "\\+" ) ) { Set < String > children = territories . get ( regionId ) ; if ( children != null ) { countries . addAll ( children ) ; } else { countries . add ( regionId ) ; } } variables . put ( variable , countries ) ; } code = CodeBlock . builder ( ) ; code . add ( "new $T<$T, $T<$T>>() {{\n" , HASHMAP , STRING , SET , STRING ) ; for ( Map . Entry < String , Set < String > > entry : variables . entrySet ( ) ) { code . add ( " put($S, new $T<>(" , entry . getKey ( ) , HASHSET ) ; List < String > list = new ArrayList < > ( entry . getValue ( ) ) ; Collections . sort ( list ) ; addStringList ( code , list , " " ) ; code . add ( "));\n" ) ; } code . add ( "\n}}" ) ; type . addField ( FieldSpec . builder ( typeName , "VARIABLES" , PROTECTED , STATIC , FINAL ) . initializer ( code . build ( ) ) . build ( ) ) ; }
Build table containing language matching variables .
5,269
private static Map < String , Set < String > > flatten ( Map < String , Set < String > > data ) { Map < String , Set < String > > territories = new TreeMap < > ( ) ; Set < String > keys = data . keySet ( ) ; for ( String key : keys ) { Set < String > values = flatten ( key , territories , data ) ; territories . put ( key , values ) ; } return territories ; }
Flatten the territory containment hierarchy .
5,270
private static Set < String > flatten ( String parent , Map < String , Set < String > > flat , Map < String , Set < String > > data ) { Set < String > countries = new LinkedHashSet < > ( ) ; Set < String > keys = data . get ( parent ) ; if ( keys == null ) { return countries ; } for ( String region : keys ) { if ( data . containsKey ( region ) ) { Set < String > children = flatten ( region , flat , data ) ; flat . put ( region , children ) ; countries . addAll ( children ) ; } else { countries . add ( region ) ; } } return countries ; }
Flatten one level of the territory containment hierarchy .
5,271
private static void addStringList ( CodeBlock . Builder code , List < String > list , String indent ) { int size = list . size ( ) ; code . add ( "$T.asList(\n$L" , Arrays . class , indent ) ; int width = indent . length ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( i != 0 ) { code . add ( ", " ) ; width += 2 ; } if ( width > 80 ) { width = indent . length ( ) ; code . add ( "\n$L" , indent ) ; } String element = list . get ( i ) ; code . add ( "$S" , element ) ; width += element . length ( ) + 2 ; } code . add ( "\n$L)" , indent ) ; }
Helper to add a list of strings to a code block .
5,272
public NumberPattern parse ( String raw ) { this . buf . setLength ( 0 ) ; this . nodes = new ArrayList < > ( ) ; this . attached = false ; this . format = new Format ( ) ; int length = raw . length ( ) ; int i = 0 ; boolean inGroup = false ; boolean inDecimal = false ; while ( i < length ) { char ch = raw . charAt ( i ) ; switch ( ch ) { case '\'' : while ( i ++ < length ) { ch = raw . charAt ( i ) ; if ( ch == '\'' ) { break ; } buf . append ( ch ) ; } break ; case '-' : pushText ( ) ; nodes . add ( NumberPattern . Symbol . MINUS ) ; break ; case '%' : pushText ( ) ; nodes . add ( NumberPattern . Symbol . PERCENT ) ; break ; case '\u00a4' : pushText ( ) ; nodes . add ( NumberPattern . Symbol . CURRENCY ) ; break ; case '#' : attach ( ) ; if ( inGroup ) { format . primaryGroupingSize ++ ; } else if ( inDecimal ) { format . maximumFractionDigits ++ ; } break ; case ',' : attach ( ) ; if ( inGroup ) { format . secondaryGroupingSize = format . primaryGroupingSize ; format . primaryGroupingSize = 0 ; } else { inGroup = true ; } break ; case '.' : inGroup = false ; attach ( ) ; inDecimal = true ; break ; case '0' : attach ( ) ; if ( inGroup ) { format . primaryGroupingSize ++ ; } else if ( inDecimal ) { format . minimumFractionDigits ++ ; format . maximumFractionDigits ++ ; } if ( ! inDecimal ) { format . minimumIntegerDigits ++ ; } break ; default : buf . append ( ch ) ; break ; } i ++ ; } pushText ( ) ; return new NumberPattern ( raw , nodes , format ) ; }
Parse a number formatting pattern .
5,273
private void pushText ( ) { if ( buf . length ( ) > 0 ) { nodes . add ( new NumberPattern . Text ( buf . toString ( ) ) ) ; buf . setLength ( 0 ) ; } }
If the buffer is not empty push it onto the node list and reset it .
5,274
public CLDR . Locale fromJavaLocale ( java . util . Locale javaLocale ) { return MetaLocale . fromJavaLocale ( javaLocale ) ; }
Convert the Java locale to a CLDR locale object .
5,275
public CLDR . Locale minimize ( CLDR . Locale locale ) { return languageResolver . removeLikelySubtags ( ( MetaLocale ) locale ) ; }
Produce the minimal representation of this locale by removing likely subtags .
5,276
public CalendarFormatter getCalendarFormatter ( CLDR . Locale locale ) { locale = bundleMatch ( locale ) ; CalendarFormatter formatter = CALENDAR_FORMATTERS . get ( locale ) ; return formatter == null ? CALENDAR_FORMATTERS . get ( CLDR . Locale . en_US ) : formatter ; }
Returns a calendar formatter for the given locale translating it before lookup .
5,277
public NumberFormatter getNumberFormatter ( CLDR . Locale locale ) { locale = bundleMatch ( locale ) ; NumberFormatter formatter = NUMBER_FORMATTERS . get ( locale ) ; return formatter == null ? NUMBER_FORMATTERS . get ( CLDR . Locale . en_US ) : formatter ; }
Returns a number formatter for the given locale translating it before lookup .
5,278
protected static void addLanguageAlias ( String rawType , String rawReplacement ) { LanguageAlias type = LanguageAlias . parse ( rawType ) ; LanguageAlias replacement = LanguageAlias . parse ( rawReplacement ) ; String language = type . language ( ) ; List < Pair < LanguageAlias , LanguageAlias > > aliases = LANGUAGE_ALIAS_MAP . get ( language ) ; if ( aliases == null ) { aliases = new ArrayList < > ( ) ; LANGUAGE_ALIAS_MAP . put ( language , aliases ) ; } aliases . add ( Pair . pair ( type , replacement ) ) ; }
Add a language alias entry .
5,279
protected CLDR . Locale bundleMatch ( CLDR . Locale locale ) { locale = DEFAULT_CONTENT . getOrDefault ( locale , locale ) ; return bundleMatcher . match ( ( MetaLocale ) locale ) ; }
Locate the correct bundle identifier for the given resolved locale . Note that the bundle identifier is not terribly useful outside of the CLDR library since it may in many cases carry incomplete information for the intended public locale . For example the bundle used for en - Latn - US is en which is missing critical subtags and as such should not be used to identify the en - Latn - US locale .
5,280
public DigitBuffer append ( String s ) { int len = s . length ( ) ; check ( len ) ; for ( int i = 0 ; i < len ; i ++ ) { this . buf [ size ] = s . charAt ( i ) ; size ++ ; } return this ; }
Append a string to the buffer expanding it if necessary .
5,281
public void append ( DigitBuffer other ) { check ( other . size ) ; System . arraycopy ( other . buf , 0 , buf , size , other . size ) ; size += other . size ; }
Append the contents of the other buffer to this one .
5,282
public void reverse ( int start ) { int end = size - 1 ; int num = end - start >> 1 ; for ( int i = 0 ; i <= num ; i ++ ) { int j = start + i ; int k = end - i ; char c = buf [ k ] ; buf [ k ] = buf [ j ] ; buf [ j ] = c ; } }
Reverse all characters from start to end of buffer .
5,283
private void check ( int length ) { if ( size + length >= buf . length ) { buf = Arrays . copyOf ( buf , buf . length + length + 16 ) ; } }
Ensure the buffer is large enough for the next append .
5,284
public static DataReader get ( ) throws IOException { if ( ! instance . initialized ) { long start = System . currentTimeMillis ( ) ; instance . init ( ) ; long elapsed = System . currentTimeMillis ( ) - start ; System . out . printf ( "Loaded CLDR data in %d ms.\n" , elapsed ) ; } return instance ; }
Returns the global DataReader instance populating it if necessary .
5,285
private void loadPatches ( ) throws IOException { List < Path > paths = Utils . listResources ( PATCHES ) ; for ( Path path : paths ) { String fileName = path . getFileName ( ) . toString ( ) ; if ( fileName . endsWith ( ".json" ) ) { JsonObject root = load ( path ) ; patches . put ( fileName , root ) ; } } }
Load patches which override values in the CLDR data . Use this to restore certain cases to our preferred form .
5,286
private JsonObject patch ( String fileName , String code , JsonObject root ) { for ( Map . Entry < String , JsonObject > entry : patches . entrySet ( ) ) { JsonObject patch = entry . getValue ( ) ; if ( ! patch . get ( "filename" ) . getAsString ( ) . equals ( fileName ) ) { continue ; } JsonArray locales = patch . getAsJsonArray ( "locales" ) ; boolean shouldPatch = false ; if ( code == null ) { shouldPatch = true ; } else { for ( JsonElement locale : locales ) { if ( locale . getAsString ( ) . equals ( code ) ) { shouldPatch = true ; break ; } } } if ( ! shouldPatch ) { return root ; } JsonObject src = resolve ( patch , "patch" ) ; JsonObject dst = root ; if ( patch . get ( "type" ) . getAsString ( ) . equals ( "main" ) ) { dst = resolve ( root , "main" , code ) ; } System . out . printf ( "Applying patch %s to %s\n" , entry . getKey ( ) , code ) ; patchObject ( src , dst ) ; } return root ; }
Apply a patch to the given filename if applicable .
5,287
private void patchObject ( JsonObject src , JsonObject dst ) { for ( String key : objectKeys ( src ) ) { JsonElement se = src . get ( key ) ; JsonElement de = dst . get ( key ) ; if ( de == null ) { continue ; } if ( se . isJsonObject ( ) && de . isJsonObject ( ) ) { patchObject ( se . getAsJsonObject ( ) , de . getAsJsonObject ( ) ) ; continue ; } if ( se . isJsonPrimitive ( ) && de . isJsonPrimitive ( ) ) { dst . add ( key , se ) ; } } }
Overlay nested values from src on top of dst .
5,288
private void sanityCheck ( List < Path > resources ) { Set < String > fileNames = resources . stream ( ) . map ( p -> p . getFileName ( ) . toString ( ) ) . collect ( Collectors . toSet ( ) ) ; for ( String name : FILENAMES_MUST_EXIST ) { if ( ! fileNames . contains ( name ) ) { String msg = String . format ( "CLDR DATA MISSING! Can't find '%s'. " + " You may need to run 'git submodule update'" , name ) ; throw new RuntimeException ( msg ) ; } } }
Blow up if required paths do not exist .
5,289
private JsonObject load ( Path path ) throws IOException { try ( InputStream stream = Resources . getResource ( path . toString ( ) ) . openStream ( ) ) { return ( JsonObject ) JSON_PARSER . parse ( new InputStreamReader ( stream ) ) ; } }
Loads and parses a JSON file returning a reference to its root object node .
5,290
private LocaleID parseIdentity ( String code , JsonObject root ) throws IOException { JsonObject node = resolve ( root , "main" , code , "identity" ) ; return new LocaleID ( string ( node , "language" ) , string ( node , "script" ) , string ( node , "territory" ) , string ( node , "variant" ) ) ; }
Parse the locale identity header from a calendar JSON tree .
5,291
private void parseLikelySubtags ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "likelySubtags" ) ; for ( Map . Entry < String , JsonElement > entry : node . entrySet ( ) ) { likelySubtags . put ( entry . getKey ( ) , entry . getValue ( ) . getAsString ( ) ) ; } }
Parse likely subtags tree .
5,292
private void parseLanguageMatchingFix ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "languageMatching" , "written_new" ) ; JsonArray matches = node . getAsJsonArray ( "languageMatch" ) ; for ( JsonElement element : matches ) { JsonObject value = ( JsonObject ) element ; String desired = string ( value , "desired" ) ; String supported = string ( value , "supported" ) ; Integer distance = Integer . parseInt ( string ( value , "distance" ) ) ; boolean oneway = string ( value , "oneway" , null ) != null ; LanguageMatch match = new LanguageMatch ( desired , supported , distance , oneway ) ; languageMatching . languageMatches . add ( match ) ; } JsonObject variables = resolve ( node , "matchVariable" ) ; for ( Map . Entry < String , JsonElement > entry : variables . entrySet ( ) ) { String value = entry . getValue ( ) . getAsString ( ) ; languageMatching . matchVariables . add ( Pair . pair ( entry . getKey ( ) , value ) ) ; } for ( String code : string ( node , "paradigmLocales" ) . split ( "\\s+" ) ) { languageMatching . paradigmLocales . add ( code ) ; } }
Parse enhanced language matching fix tree .
5,293
private void parseTerritoryContainment ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "territoryContainment" ) ; for ( Map . Entry < String , JsonElement > entry : node . entrySet ( ) ) { String parentCode = entry . getKey ( ) ; if ( parentCode . contains ( "-" ) ) { if ( ! parentCode . endsWith ( "-status-grouping" ) ) { continue ; } parentCode = parentCode . split ( "-" ) [ 0 ] ; } JsonObject value = entry . getValue ( ) . getAsJsonObject ( ) ; JsonArray elements = ( JsonArray ) value . get ( "_contains" ) ; if ( elements == null ) { throw new RuntimeException ( "Unexpected object structure: " + value ) ; } List < String > children = new ArrayList < > ( ) ; for ( JsonElement element : elements ) { String code = element . getAsString ( ) ; children . add ( code ) ; } Set < String > regions = territoryContainment . get ( parentCode ) ; if ( regions == null ) { regions = new TreeSet < > ( ) ; territoryContainment . put ( parentCode , regions ) ; } regions . addAll ( children ) ; } }
Parse territory containment tree .
5,294
private DateTimeData parseCalendar ( JsonObject root ) throws IOException { DateTimeData data = new DateTimeData ( ) ; JsonObject node = resolve ( root , "dates" , "calendars" , "gregorian" ) ; data . eras = parseEras ( node ) ; data . dayPeriodsFormat = parseDayPeriods ( node , "format" ) ; data . dayPeriodsStandalone = parseDayPeriods ( node , "stand-alone" ) ; data . monthsFormat = parseMonths ( node , "format" ) ; data . monthsStandalone = parseMonths ( node , "stand-alone" ) ; data . weekdaysFormat = parseWeekdays ( node , "format" ) ; data . weekdaysStandalone = parseWeekdays ( node , "stand-alone" ) ; data . quartersFormat = parseQuarters ( node , "format" ) ; data . quartersStandalone = parseQuarters ( node , "stand-alone" ) ; data . dateFormats = parseDateFormats ( node ) ; data . timeFormats = parseTimeFormats ( node ) ; data . dateTimeFormats = parseDateTimeFormats ( node ) ; data . dateTimeSkeletons = parseDateTimeSkeletons ( node ) ; data . intervalFormats = new HashMap < > ( ) ; node = resolve ( node , "dateTimeFormats" , "intervalFormats" ) ; for ( String key : objectKeys ( node ) ) { if ( key . equals ( "intervalFormatFallback" ) ) { data . intervalFallbackFormat = string ( node , key ) ; } else { Map < String , String > format = data . intervalFormats . get ( key ) ; if ( format == null ) { format = new HashMap < > ( ) ; data . intervalFormats . put ( key , format ) ; } JsonObject fieldNode = node . getAsJsonObject ( key ) ; for ( String field : objectKeys ( fieldNode ) ) { if ( ! field . endsWith ( "-alt-variant" ) ) { format . put ( field , string ( fieldNode , field ) ) ; } } } } return data ; }
Parse calendar date - time attributes .
5,295
private Format parseDateFormats ( JsonObject calendar ) { JsonObject node = resolve ( calendar , "dateFormats" ) ; return new Format ( string ( node , "short" ) , string ( node , "medium" ) , string ( node , "long" ) , string ( node , "full" ) ) ; }
Parse standard date formats of varying sizes .
5,296
private Format parseTimeFormats ( JsonObject calendar ) { JsonObject node = resolve ( calendar , "timeFormats" ) ; return new Format ( string ( node , "short" ) , string ( node , "medium" ) , string ( node , "long" ) , string ( node , "full" ) ) ; }
Parse standard time formats of varying sizes .
5,297
private Format parseDateTimeFormats ( JsonObject calendar ) { JsonObject node = resolve ( calendar , "dateTimeFormats" ) ; return new Format ( string ( node , "short" ) , string ( node , "medium" ) , string ( node , "long" ) , string ( node , "full" ) ) ; }
Parse standard date - time wrapper formats of varying sizes .
5,298
private List < Skeleton > parseDateTimeSkeletons ( JsonObject calendar ) { JsonObject node = resolve ( calendar , "dateTimeFormats" , "availableFormats" ) ; List < Skeleton > value = new ArrayList < > ( ) ; for ( String key : objectKeys ( node ) ) { value . add ( new Skeleton ( key , string ( node , key ) ) ) ; } return value ; }
Parse date - time skeletons .
5,299
private Map < String , Integer > parseMinDays ( JsonObject root ) { JsonObject node = resolve ( root , "supplemental" , "weekData" , "minDays" ) ; Map < String , Integer > m = new HashMap < > ( ) ; for ( String key : objectKeys ( node ) ) { m . put ( key , Integer . valueOf ( string ( node , key ) ) ) ; } return m ; }
Parse the min days values . This indicates the minimum number of days a week must include for it to be counted as the first week of the year ; otherwise it s the last week of the previous year .