com.ibm.icu.impl.ICUService Maven / Gradle / Ivy
Show all versions of icu4j Show documentation
/**
*******************************************************************************
* Copyright (C) 2001-2013, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.impl;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EventListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import com.ibm.icu.util.ULocale;
import com.ibm.icu.util.ULocale.Category;
/**
* A Service provides access to service objects that implement a
* particular service, e.g. transliterators. Users provide a String
* id (for example, a locale string) to the service, and get back an
* object for that id. Service objects can be any kind of object.
* The service object is cached and returned for later queries, so
* generally it should not be mutable, or the caller should clone the
* object before modifying it.
*
* Services 'canonicalize' the query id and use the canonical id to
* query for the service. The service also defines a mechanism to
* 'fallback' the id multiple times. Clients can optionally request
* the actual id that was matched by a query when they use an id to
* retrieve a service object.
*
* Service objects are instantiated by Factory objects registered with
* the service. The service queries each Factory in turn, from most recently
* registered to earliest registered, until one returns a service object.
* If none responds with a service object, a fallback id is generated,
* and the process repeats until a service object is returned or until
* the id has no further fallbacks.
*
* Factories can be dynamically registered and unregistered with the
* service. When registered, a Factory is installed at the head of
* the factory list, and so gets 'first crack' at any keys or fallback
* keys. When unregistered, it is removed from the service and can no
* longer be located through it. Service objects generated by this
* factory and held by the client are unaffected.
*
* ICUService uses Keys to query factories and perform
* fallback. The Key defines the canonical form of the id, and
* implements the fallback strategy. Custom Keys can be defined that
* parse complex IDs into components that Factories can more easily
* use. The Key can cache the results of this parsing to save
* repeated effort. ICUService provides convenience APIs that
* take Strings and generate default Keys for use in querying.
*
* ICUService provides API to get the list of ids publicly
* supported by the service (although queries aren't restricted to
* this list). This list contains only 'simple' IDs, and not fully
* unique ids. Factories are associated with each simple ID and
* the responsible factory can also return a human-readable localized
* version of the simple ID, for use in user interfaces. ICUService
* can also provide a sorted collection of the all the localized visible
* ids.
*
* ICUService implements ICUNotifier, so that clients can register
* to receive notification when factories are added or removed from
* the service. ICUService provides a default EventListener subinterface,
* ServiceListener, which can be registered with the service. When
* the service changes, the ServiceListener's serviceChanged method
* is called, with the service as the only argument.
*
* The ICUService API is both rich and generic, and it is expected
* that most implementations will statically 'wrap' ICUService to
* present a more appropriate API-- for example, to declare the type
* of the objects returned from get, to limit the factories that can
* be registered with the service, or to define their own listener
* interface with a custom callback method. They might also customize
* ICUService by overriding it, for example, to customize the Key and
* fallback strategy. ICULocaleService is a customized service that
* uses Locale names as ids and uses Keys that implement the standard
* resource bundle fallback strategy.
*/
public class ICUService extends ICUNotifier {
/**
* Name used for debugging.
*/
protected final String name;
/**
* Constructor.
*/
public ICUService() {
name = "";
}
private static final boolean DEBUG = ICUDebug.enabled("service");
/**
* Construct with a name (useful for debugging).
*/
public ICUService(String name) {
this.name = name;
}
/**
* Access to factories is protected by a read-write lock. This is
* to allow multiple threads to read concurrently, but keep
* changes to the factory list atomic with respect to all readers.
*/
private final ICURWLock factoryLock = new ICURWLock();
/**
* All the factories registered with this service.
*/
private final List factories = new ArrayList();
/**
* Record the default number of factories for this service.
* Can be set by markDefault.
*/
private int defaultSize = 0;
/**
* Keys are used to communicate with factories to generate an
* instance of the service. Keys define how ids are
* canonicalized, provide both a current id and a current
* descriptor to use in querying the cache and factories, and
* determine the fallback strategy.
*
* Keys provide both a currentDescriptor and a currentID.
* The descriptor contains an optional prefix, followed by '/'
* and the currentID. Factories that handle complex keys,
* for example number format factories that generate multiple
* kinds of formatters for the same locale, use the descriptor
* to provide a fully unique identifier for the service object,
* while using the currentID (in this case, the locale string),
* as the visible IDs that can be localized.
*
*
The default implementation of Key has no fallbacks and
* has no custom descriptors.
*/
public static class Key {
private final String id;
/**
* Construct a key from an id.
*/
public Key(String id) {
this.id = id;
}
/**
* Return the original ID used to construct this key.
*/
public final String id() {
return id;
}
/**
* Return the canonical version of the original ID. This implementation
* returns the original ID unchanged.
*/
public String canonicalID() {
return id;
}
/**
* Return the (canonical) current ID. This implementation
* returns the canonical ID.
*/
public String currentID() {
return canonicalID();
}
/**
* Return the current descriptor. This implementation returns
* the current ID. The current descriptor is used to fully
* identify an instance of the service in the cache. A
* factory may handle all descriptors for an ID, or just a
* particular descriptor. The factory can either parse the
* descriptor or use custom API on the key in order to
* instantiate the service.
*/
public String currentDescriptor() {
return "/" + currentID();
}
/**
* If the key has a fallback, modify the key and return true,
* otherwise return false. The current ID will change if there
* is a fallback. No currentIDs should be repeated, and fallback
* must eventually return false. This implmentation has no fallbacks
* and always returns false.
*/
public boolean fallback() {
return false;
}
/**
* If a key created from id would eventually fallback to match the
* canonical ID of this key, return true.
*/
public boolean isFallbackOf(String idToCheck) {
return canonicalID().equals(idToCheck);
}
}
/**
* Factories generate the service objects maintained by the
* service. A factory generates a service object from a key,
* updates id->factory mappings, and returns the display name for
* a supported id.
*/
public static interface Factory {
/**
* Create a service object from the key, if this factory
* supports the key. Otherwise, return null.
*
* If the factory supports the key, then it can call
* the service's getKey(Key, String[], Factory) method
* passing itself as the factory to get the object that
* the service would have created prior to the factory's
* registration with the service. This can change the
* key, so any information required from the key should
* be extracted before making such a callback.
*/
public Object create(Key key, ICUService service);
/**
* Update the result IDs (not descriptors) to reflect the IDs
* this factory handles. This function and getDisplayName are
* used to support ICUService.getDisplayNames. Basically, the
* factory has to determine which IDs it will permit to be
* available, and of those, which it will provide localized
* display names for. In most cases this reflects the IDs that
* the factory directly supports.
*/
public void updateVisibleIDs(Map result);
/**
* Return the display name for this id in the provided locale.
* This is an localized id, not a descriptor. If the id is
* not visible or not defined by the factory, return null.
* If locale is null, return id unchanged.
*/
public String getDisplayName(String id, ULocale locale);
}
/**
* A default implementation of factory. This provides default
* implementations for subclasses, and implements a singleton
* factory that matches a single id and returns a single
* (possibly deferred-initialized) instance. This implements
* updateVisibleIDs to add a mapping from its ID to itself
* if visible is true, or to remove any existing mapping
* for its ID if visible is false.
*/
public static class SimpleFactory implements Factory {
protected Object instance;
protected String id;
protected boolean visible;
/**
* Convenience constructor that calls SimpleFactory(Object, String, boolean)
* with visible true.
*/
public SimpleFactory(Object instance, String id) {
this(instance, id, true);
}
/**
* Construct a simple factory that maps a single id to a single
* service instance. If visible is true, the id will be visible.
* Neither the instance nor the id can be null.
*/
public SimpleFactory(Object instance, String id, boolean visible) {
if (instance == null || id == null) {
throw new IllegalArgumentException("Instance or id is null");
}
this.instance = instance;
this.id = id;
this.visible = visible;
}
/**
* Return the service instance if the factory's id is equal to
* the key's currentID. Service is ignored.
*/
public Object create(Key key, ICUService service) {
if (id.equals(key.currentID())) {
return instance;
}
return null;
}
/**
* If visible, adds a mapping from id -> this to the result,
* otherwise removes id from result.
*/
public void updateVisibleIDs(Map result) {
if (visible) {
result.put(id, this);
} else {
result.remove(id);
}
}
/**
* If this.id equals id, returns id regardless of locale,
* otherwise returns null. (This default implementation has
* no localized id information.)
*/
public String getDisplayName(String identifier, ULocale locale) {
return (visible && id.equals(identifier)) ? identifier : null;
}
/**
* For debugging.
*/
public String toString() {
StringBuilder buf = new StringBuilder(super.toString());
buf.append(", id: ");
buf.append(id);
buf.append(", visible: ");
buf.append(visible);
return buf.toString();
}
}
/**
* Convenience override for get(String, String[]). This uses
* createKey to create a key for the provided descriptor.
*/
public Object get(String descriptor) {
return getKey(createKey(descriptor), null);
}
/**
* Convenience override for get(Key, String[]). This uses
* createKey to create a key from the provided descriptor.
*/
public Object get(String descriptor, String[] actualReturn) {
if (descriptor == null) {
throw new NullPointerException("descriptor must not be null");
}
return getKey(createKey(descriptor), actualReturn);
}
/**
* Convenience override for get(Key, String[]).
*/
public Object getKey(Key key) {
return getKey(key, null);
}
/**
* Given a key, return a service object, and, if actualReturn
* is not null, the descriptor with which it was found in the
* first element of actualReturn. If no service object matches
* this key, return null, and leave actualReturn unchanged.
*
* This queries the cache using the key's descriptor, and if no
* object in the cache matches it, tries the key on each
* registered factory, in order. If none generates a service
* object for the key, repeats the process with each fallback of
* the key, until either one returns a service object, or the key
* has no fallback.
*
* If key is null, just returns null.
*/
public Object getKey(Key key, String[] actualReturn) {
return getKey(key, actualReturn, null);
}
// debugging
// Map hardRef;
public Object getKey(Key key, String[] actualReturn, Factory factory) {
if (factories.size() == 0) {
return handleDefault(key, actualReturn);
}
if (DEBUG) System.out.println("Service: " + name + " key: " + key.canonicalID());
CacheEntry result = null;
if (key != null) {
try {
// The factory list can't be modified until we're done,
// otherwise we might update the cache with an invalid result.
// The cache has to stay in synch with the factory list.
factoryLock.acquireRead();
Map cache = null;
SoftReference