1 /* GENERATED SOURCE. DO NOT MODIFY. */ 2 // © 2016 and later: Unicode, Inc. and others. 3 // License & terms of use: http://www.unicode.org/copyright.html#License 4 /** 5 ******************************************************************************* 6 * Copyright (C) 2001-2016, International Business Machines Corporation and 7 * others. All Rights Reserved. 8 ******************************************************************************* 9 */ 10 package android.icu.impl; 11 12 import java.util.ArrayList; 13 import java.util.Collections; 14 import java.util.Comparator; 15 import java.util.EventListener; 16 import java.util.HashMap; 17 import java.util.HashSet; 18 import java.util.Iterator; 19 import java.util.List; 20 import java.util.ListIterator; 21 import java.util.Map; 22 import java.util.Map.Entry; 23 import java.util.Set; 24 import java.util.SortedMap; 25 import java.util.TreeMap; 26 import java.util.concurrent.ConcurrentHashMap; 27 28 import android.icu.util.ULocale; 29 import android.icu.util.ULocale.Category; 30 31 /** 32 * <p>A Service provides access to service objects that implement a 33 * particular service, e.g. transliterators. Users provide a String 34 * id (for example, a locale string) to the service, and get back an 35 * object for that id. Service objects can be any kind of object. 36 * The service object is cached and returned for later queries, so 37 * generally it should not be mutable, or the caller should clone the 38 * object before modifying it.</p> 39 * 40 * <p>Services 'canonicalize' the query id and use the canonical id to 41 * query for the service. The service also defines a mechanism to 42 * 'fallback' the id multiple times. Clients can optionally request 43 * the actual id that was matched by a query when they use an id to 44 * retrieve a service object.</p> 45 * 46 * <p>Service objects are instantiated by Factory objects registered with 47 * the service. The service queries each Factory in turn, from most recently 48 * registered to earliest registered, until one returns a service object. 49 * If none responds with a service object, a fallback id is generated, 50 * and the process repeats until a service object is returned or until 51 * the id has no further fallbacks.</p> 52 * 53 * <p>Factories can be dynamically registered and unregistered with the 54 * service. When registered, a Factory is installed at the head of 55 * the factory list, and so gets 'first crack' at any keys or fallback 56 * keys. When unregistered, it is removed from the service and can no 57 * longer be located through it. Service objects generated by this 58 * factory and held by the client are unaffected.</p> 59 * 60 * <p>ICUService uses Keys to query factories and perform 61 * fallback. The Key defines the canonical form of the id, and 62 * implements the fallback strategy. Custom Keys can be defined that 63 * parse complex IDs into components that Factories can more easily 64 * use. The Key can cache the results of this parsing to save 65 * repeated effort. ICUService provides convenience APIs that 66 * take Strings and generate default Keys for use in querying.</p> 67 * 68 * <p>ICUService provides API to get the list of ids publicly 69 * supported by the service (although queries aren't restricted to 70 * this list). This list contains only 'simple' IDs, and not fully 71 * unique ids. Factories are associated with each simple ID and 72 * the responsible factory can also return a human-readable localized 73 * version of the simple ID, for use in user interfaces. ICUService 74 * can also provide a sorted collection of the all the localized visible 75 * ids.</p> 76 * 77 * <p>ICUService implements ICUNotifier, so that clients can register 78 * to receive notification when factories are added or removed from 79 * the service. ICUService provides a default EventListener subinterface, 80 * ServiceListener, which can be registered with the service. When 81 * the service changes, the ServiceListener's serviceChanged method 82 * is called, with the service as the only argument.</p> 83 * 84 * <p>The ICUService API is both rich and generic, and it is expected 85 * that most implementations will statically 'wrap' ICUService to 86 * present a more appropriate API-- for example, to declare the type 87 * of the objects returned from get, to limit the factories that can 88 * be registered with the service, or to define their own listener 89 * interface with a custom callback method. They might also customize 90 * ICUService by overriding it, for example, to customize the Key and 91 * fallback strategy. ICULocaleService is a customized service that 92 * uses Locale names as ids and uses Keys that implement the standard 93 * resource bundle fallback strategy.<p> 94 * @hide Only a subset of ICU is exposed in Android 95 */ 96 public class ICUService extends ICUNotifier { 97 /** 98 * Name used for debugging. 99 */ 100 protected final String name; 101 102 /** 103 * Constructor. 104 */ ICUService()105 public ICUService() { 106 name = ""; 107 } 108 109 private static final boolean DEBUG = ICUDebug.enabled("service"); 110 /** 111 * Construct with a name (useful for debugging). 112 */ ICUService(String name)113 public ICUService(String name) { 114 this.name = name; 115 } 116 117 /** 118 * Access to factories is protected by a read-write lock. This is 119 * to allow multiple threads to read concurrently, but keep 120 * changes to the factory list atomic with respect to all readers. 121 */ 122 private final ICURWLock factoryLock = new ICURWLock(); 123 124 /** 125 * All the factories registered with this service. 126 */ 127 private final List<Factory> factories = new ArrayList<Factory>(); 128 129 /** 130 * Record the default number of factories for this service. 131 * Can be set by markDefault. 132 */ 133 private int defaultSize = 0; 134 135 /** 136 * Keys are used to communicate with factories to generate an 137 * instance of the service. Keys define how ids are 138 * canonicalized, provide both a current id and a current 139 * descriptor to use in querying the cache and factories, and 140 * determine the fallback strategy.</p> 141 * 142 * <p>Keys provide both a currentDescriptor and a currentID. 143 * The descriptor contains an optional prefix, followed by '/' 144 * and the currentID. Factories that handle complex keys, 145 * for example number format factories that generate multiple 146 * kinds of formatters for the same locale, use the descriptor 147 * to provide a fully unique identifier for the service object, 148 * while using the currentID (in this case, the locale string), 149 * as the visible IDs that can be localized. 150 * 151 * <p> The default implementation of Key has no fallbacks and 152 * has no custom descriptors.</p> 153 * @hide Only a subset of ICU is exposed in Android 154 */ 155 public static class Key { 156 private final String id; 157 158 /** 159 * Construct a key from an id. 160 */ Key(String id)161 public Key(String id) { 162 this.id = id; 163 } 164 165 /** 166 * Return the original ID used to construct this key. 167 */ id()168 public final String id() { 169 return id; 170 } 171 172 /** 173 * Return the canonical version of the original ID. This implementation 174 * returns the original ID unchanged. 175 */ canonicalID()176 public String canonicalID() { 177 return id; 178 } 179 180 /** 181 * Return the (canonical) current ID. This implementation 182 * returns the canonical ID. 183 */ currentID()184 public String currentID() { 185 return canonicalID(); 186 } 187 188 /** 189 * Return the current descriptor. This implementation returns 190 * the current ID. The current descriptor is used to fully 191 * identify an instance of the service in the cache. A 192 * factory may handle all descriptors for an ID, or just a 193 * particular descriptor. The factory can either parse the 194 * descriptor or use custom API on the key in order to 195 * instantiate the service. 196 */ currentDescriptor()197 public String currentDescriptor() { 198 return "/" + currentID(); 199 } 200 201 /** 202 * If the key has a fallback, modify the key and return true, 203 * otherwise return false. The current ID will change if there 204 * is a fallback. No currentIDs should be repeated, and fallback 205 * must eventually return false. This implmentation has no fallbacks 206 * and always returns false. 207 */ fallback()208 public boolean fallback() { 209 return false; 210 } 211 212 /** 213 * If a key created from id would eventually fallback to match the 214 * canonical ID of this key, return true. 215 */ isFallbackOf(String idToCheck)216 public boolean isFallbackOf(String idToCheck) { 217 return canonicalID().equals(idToCheck); 218 } 219 } 220 221 /** 222 * Factories generate the service objects maintained by the 223 * service. A factory generates a service object from a key, 224 * updates id->factory mappings, and returns the display name for 225 * a supported id. 226 * @hide Only a subset of ICU is exposed in Android 227 */ 228 public static interface Factory { 229 230 /** 231 * Create a service object from the key, if this factory 232 * supports the key. Otherwise, return null. 233 * 234 * <p>If the factory supports the key, then it can call 235 * the service's getKey(Key, String[], Factory) method 236 * passing itself as the factory to get the object that 237 * the service would have created prior to the factory's 238 * registration with the service. This can change the 239 * key, so any information required from the key should 240 * be extracted before making such a callback. 241 */ create(Key key, ICUService service)242 public Object create(Key key, ICUService service); 243 244 /** 245 * Update the result IDs (not descriptors) to reflect the IDs 246 * this factory handles. This function and getDisplayName are 247 * used to support ICUService.getDisplayNames. Basically, the 248 * factory has to determine which IDs it will permit to be 249 * available, and of those, which it will provide localized 250 * display names for. In most cases this reflects the IDs that 251 * the factory directly supports. 252 */ updateVisibleIDs(Map<String, Factory> result)253 public void updateVisibleIDs(Map<String, Factory> result); 254 255 /** 256 * Return the display name for this id in the provided locale. 257 * This is an localized id, not a descriptor. If the id is 258 * not visible or not defined by the factory, return null. 259 * If locale is null, return id unchanged. 260 */ getDisplayName(String id, ULocale locale)261 public String getDisplayName(String id, ULocale locale); 262 } 263 264 /** 265 * A default implementation of factory. This provides default 266 * implementations for subclasses, and implements a singleton 267 * factory that matches a single id and returns a single 268 * (possibly deferred-initialized) instance. This implements 269 * updateVisibleIDs to add a mapping from its ID to itself 270 * if visible is true, or to remove any existing mapping 271 * for its ID if visible is false. 272 * @hide Only a subset of ICU is exposed in Android 273 */ 274 public static class SimpleFactory implements Factory { 275 protected Object instance; 276 protected String id; 277 protected boolean visible; 278 279 /** 280 * Convenience constructor that calls SimpleFactory(Object, String, boolean) 281 * with visible true. 282 */ SimpleFactory(Object instance, String id)283 public SimpleFactory(Object instance, String id) { 284 this(instance, id, true); 285 } 286 287 /** 288 * Construct a simple factory that maps a single id to a single 289 * service instance. If visible is true, the id will be visible. 290 * Neither the instance nor the id can be null. 291 */ SimpleFactory(Object instance, String id, boolean visible)292 public SimpleFactory(Object instance, String id, boolean visible) { 293 if (instance == null || id == null) { 294 throw new IllegalArgumentException("Instance or id is null"); 295 } 296 this.instance = instance; 297 this.id = id; 298 this.visible = visible; 299 } 300 301 /** 302 * Return the service instance if the factory's id is equal to 303 * the key's currentID. Service is ignored. 304 */ 305 @Override create(Key key, ICUService service)306 public Object create(Key key, ICUService service) { 307 if (id.equals(key.currentID())) { 308 return instance; 309 } 310 return null; 311 } 312 313 /** 314 * If visible, adds a mapping from id -> this to the result, 315 * otherwise removes id from result. 316 */ 317 @Override updateVisibleIDs(Map<String, Factory> result)318 public void updateVisibleIDs(Map<String, Factory> result) { 319 if (visible) { 320 result.put(id, this); 321 } else { 322 result.remove(id); 323 } 324 } 325 326 /** 327 * If this.id equals id, returns id regardless of locale, 328 * otherwise returns null. (This default implementation has 329 * no localized id information.) 330 */ 331 @Override getDisplayName(String identifier, ULocale locale)332 public String getDisplayName(String identifier, ULocale locale) { 333 return (visible && id.equals(identifier)) ? identifier : null; 334 } 335 336 /** 337 * For debugging. 338 */ 339 @Override toString()340 public String toString() { 341 StringBuilder buf = new StringBuilder(super.toString()); 342 buf.append(", id: "); 343 buf.append(id); 344 buf.append(", visible: "); 345 buf.append(visible); 346 return buf.toString(); 347 } 348 } 349 350 /** 351 * Convenience override for get(String, String[]). This uses 352 * createKey to create a key for the provided descriptor. 353 */ get(String descriptor)354 public Object get(String descriptor) { 355 return getKey(createKey(descriptor), null); 356 } 357 358 /** 359 * Convenience override for get(Key, String[]). This uses 360 * createKey to create a key from the provided descriptor. 361 */ get(String descriptor, String[] actualReturn)362 public Object get(String descriptor, String[] actualReturn) { 363 if (descriptor == null) { 364 throw new NullPointerException("descriptor must not be null"); 365 } 366 return getKey(createKey(descriptor), actualReturn); 367 } 368 369 /** 370 * Convenience override for get(Key, String[]). 371 */ getKey(Key key)372 public Object getKey(Key key) { 373 return getKey(key, null); 374 } 375 376 /** 377 * <p>Given a key, return a service object, and, if actualReturn 378 * is not null, the descriptor with which it was found in the 379 * first element of actualReturn. If no service object matches 380 * this key, return null, and leave actualReturn unchanged.</p> 381 * 382 * <p>This queries the cache using the key's descriptor, and if no 383 * object in the cache matches it, tries the key on each 384 * registered factory, in order. If none generates a service 385 * object for the key, repeats the process with each fallback of 386 * the key, until either one returns a service object, or the key 387 * has no fallback.</p> 388 * 389 * <p>If key is null, just returns null.</p> 390 */ getKey(Key key, String[] actualReturn)391 public Object getKey(Key key, String[] actualReturn) { 392 return getKey(key, actualReturn, null); 393 } 394 395 // debugging 396 // Map hardRef; 397 getKey(Key key, String[] actualReturn, Factory factory)398 public Object getKey(Key key, String[] actualReturn, Factory factory) { 399 if (factories.size() == 0) { 400 return handleDefault(key, actualReturn); 401 } 402 403 if (DEBUG) System.out.println("Service: " + name + " key: " + key.canonicalID()); 404 405 CacheEntry result = null; 406 if (key != null) { 407 try { 408 // The factory list can't be modified until we're done, 409 // otherwise we might update the cache with an invalid result. 410 // The cache has to stay in synch with the factory list. 411 factoryLock.acquireRead(); 412 413 Map<String, CacheEntry> cache = this.cache; // copy so we don't need to sync on this 414 if (cache == null) { 415 if (DEBUG) System.out.println("Service " + name + " cache was empty"); 416 // synchronized since additions and queries on the cache must be atomic 417 // they can be interleaved, though 418 cache = new ConcurrentHashMap<String, CacheEntry>(); 419 } 420 421 String currentDescriptor = null; 422 ArrayList<String> cacheDescriptorList = null; 423 boolean putInCache = false; 424 425 int NDebug = 0; 426 427 int startIndex = 0; 428 int limit = factories.size(); 429 boolean cacheResult = true; 430 if (factory != null) { 431 for (int i = 0; i < limit; ++i) { 432 if (factory == factories.get(i)) { 433 startIndex = i + 1; 434 break; 435 } 436 } 437 if (startIndex == 0) { 438 throw new IllegalStateException("Factory " + factory + "not registered with service: " + this); 439 } 440 cacheResult = false; 441 } 442 443 outer: 444 do { 445 currentDescriptor = key.currentDescriptor(); 446 if (DEBUG) System.out.println(name + "[" + NDebug++ + "] looking for: " + currentDescriptor); 447 result = cache.get(currentDescriptor); 448 if (result != null) { 449 if (DEBUG) System.out.println(name + " found with descriptor: " + currentDescriptor); 450 break outer; 451 } else { 452 if (DEBUG) System.out.println("did not find: " + currentDescriptor + " in cache"); 453 } 454 455 // first test of cache failed, so we'll have to update 456 // the cache if we eventually succeed-- that is, if we're 457 // going to update the cache at all. 458 putInCache = cacheResult; 459 460 // int n = 0; 461 int index = startIndex; 462 while (index < limit) { 463 Factory f = factories.get(index++); 464 if (DEBUG) System.out.println("trying factory[" + (index-1) + "] " + f.toString()); 465 Object service = f.create(key, this); 466 if (service != null) { 467 result = new CacheEntry(currentDescriptor, service); 468 if (DEBUG) System.out.println(name + " factory supported: " + currentDescriptor + ", caching"); 469 break outer; 470 } else { 471 if (DEBUG) System.out.println("factory did not support: " + currentDescriptor); 472 } 473 } 474 475 // prepare to load the cache with all additional ids that 476 // will resolve to result, assuming we'll succeed. We 477 // don't want to keep querying on an id that's going to 478 // fallback to the one that succeeded, we want to hit the 479 // cache the first time next goaround. 480 if (cacheDescriptorList == null) { 481 cacheDescriptorList = new ArrayList<String>(5); 482 } 483 cacheDescriptorList.add(currentDescriptor); 484 485 } while (key.fallback()); 486 487 if (result != null) { 488 if (putInCache) { 489 if (DEBUG) System.out.println("caching '" + result.actualDescriptor + "'"); 490 cache.put(result.actualDescriptor, result); 491 if (cacheDescriptorList != null) { 492 for (String desc : cacheDescriptorList) { 493 if (DEBUG) System.out.println(name + " adding descriptor: '" + desc + "' for actual: '" + result.actualDescriptor + "'"); 494 495 cache.put(desc, result); 496 } 497 } 498 // Atomic update. We held the read lock all this time 499 // so we know our cache is consistent with the factory list. 500 // We might stomp over a cache that some other thread 501 // rebuilt, but that's the breaks. They're both good. 502 this.cache = cache; 503 } 504 505 if (actualReturn != null) { 506 // strip null prefix 507 if (result.actualDescriptor.indexOf("/") == 0) { 508 actualReturn[0] = result.actualDescriptor.substring(1); 509 } else { 510 actualReturn[0] = result.actualDescriptor; 511 } 512 } 513 514 if (DEBUG) System.out.println("found in service: " + name); 515 516 return result.service; 517 } 518 } 519 finally { 520 factoryLock.releaseRead(); 521 } 522 } 523 524 if (DEBUG) System.out.println("not found in service: " + name); 525 526 return handleDefault(key, actualReturn); 527 } 528 private Map<String, CacheEntry> cache; 529 530 // Record the actual id for this service in the cache, so we can return it 531 // even if we succeed later with a different id. 532 private static final class CacheEntry { 533 final String actualDescriptor; 534 final Object service; CacheEntry(String actualDescriptor, Object service)535 CacheEntry(String actualDescriptor, Object service) { 536 this.actualDescriptor = actualDescriptor; 537 this.service = service; 538 } 539 } 540 541 542 /** 543 * Default handler for this service if no factory in the list 544 * handled the key. 545 */ handleDefault(Key key, String[] actualIDReturn)546 protected Object handleDefault(Key key, String[] actualIDReturn) { 547 return null; 548 } 549 550 /** 551 * Convenience override for getVisibleIDs(String) that passes null 552 * as the fallback, thus returning all visible IDs. 553 */ getVisibleIDs()554 public Set<String> getVisibleIDs() { 555 return getVisibleIDs(null); 556 } 557 558 /** 559 * <p>Return a snapshot of the visible IDs for this service. This 560 * set will not change as Factories are added or removed, but the 561 * supported ids will, so there is no guarantee that all and only 562 * the ids in the returned set are visible and supported by the 563 * service in subsequent calls.</p> 564 * 565 * <p>matchID is passed to createKey to create a key. If the 566 * key is not null, it is used to filter out ids that don't have 567 * the key as a fallback. 568 */ getVisibleIDs(String matchID)569 public Set<String> getVisibleIDs(String matchID) { 570 Set<String> result = getVisibleIDMap().keySet(); 571 572 Key fallbackKey = createKey(matchID); 573 574 if (fallbackKey != null) { 575 Set<String> temp = new HashSet<String>(result.size()); 576 for (String id : result) { 577 if (fallbackKey.isFallbackOf(id)) { 578 temp.add(id); 579 } 580 } 581 result = temp; 582 } 583 return result; 584 } 585 586 /** 587 * Return a map from visible ids to factories. 588 */ getVisibleIDMap()589 private Map<String, Factory> getVisibleIDMap() { 590 synchronized (this) { // or idcache-only lock? 591 if (idcache == null) { 592 try { 593 factoryLock.acquireRead(); 594 Map<String, Factory> mutableMap = new HashMap<String, Factory>(); 595 ListIterator<Factory> lIter = factories.listIterator(factories.size()); 596 while (lIter.hasPrevious()) { 597 Factory f = lIter.previous(); 598 f.updateVisibleIDs(mutableMap); 599 } 600 this.idcache = Collections.unmodifiableMap(mutableMap); 601 } finally { 602 factoryLock.releaseRead(); 603 } 604 } 605 } 606 return idcache; 607 } 608 private Map<String, Factory> idcache; 609 610 /** 611 * Convenience override for getDisplayName(String, ULocale) that 612 * uses the current default locale. 613 */ getDisplayName(String id)614 public String getDisplayName(String id) { 615 return getDisplayName(id, ULocale.getDefault(Category.DISPLAY)); 616 } 617 618 /** 619 * Given a visible id, return the display name in the requested locale. 620 * If there is no directly supported id corresponding to this id, return 621 * null. 622 */ getDisplayName(String id, ULocale locale)623 public String getDisplayName(String id, ULocale locale) { 624 Map<String, Factory> m = getVisibleIDMap(); 625 Factory f = m.get(id); 626 if (f != null) { 627 return f.getDisplayName(id, locale); 628 } 629 630 Key key = createKey(id); 631 while (key.fallback()) { 632 f = m.get(key.currentID()); 633 if (f != null) { 634 return f.getDisplayName(id, locale); 635 } 636 } 637 638 return null; 639 } 640 641 /** 642 * Convenience override of getDisplayNames(ULocale, Comparator, String) that 643 * uses the current default Locale as the locale, null as 644 * the comparator, and null for the matchID. 645 */ getDisplayNames()646 public SortedMap<String, String> getDisplayNames() { 647 ULocale locale = ULocale.getDefault(Category.DISPLAY); 648 return getDisplayNames(locale, null, null); 649 } 650 651 /** 652 * Convenience override of getDisplayNames(ULocale, Comparator, String) that 653 * uses null for the comparator, and null for the matchID. 654 */ getDisplayNames(ULocale locale)655 public SortedMap<String, String> getDisplayNames(ULocale locale) { 656 return getDisplayNames(locale, null, null); 657 } 658 659 /** 660 * Convenience override of getDisplayNames(ULocale, Comparator, String) that 661 * uses null for the matchID, thus returning all display names. 662 */ getDisplayNames(ULocale locale, Comparator<Object> com)663 public SortedMap<String, String> getDisplayNames(ULocale locale, Comparator<Object> com) { 664 return getDisplayNames(locale, com, null); 665 } 666 667 /** 668 * Convenience override of getDisplayNames(ULocale, Comparator, String) that 669 * uses null for the comparator. 670 */ getDisplayNames(ULocale locale, String matchID)671 public SortedMap<String, String> getDisplayNames(ULocale locale, String matchID) { 672 return getDisplayNames(locale, null, matchID); 673 } 674 675 /** 676 * Return a snapshot of the mapping from display names to visible 677 * IDs for this service. This set will not change as factories 678 * are added or removed, but the supported ids will, so there is 679 * no guarantee that all and only the ids in the returned map will 680 * be visible and supported by the service in subsequent calls, 681 * nor is there any guarantee that the current display names match 682 * those in the set. The display names are sorted based on the 683 * comparator provided. 684 */ getDisplayNames(ULocale locale, Comparator<Object> com, String matchID)685 public SortedMap<String, String> getDisplayNames(ULocale locale, Comparator<Object> com, String matchID) { 686 SortedMap<String, String> dncache = null; 687 LocaleRef ref = dnref; 688 689 if (ref != null) { 690 dncache = ref.get(locale, com); 691 } 692 693 while (dncache == null) { 694 synchronized (this) { 695 if (ref == dnref || dnref == null) { 696 dncache = new TreeMap<String, String>(com); // sorted 697 698 Map<String, Factory> m = getVisibleIDMap(); 699 Iterator<Entry<String, Factory>> ei = m.entrySet().iterator(); 700 while (ei.hasNext()) { 701 Entry<String, Factory> e = ei.next(); 702 String id = e.getKey(); 703 Factory f = e.getValue(); 704 dncache.put(f.getDisplayName(id, locale), id); 705 } 706 707 dncache = Collections.unmodifiableSortedMap(dncache); 708 dnref = new LocaleRef(dncache, locale, com); 709 } else { 710 ref = dnref; 711 dncache = ref.get(locale, com); 712 } 713 } 714 } 715 716 Key matchKey = createKey(matchID); 717 if (matchKey == null) { 718 return dncache; 719 } 720 721 SortedMap<String, String> result = new TreeMap<String, String>(dncache); 722 Iterator<Entry<String, String>> iter = result.entrySet().iterator(); 723 while (iter.hasNext()) { 724 Entry<String, String> e = iter.next(); 725 if (!matchKey.isFallbackOf(e.getValue())) { 726 iter.remove(); 727 } 728 } 729 return result; 730 } 731 732 // we define a class so we get atomic simultaneous access to the 733 // locale, comparator, and corresponding map. 734 private static class LocaleRef { 735 private final ULocale locale; 736 private SortedMap<String, String> dnCache; 737 private Comparator<Object> com; 738 LocaleRef(SortedMap<String, String> dnCache, ULocale locale, Comparator<Object> com)739 LocaleRef(SortedMap<String, String> dnCache, ULocale locale, Comparator<Object> com) { 740 this.locale = locale; 741 this.com = com; 742 this.dnCache = dnCache; 743 } 744 745 get(ULocale loc, Comparator<Object> comp)746 SortedMap<String, String> get(ULocale loc, Comparator<Object> comp) { 747 SortedMap<String, String> m = dnCache; 748 if (m != null && 749 this.locale.equals(loc) && 750 (this.com == comp || (this.com != null && this.com.equals(comp)))) { 751 752 return m; 753 } 754 return null; 755 } 756 } 757 private LocaleRef dnref; 758 759 /** 760 * Return a snapshot of the currently registered factories. There 761 * is no guarantee that the list will still match the current 762 * factory list of the service subsequent to this call. 763 */ factories()764 public final List<Factory> factories() { 765 try { 766 factoryLock.acquireRead(); 767 return new ArrayList<Factory>(factories); 768 } 769 finally{ 770 factoryLock.releaseRead(); 771 } 772 } 773 774 /** 775 * A convenience override of registerObject(Object, String, boolean) 776 * that defaults visible to true. 777 */ registerObject(Object obj, String id)778 public Factory registerObject(Object obj, String id) { 779 return registerObject(obj, id, true); 780 } 781 782 /** 783 * Register an object with the provided id. The id will be 784 * canonicalized. The canonicalized ID will be returned by 785 * getVisibleIDs if visible is true. 786 */ registerObject(Object obj, String id, boolean visible)787 public Factory registerObject(Object obj, String id, boolean visible) { 788 String canonicalID = createKey(id).canonicalID(); 789 return registerFactory(new SimpleFactory(obj, canonicalID, visible)); 790 } 791 792 /** 793 * Register a Factory. Returns the factory if the service accepts 794 * the factory, otherwise returns null. The default implementation 795 * accepts all factories. 796 */ registerFactory(Factory factory)797 public final Factory registerFactory(Factory factory) { 798 if (factory == null) { 799 throw new NullPointerException(); 800 } 801 try { 802 factoryLock.acquireWrite(); 803 factories.add(0, factory); 804 clearCaches(); 805 } 806 finally { 807 factoryLock.releaseWrite(); 808 } 809 notifyChanged(); 810 return factory; 811 } 812 813 /** 814 * Unregister a factory. The first matching registered factory will 815 * be removed from the list. Returns true if a matching factory was 816 * removed. 817 */ unregisterFactory(Factory factory)818 public final boolean unregisterFactory(Factory factory) { 819 if (factory == null) { 820 throw new NullPointerException(); 821 } 822 823 boolean result = false; 824 try { 825 factoryLock.acquireWrite(); 826 if (factories.remove(factory)) { 827 result = true; 828 clearCaches(); 829 } 830 } 831 finally { 832 factoryLock.releaseWrite(); 833 } 834 835 if (result) { 836 notifyChanged(); 837 } 838 return result; 839 } 840 841 /** 842 * Reset the service to the default factories. The factory 843 * lock is acquired and then reInitializeFactories is called. 844 */ reset()845 public final void reset() { 846 try { 847 factoryLock.acquireWrite(); 848 reInitializeFactories(); 849 clearCaches(); 850 } 851 finally { 852 factoryLock.releaseWrite(); 853 } 854 notifyChanged(); 855 } 856 857 /** 858 * Reinitialize the factory list to its default state. By default 859 * this clears the list. Subclasses can override to provide other 860 * default initialization of the factory list. Subclasses must 861 * not call this method directly, as it must only be called while 862 * holding write access to the factory list. 863 */ reInitializeFactories()864 protected void reInitializeFactories() { 865 factories.clear(); 866 } 867 868 /** 869 * Return true if the service is in its default state. The default 870 * implementation returns true if there are no factories registered. 871 */ isDefault()872 public boolean isDefault() { 873 return factories.size() == defaultSize; 874 } 875 876 /** 877 * Set the default size to the current number of registered factories. 878 * Used by subclasses to customize the behavior of isDefault. 879 */ markDefault()880 protected void markDefault() { 881 defaultSize = factories.size(); 882 } 883 884 /** 885 * Create a key from an id. This creates a Key instance. 886 * Subclasses can override to define more useful keys appropriate 887 * to the factories they accept. If id is null, returns null. 888 */ createKey(String id)889 public Key createKey(String id) { 890 return id == null ? null : new Key(id); 891 } 892 893 /** 894 * Clear caches maintained by this service. Subclasses can 895 * override if they implement additional that need to be cleared 896 * when the service changes. Subclasses should generally not call 897 * this method directly, as it must only be called while 898 * synchronized on this. 899 */ clearCaches()900 protected void clearCaches() { 901 // we don't synchronize on these because methods that use them 902 // copy before use, and check for changes if they modify the 903 // caches. 904 cache = null; 905 idcache = null; 906 dnref = null; 907 } 908 909 /** 910 * Clears only the service cache. 911 * This can be called by subclasses when a change affects the service 912 * cache but not the id caches, e.g., when the default locale changes 913 * the resolution of ids changes, but not the visible ids themselves. 914 */ clearServiceCache()915 protected void clearServiceCache() { 916 cache = null; 917 } 918 919 /** 920 * ServiceListener is the listener that ICUService provides by default. 921 * ICUService will notifiy this listener when factories are added to 922 * or removed from the service. Subclasses can provide 923 * different listener interfaces that extend EventListener, and modify 924 * acceptsListener and notifyListener as appropriate. 925 * @hide Only a subset of ICU is exposed in Android 926 */ 927 public static interface ServiceListener extends EventListener { serviceChanged(ICUService service)928 public void serviceChanged(ICUService service); 929 } 930 931 /** 932 * Return true if the listener is accepted; by default this 933 * requires a ServiceListener. Subclasses can override to accept 934 * different listeners. 935 */ 936 @Override acceptsListener(EventListener l)937 protected boolean acceptsListener(EventListener l) { 938 return l instanceof ServiceListener; 939 } 940 941 /** 942 * Notify the listener, which by default is a ServiceListener. 943 * Subclasses can override to use a different listener. 944 */ 945 @Override notifyListener(EventListener l)946 protected void notifyListener(EventListener l) { 947 ((ServiceListener)l).serviceChanged(this); 948 } 949 950 /** 951 * When the statistics for this service is already enabled, 952 * return the log and resets he statistics. 953 * When the statistics is not enabled, this method enable 954 * the statistics. Used for debugging purposes. 955 */ stats()956 public String stats() { 957 ICURWLock.Stats stats = factoryLock.resetStats(); 958 if (stats != null) { 959 return stats.toString(); 960 } 961 return "no stats"; 962 } 963 964 /** 965 * Return the name of this service. This will be the empty string if none was assigned. 966 */ getName()967 public String getName() { 968 return name; 969 } 970 971 /** 972 * Returns the result of super.toString, appending the name in curly braces. 973 */ 974 @Override toString()975 public String toString() { 976 return super.toString() + "{" + name + "}"; 977 } 978 } 979