KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibm > icu > impl > ICUService


1 /**
2  *******************************************************************************
3  * Copyright (C) 2001-2006, International Business Machines Corporation and *
4  * others. All Rights Reserved. *
5  *******************************************************************************
6  */

7 package com.ibm.icu.impl;
8
9 //import com.ibm.icu.text.Collator;
10

11 import java.lang.ref.SoftReference JavaDoc;
12 import java.util.ArrayList JavaDoc;
13 import java.util.Collections JavaDoc;
14 import java.util.Comparator JavaDoc;
15 import java.util.EventListener JavaDoc;
16 import java.util.HashMap JavaDoc;
17 import java.util.HashSet JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.ListIterator JavaDoc;
21 import java.util.Locale JavaDoc;
22 import java.util.Map JavaDoc;
23 import java.util.Map.Entry;
24 import java.util.Set JavaDoc;
25 import java.util.SortedMap JavaDoc;
26 import java.util.TreeMap JavaDoc;
27
28 import com.ibm.icu.util.ULocale;
29
30 /**
31  * <p>A Service provides access to service objects that implement a
32  * particular service, e.g. transliterators. Users provide a String
33  * id (for example, a locale string) to the service, and get back an
34  * object for that id. Service objects can be any kind of object.
35  * The service object is cached and returned for later queries, so
36  * generally it should not be mutable, or the caller should clone the
37  * object before modifying it.</p>
38  *
39  * <p>Services 'canonicalize' the query id and use the canonical id to
40  * query for the service. The service also defines a mechanism to
41  * 'fallback' the id multiple times. Clients can optionally request
42  * the actual id that was matched by a query when they use an id to
43  * retrieve a service object.</p>
44  *
45  * <p>Service objects are instantiated by Factory objects registered with
46  * the service. The service queries each Factory in turn, from most recently
47  * registered to earliest registered, until one returns a service object.
48  * If none responds with a service object, a fallback id is generated,
49  * and the process repeats until a service object is returned or until
50  * the id has no further fallbacks.</p>
51  *
52  * <p>Factories can be dynamically registered and unregistered with the
53  * service. When registered, a Factory is installed at the head of
54  * the factory list, and so gets 'first crack' at any keys or fallback
55  * keys. When unregistered, it is removed from the service and can no
56  * longer be located through it. Service objects generated by this
57  * factory and held by the client are unaffected.</p>
58  *
59  * <p>ICUService uses Keys to query factories and perform
60  * fallback. The Key defines the canonical form of the id, and
61  * implements the fallback strategy. Custom Keys can be defined that
62  * parse complex IDs into components that Factories can more easily
63  * use. The Key can cache the results of this parsing to save
64  * repeated effort. ICUService provides convenience APIs that
65  * take Strings and generate default Keys for use in querying.</p>
66  *
67  * <p>ICUService provides API to get the list of ids publicly
68  * supported by the service (although queries aren't restricted to
69  * this list). This list contains only 'simple' IDs, and not fully
70  * unique ids. Factories are associated with each simple ID and
71  * the responsible factory can also return a human-readable localized
72  * version of the simple ID, for use in user interfaces. ICUService
73  * can also provide a sorted collection of the all the localized visible
74  * ids.</p>
75  *
76  * <p>ICUService implements ICUNotifier, so that clients can register
77  * to receive notification when factories are added or removed from
78  * the service. ICUService provides a default EventListener subinterface,
79  * ServiceListener, which can be registered with the service. When
80  * the service changes, the ServiceListener's serviceChanged method
81  * is called, with the service as the only argument.</p>
82  *
83  * <p>The ICUService API is both rich and generic, and it is expected
84  * that most implementations will statically 'wrap' ICUService to
85  * present a more appropriate API-- for example, to declare the type
86  * of the objects returned from get, to limit the factories that can
87  * be registered with the service, or to define their own listener
88  * interface with a custom callback method. They might also customize
89  * ICUService by overriding it, for example, to customize the Key and
90  * fallback strategy. ICULocaleService is a customized service that
91  * uses Locale names as ids and uses Keys that implement the standard
92  * resource bundle fallback strategy.<p>
93  */

94 public class ICUService extends ICUNotifier {
95     /**
96      * Name used for debugging.
97      */

98     protected final String JavaDoc name;
99
100     /**
101      * Constructor.
102      */

103     public ICUService() {
104         name = "";
105     }
106
107     private static final boolean DEBUG = ICUDebug.enabled("service");
108     /**
109      * Construct with a name (useful for debugging).
110      */

111     public ICUService(String JavaDoc name) {
112         this.name = name;
113     }
114
115     /**
116      * Access to factories is protected by a read-write lock. This is
117      * to allow multiple threads to read concurrently, but keep
118      * changes to the factory list atomic with respect to all readers.
119      */

120     private final ICURWLock factoryLock = new ICURWLock();
121
122     /**
123      * All the factories registered with this service.
124      */

125     private final List JavaDoc factories = new ArrayList JavaDoc();
126
127     /**
128      * Record the default number of factories for this service.
129      * Can be set by markDefault.
130      */

131     private int defaultSize = 0;
132
133     /**
134      * Keys are used to communicate with factories to generate an
135      * instance of the service. Keys define how ids are
136      * canonicalized, provide both a current id and a current
137      * descriptor to use in querying the cache and factories, and
138      * determine the fallback strategy.</p>
139      *
140      * <p>Keys provide both a currentDescriptor and a currentID.
141      * The descriptor contains an optional prefix, followed by '/'
142      * and the currentID. Factories that handle complex keys,
143      * for example number format factories that generate multiple
144      * kinds of formatters for the same locale, use the descriptor
145      * to provide a fully unique identifier for the service object,
146      * while using the currentID (in this case, the locale string),
147      * as the visible IDs that can be localized.
148      *
149      * <p> The default implementation of Key has no fallbacks and
150      * has no custom descriptors.</p>
151      */

152     public static class Key {
153         private final String JavaDoc id;
154
155         /**
156          * Construct a key from an id.
157          */

158         public Key(String JavaDoc id) {
159             this.id = id;
160         }
161
162         /**
163          * Return the original ID used to construct this key.
164          */

165         public final String JavaDoc id() {
166             return id;
167         }
168
169         /**
170          * Return the canonical version of the original ID. This implementation
171          * returns the original ID unchanged.
172          */

173         public String JavaDoc canonicalID() {
174             return id;
175         }
176
177         /**
178          * Return the (canonical) current ID. This implementation
179          * returns the canonical ID.
180          */

181         public String JavaDoc currentID() {
182             return canonicalID();
183         }
184
185         /**
186          * Return the current descriptor. This implementation returns
187          * the current ID. The current descriptor is used to fully
188          * identify an instance of the service in the cache. A
189          * factory may handle all descriptors for an ID, or just a
190          * particular descriptor. The factory can either parse the
191          * descriptor or use custom API on the key in order to
192          * instantiate the service.
193          */

194         public String JavaDoc currentDescriptor() {
195             return "/" + currentID();
196         }
197
198         /**
199          * If the key has a fallback, modify the key and return true,
200          * otherwise return false. The current ID will change if there
201          * is a fallback. No currentIDs should be repeated, and fallback
202          * must eventually return false. This implmentation has no fallbacks
203          * and always returns false.
204          */

205         public boolean fallback() {
206             return false;
207         }
208
209         /**
210          * If a key created from id would eventually fallback to match the
211          * canonical ID of this key, return true.
212          */

213         public boolean isFallbackOf(String JavaDoc id) {
214             return canonicalID().equals(id);
215         }
216     }
217
218     /**
219      * Factories generate the service objects maintained by the
220      * service. A factory generates a service object from a key,
221      * updates id->factory mappings, and returns the display name for
222      * a supported id.
223      */

224     public static interface Factory {
225
226         /**
227          * Create a service object from the key, if this factory
228          * supports the key. Otherwise, return null.
229          *
230          * <p>If the factory supports the key, then it can call
231          * the service's getKey(Key, String[], Factory) method
232          * passing itself as the factory to get the object that
233          * the service would have created prior to the factory's
234          * registration with the service. This can change the
235          * key, so any information required from the key should
236          * be extracted before making such a callback.
237          */

238         public Object JavaDoc create(Key key, ICUService service);
239
240         /**
241          * Update the result IDs (not descriptors) to reflect the IDs
242          * this factory handles. This function and getDisplayName are
243          * used to support ICUService.getDisplayNames. Basically, the
244          * factory has to determine which IDs it will permit to be
245          * available, and of those, which it will provide localized
246          * display names for. In most cases this reflects the IDs that
247          * the factory directly supports.
248          */

249         public void updateVisibleIDs(Map JavaDoc result);
250
251         /**
252          * Return the display name for this id in the provided locale.
253          * This is an localized id, not a descriptor. If the id is
254          * not visible or not defined by the factory, return null.
255          * If locale is null, return id unchanged.
256          */

257         public String JavaDoc getDisplayName(String JavaDoc id, ULocale locale);
258     }
259
260     /**
261      * A default implementation of factory. This provides default
262      * implementations for subclasses, and implements a singleton
263      * factory that matches a single id and returns a single
264      * (possibly deferred-initialized) instance. This implements
265      * updateVisibleIDs to add a mapping from its ID to itself
266      * if visible is true, or to remove any existing mapping
267      * for its ID if visible is false.
268      */

269     public static class SimpleFactory implements Factory {
270         protected Object JavaDoc instance;
271         protected String JavaDoc id;
272         protected boolean visible;
273
274         /**
275          * Convenience constructor that calls SimpleFactory(Object, String, boolean)
276          * with visible true.
277          */

278         public SimpleFactory(Object JavaDoc instance, String JavaDoc id) {
279             this(instance, id, true);
280         }
281
282         /**
283          * Construct a simple factory that maps a single id to a single
284          * service instance. If visible is true, the id will be visible.
285          * Neither the instance nor the id can be null.
286          */

287         public SimpleFactory(Object JavaDoc instance, String JavaDoc id, boolean visible) {
288             if (instance == null || id == null) {
289                 throw new IllegalArgumentException JavaDoc("Instance or id is null");
290             }
291             this.instance = instance;
292             this.id = id;
293             this.visible = visible;
294         }
295
296         /**
297          * Return the service instance if the factory's id is equal to
298          * the key's currentID. Service is ignored.
299          */

300         public Object JavaDoc create(Key key, ICUService service) {
301             if (id.equals(key.currentID())) {
302                 return instance;
303             }
304             return null;
305         }
306
307         /**
308          * If visible, adds a mapping from id -> this to the result,
309          * otherwise removes id from result.
310          */

311         public void updateVisibleIDs(Map JavaDoc result) {
312             if (visible) {
313                 result.put(id, this);
314             } else {
315                 result.remove(id);
316             }
317         }
318
319         /**
320          * If this.id equals id, returns id regardless of locale,
321          * otherwise returns null. (This default implementation has
322          * no localized id information.)
323          */

324         public String JavaDoc getDisplayName(String JavaDoc id, ULocale locale) {
325             return (visible && this.id.equals(id)) ? id : null;
326         }
327
328         /**
329          * For debugging.
330          */

331         public String JavaDoc toString() {
332             StringBuffer JavaDoc buf = new StringBuffer JavaDoc(super.toString());
333             buf.append(", id: ");
334             buf.append(id);
335             buf.append(", visible: ");
336             buf.append(visible);
337             return buf.toString();
338         }
339     }
340
341     /**
342      * Convenience override for get(String, String[]). This uses
343      * createKey to create a key for the provided descriptor.
344      */

345     public Object JavaDoc get(String JavaDoc descriptor) {
346         return getKey(createKey(descriptor), null);
347     }
348
349     /**
350      * Convenience override for get(Key, String[]). This uses
351      * createKey to create a key from the provided descriptor.
352      */

353     public Object JavaDoc get(String JavaDoc descriptor, String JavaDoc[] actualReturn) {
354         if (descriptor == null) {
355             throw new NullPointerException JavaDoc("descriptor must not be null");
356         }
357         return getKey(createKey(descriptor), actualReturn);
358     }
359
360     /**
361      * Convenience override for get(Key, String[]).
362      */

363     public Object JavaDoc getKey(Key key) {
364         return getKey(key, null);
365     }
366
367     /**
368      * <p>Given a key, return a service object, and, if actualReturn
369      * is not null, the descriptor with which it was found in the
370      * first element of actualReturn. If no service object matches
371      * this key, return null, and leave actualReturn unchanged.</p>
372      *
373      * <p>This queries the cache using the key's descriptor, and if no
374      * object in the cache matches it, tries the key on each
375      * registered factory, in order. If none generates a service
376      * object for the key, repeats the process with each fallback of
377      * the key, until either one returns a service object, or the key
378      * has no fallback.</p>
379      *
380      * <p>If key is null, just returns null.</p>
381      */

382     public Object JavaDoc getKey(Key key, String JavaDoc[] actualReturn) {
383         return getKey(key, actualReturn, null);
384     }
385
386     // debugging
387
// Map hardRef;
388

389     public Object JavaDoc getKey(Key key, String JavaDoc[] actualReturn, Factory factory) {
390         if (factories.size() == 0) {
391             return handleDefault(key, actualReturn);
392         }
393
394         if (DEBUG) System.out.println("Service: " + name + " key: " + key.canonicalID());
395
396         CacheEntry result = null;
397         if (key != null) {
398             try {
399                 // The factory list can't be modified until we're done,
400
// otherwise we might update the cache with an invalid result.
401
// The cache has to stay in synch with the factory list.
402
factoryLock.acquireRead();
403
404                 Map JavaDoc cache = null;
405                 SoftReference JavaDoc cref = cacheref; // copy so we don't need to sync on this
406
if (cref != null) {
407                     if (DEBUG) System.out.println("Service " + name + " ref exists");
408                     cache = (Map JavaDoc)cref.get();
409                 }
410                 if (cache == null) {
411                     if (DEBUG) System.out.println("Service " + name + " cache was empty");
412                     // synchronized since additions and queries on the cache must be atomic
413
// they can be interleaved, though
414
cache = Collections.synchronizedMap(new HashMap JavaDoc());
415 // hardRef = cache; // debug
416
cref = new SoftReference JavaDoc(cache);
417                 }
418
419                 String JavaDoc currentDescriptor = null;
420                 ArrayList JavaDoc cacheDescriptorList = null;
421                 boolean putInCache = false;
422
423                 int NDebug = 0;
424
425                 int startIndex = 0;
426                 int limit = factories.size();
427                 boolean cacheResult = true;
428                 if (factory != null) {
429                     for (int i = 0; i < limit; ++i) {
430                         if (factory == factories.get(i)) {
431                             startIndex = i + 1;
432                             break;
433                         }
434                     }
435                     if (startIndex == 0) {
436                         throw new IllegalStateException JavaDoc("Factory " + factory + "not registered with service: " + this);
437                     }
438                     cacheResult = false;
439                 }
440
441             outer:
442                 do {
443                     currentDescriptor = key.currentDescriptor();
444                     if (DEBUG) System.out.println(name + "[" + NDebug++ + "] looking for: " + currentDescriptor);
445                     result = (CacheEntry)cache.get(currentDescriptor);
446                     if (result != null) {
447                         if (DEBUG) System.out.println(name + " found with descriptor: " + currentDescriptor);
448                         break outer;
449                     } else {
450                         if (DEBUG) System.out.println("did not find: " + currentDescriptor + " in cache");
451                     }
452
453                     // first test of cache failed, so we'll have to update
454
// the cache if we eventually succeed-- that is, if we're
455
// going to update the cache at all.
456
putInCache = cacheResult;
457
458                     // int n = 0;
459
int index = startIndex;
460                     while (index < limit) {
461                         Factory f = (Factory)factories.get(index++);
462                         if (DEBUG) System.out.println("trying factory[" + (index-1) + "] " + f.toString());
463                         Object JavaDoc service = f.create(key, this);
464                         if (service != null) {
465                             result = new CacheEntry(currentDescriptor, service);
466                             if (DEBUG) System.out.println(name + " factory supported: " + currentDescriptor + ", caching");
467                             break outer;
468                         } else {
469                             if (DEBUG) System.out.println("factory did not support: " + currentDescriptor);
470                         }
471                     }
472
473                     // prepare to load the cache with all additional ids that
474
// will resolve to result, assuming we'll succeed. We
475
// don't want to keep querying on an id that's going to
476
// fallback to the one that succeeded, we want to hit the
477
// cache the first time next goaround.
478
if (cacheDescriptorList == null) {
479                         cacheDescriptorList = new ArrayList JavaDoc(5);
480                     }
481                     cacheDescriptorList.add(currentDescriptor);
482
483                 } while (key.fallback());
484
485                 if (result != null) {
486                     if (putInCache) {
487                         if (DEBUG) System.out.println("caching '" + result.actualDescriptor + "'");
488                         cache.put(result.actualDescriptor, result);
489                         if (cacheDescriptorList != null) {
490                             Iterator JavaDoc iter = cacheDescriptorList.iterator();
491                             while (iter.hasNext()) {
492                                 String JavaDoc desc = (String JavaDoc)iter.next();
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
cacheref = cref;
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 SoftReference JavaDoc cacheref;
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 JavaDoc actualDescriptor;
534         final Object JavaDoc service;
535         CacheEntry(String JavaDoc actualDescriptor, Object JavaDoc 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      */

546     protected Object JavaDoc handleDefault(Key key, String JavaDoc[] 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      */

554     public Set JavaDoc 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      */

569     public Set JavaDoc getVisibleIDs(String JavaDoc matchID) {
570         Set JavaDoc result = getVisibleIDMap().keySet();
571
572         Key fallbackKey = createKey(matchID);
573
574         if (fallbackKey != null) {
575             Set JavaDoc temp = new HashSet JavaDoc(result.size());
576             Iterator JavaDoc iter = result.iterator();
577             while (iter.hasNext()) {
578                 String JavaDoc id = (String JavaDoc)iter.next();
579                 if (fallbackKey.isFallbackOf(id)) {
580                     temp.add(id);
581                 }
582             }
583             result = temp;
584         }
585         return result;
586     }
587
588     /**
589      * Return a map from visible ids to factories.
590      */

591     private Map JavaDoc getVisibleIDMap() {
592         Map JavaDoc idcache = null;
593         SoftReference JavaDoc ref = idref;
594         if (ref != null) {
595             idcache = (Map JavaDoc)ref.get();
596         }
597         while (idcache == null) {
598             synchronized (this) { // or idref-only lock?
599
if (ref == idref || idref == null) {
600                     // no other thread updated idref before we got the lock, so
601
// grab the factory list and update it ourselves
602
try {
603                         factoryLock.acquireRead();
604                         idcache = new HashMap JavaDoc();
605                         ListIterator JavaDoc lIter = factories.listIterator(factories.size());
606                         while (lIter.hasPrevious()) {
607                             Factory f = (Factory)lIter.previous();
608                             f.updateVisibleIDs(idcache);
609                         }
610                         idcache = Collections.unmodifiableMap(idcache);
611                         idref = new SoftReference JavaDoc(idcache);
612                     }
613                     finally {
614                         factoryLock.releaseRead();
615                     }
616                 } else {
617                     // another thread updated idref, but gc may have stepped
618
// in and undone its work, leaving idcache null. If so,
619
// retry.
620
ref = idref;
621                     idcache = (Map JavaDoc)ref.get();
622                 }
623             }
624         }
625
626         return idcache;
627     }
628     private SoftReference JavaDoc idref;
629
630     /**
631      * Convenience override for getDisplayName(String, ULocale) that
632      * uses the current default locale.
633      */

634     public String JavaDoc getDisplayName(String JavaDoc id) {
635         return getDisplayName(id, ULocale.getDefault());
636     }
637
638     /**
639      * Given a visible id, return the display name in the requested locale.
640      * If there is no directly supported id corresponding to this id, return
641      * null.
642      */

643     public String JavaDoc getDisplayName(String JavaDoc id, ULocale locale) {
644         Map JavaDoc m = getVisibleIDMap();
645         Factory f = (Factory)m.get(id);
646         if (f != null) {
647             return f.getDisplayName(id, locale);
648         }
649
650         Key key = createKey(id);
651         while (key.fallback()) {
652             f = (Factory)m.get(key.currentID());
653             if (f != null) {
654                 return f.getDisplayName(id, locale);
655             }
656         }
657         
658         return null;
659     }
660
661     /**
662      * Convenience override of getDisplayNames(ULocale, Comparator, String) that
663      * uses the current default Locale as the locale, null as
664      * the comparator, and null for the matchID.
665      */

666     public SortedMap JavaDoc getDisplayNames() {
667         ULocale locale = ULocale.getDefault();
668         return getDisplayNames(locale, null, null);
669     }
670
671     /**
672      * Convenience override of getDisplayNames(ULocale, Comparator, String) that
673      * uses null for the comparator, and null for the matchID.
674      */

675     public SortedMap JavaDoc getDisplayNames(ULocale locale) {
676         return getDisplayNames(locale, null, null);
677     }
678
679     /**
680      * Convenience override of getDisplayNames(ULocale, Comparator, String) that
681      * uses null for the matchID, thus returning all display names.
682      */

683     public SortedMap JavaDoc getDisplayNames(ULocale locale, Comparator JavaDoc com) {
684         return getDisplayNames(locale, com, null);
685     }
686
687     /**
688      * Convenience override of getDisplayNames(ULocale, Comparator, String) that
689      * uses null for the comparator.
690      */

691     public SortedMap JavaDoc getDisplayNames(ULocale locale, String JavaDoc matchID) {
692         return getDisplayNames(locale, null, matchID);
693     }
694
695     /**
696      * Return a snapshot of the mapping from display names to visible
697      * IDs for this service. This set will not change as factories
698      * are added or removed, but the supported ids will, so there is
699      * no guarantee that all and only the ids in the returned map will
700      * be visible and supported by the service in subsequent calls,
701      * nor is there any guarantee that the current display names match
702      * those in the set. The display names are sorted based on the
703      * comparator provided.
704      */

705     public SortedMap JavaDoc getDisplayNames(ULocale locale, Comparator JavaDoc com, String JavaDoc matchID) {
706         SortedMap JavaDoc dncache = null;
707         LocaleRef ref = dnref;
708
709         if (ref != null) {
710             dncache = ref.get(locale, com);
711         }
712
713         while (dncache == null) {
714             synchronized (this) {
715                 if (ref == dnref || dnref == null) {
716                     dncache = new TreeMap JavaDoc(com); // sorted
717

718                     Map JavaDoc m = getVisibleIDMap();
719                     Iterator JavaDoc ei = m.entrySet().iterator();
720                     while (ei.hasNext()) {
721                         Entry e = (Entry)ei.next();
722                         String JavaDoc id = (String JavaDoc)e.getKey();
723                         Factory f = (Factory)e.getValue();
724                         dncache.put(f.getDisplayName(id, locale), id);
725                     }
726
727                     dncache = Collections.unmodifiableSortedMap(dncache);
728                     dnref = new LocaleRef(dncache, locale, com);
729                 } else {
730                     ref = dnref;
731                     dncache = ref.get(locale, com);
732                 }
733             }
734         }
735
736         Key matchKey = createKey(matchID);
737         if (matchKey == null) {
738             return dncache;
739         }
740
741         SortedMap JavaDoc result = new TreeMap JavaDoc(dncache);
742         Iterator JavaDoc iter = result.entrySet().iterator();
743         while (iter.hasNext()) {
744             Entry e = (Entry)iter.next();
745             if (!matchKey.isFallbackOf((String JavaDoc)e.getValue())) {
746                 iter.remove();
747             }
748         }
749         return result;
750     }
751
752     // we define a class so we get atomic simultaneous access to the
753
// locale, comparator, and corresponding map.
754
private static class LocaleRef {
755         private final ULocale locale;
756         private SoftReference JavaDoc ref;
757         private Comparator JavaDoc com;
758
759         LocaleRef(Map JavaDoc dnCache, ULocale locale, Comparator JavaDoc com) {
760             this.locale = locale;
761             this.com = com;
762             this.ref = new SoftReference JavaDoc(dnCache);
763         }
764
765
766         SortedMap JavaDoc get(ULocale locale, Comparator JavaDoc com) {
767             SortedMap JavaDoc m = (SortedMap JavaDoc)ref.get();
768             if (m != null &&
769                 this.locale.equals(locale) &&
770                 (this.com == com || (this.com != null && this.com.equals(com)))) {
771
772                 return m;
773             }
774             return null;
775         }
776     }
777     private LocaleRef dnref;
778
779     /**
780      * Return a snapshot of the currently registered factories. There
781      * is no guarantee that the list will still match the current
782      * factory list of the service subsequent to this call.
783      */

784     public final List JavaDoc factories() {
785         try {
786             factoryLock.acquireRead();
787             return new ArrayList JavaDoc(factories);
788         }
789         finally{
790             factoryLock.releaseRead();
791         }
792     }
793
794     /**
795      * A convenience override of registerObject(Object, String, boolean)
796      * that defaults visible to true.
797      */

798     public Factory registerObject(Object JavaDoc obj, String JavaDoc id) {
799         return registerObject(obj, id, true);
800     }
801
802     /**
803      * Register an object with the provided id. The id will be
804      * canonicalized. The canonicalized ID will be returned by
805      * getVisibleIDs if visible is true.
806      */

807     public Factory registerObject(Object JavaDoc obj, String JavaDoc id, boolean visible) {
808         String JavaDoc canonicalID = createKey(id).canonicalID();
809         return registerFactory(new SimpleFactory(obj, canonicalID, visible));
810     }
811
812     /**
813      * Register a Factory. Returns the factory if the service accepts
814      * the factory, otherwise returns null. The default implementation
815      * accepts all factories.
816      */

817     public final Factory registerFactory(Factory factory) {
818         if (factory == null) {
819             throw new NullPointerException JavaDoc();
820         }
821         try {
822             factoryLock.acquireWrite();
823             factories.add(0, factory);
824             clearCaches();
825         }
826         finally {
827             factoryLock.releaseWrite();
828         }
829         notifyChanged();
830         return factory;
831     }
832
833     /**
834      * Unregister a factory. The first matching registered factory will
835      * be removed from the list. Returns true if a matching factory was
836      * removed.
837      */

838     public final boolean unregisterFactory(Factory factory) {
839         if (factory == null) {
840             throw new NullPointerException JavaDoc();
841         }
842
843         boolean result = false;
844         try {
845             factoryLock.acquireWrite();
846             if (factories.remove(factory)) {
847                 result = true;
848                 clearCaches();
849             }
850         }
851         finally {
852             factoryLock.releaseWrite();
853         }
854
855         if (result) {
856             notifyChanged();
857         }
858         return result;
859     }
860
861     /**
862      * Reset the service to the default factories. The factory
863      * lock is acquired and then reInitializeFactories is called.
864      */

865     public final void reset() {
866         try {
867             factoryLock.acquireWrite();
868             reInitializeFactories();
869             clearCaches();
870         }
871         finally {
872             factoryLock.releaseWrite();
873         }
874         notifyChanged();
875     }
876
877     /**
878      * Reinitialize the factory list to its default state. By default
879      * this clears the list. Subclasses can override to provide other
880      * default initialization of the factory list. Subclasses must
881      * not call this method directly, as it must only be called while
882      * holding write access to the factory list.
883      */

884     protected void reInitializeFactories() {
885         factories.clear();
886     }
887
888     /**
889      * Return true if the service is in its default state. The default
890      * implementation returns true if there are no factories registered.
891      */

892     public boolean isDefault() {
893         return factories.size() == defaultSize;
894     }
895
896     /**
897      * Set the default size to the current number of registered factories.
898      * Used by subclasses to customize the behavior of isDefault.
899      */

900     protected void markDefault() {
901         defaultSize = factories.size();
902     }
903
904     /**
905      * Create a key from an id. This creates a Key instance.
906      * Subclasses can override to define more useful keys appropriate
907      * to the factories they accept. If id is null, returns null.
908      */

909     public Key createKey(String JavaDoc id) {
910         return id == null ? null : new Key(id);
911     }
912
913     /**
914      * Clear caches maintained by this service. Subclasses can
915      * override if they implement additional that need to be cleared
916      * when the service changes. Subclasses should generally not call
917      * this method directly, as it must only be called while
918      * synchronized on this.
919      */

920     protected void clearCaches() {
921         // we don't synchronize on these because methods that use them
922
// copy before use, and check for changes if they modify the
923
// caches.
924
cacheref = null;
925         idref = null;
926         dnref = null;
927     }
928
929     /**
930      * Clears only the service cache.
931      * This can be called by subclasses when a change affects the service
932      * cache but not the id caches, e.g., when the default locale changes
933      * the resolution of ids changes, but not the visible ids themselves.
934      */

935     protected void clearServiceCache() {
936         cacheref = null;
937     }
938
939     /**
940      * ServiceListener is the listener that ICUService provides by default.
941      * ICUService will notifiy this listener when factories are added to
942      * or removed from the service. Subclasses can provide
943      * different listener interfaces that extend EventListener, and modify
944      * acceptsListener and notifyListener as appropriate.
945      */

946     public static interface ServiceListener extends EventListener JavaDoc {
947         public void serviceChanged(ICUService service);
948     }
949
950     /**
951      * Return true if the listener is accepted; by default this
952      * requires a ServiceListener. Subclasses can override to accept
953      * different listeners.
954      */

955     protected boolean acceptsListener(EventListener JavaDoc l) {
956         return l instanceof ServiceListener;
957     }
958
959     /**
960      * Notify the listener, which by default is a ServiceListener.
961      * Subclasses can override to use a different listener.
962      */

963     protected void notifyListener(EventListener JavaDoc l) {
964         ((ServiceListener)l).serviceChanged(this);
965     }
966
967     /**
968      * Return a string describing the statistics for this service.
969      * This also resets the statistics. Used for debugging purposes.
970      */

971     public String JavaDoc stats() {
972         ICURWLock.Stats stats = factoryLock.resetStats();
973         if (stats != null) {
974             return stats.toString();
975         }
976         return "no stats";
977     }
978
979     /**
980      * Return the name of this service. This will be the empty string if none was assigned.
981      */

982     public String JavaDoc getName() {
983         return name;
984     }
985
986     /**
987      * Returns the result of super.toString, appending the name in curly braces.
988      */

989     public String JavaDoc toString() {
990         return super.toString() + "{" + name + "}";
991     }
992 }
993
Popular Tags