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