org.jvnet.hk2.component
Class Habitat

java.lang.Object
  extended by org.jvnet.hk2.component.Habitat
All Implemented Interfaces:
Injector, BaseServiceLocator, SimpleServiceLocator

public class Habitat
extends Object
implements Injector, SimpleServiceLocator

A set of templates that constitute a world of objects.

Author:
Kohsuke Kawaguchi, Jerome Dochez

Nested Class Summary
protected static interface Habitat.NotifyCall
           
 
Field Summary
 String DEFAULT_NAME
          Name to use to programmatically store default instances of a particular service.
static String HK2_CONCURRENCY_CONTROLS
          System property tag for concurrency controls (i.e., true for multi threaded injection, inhabitant activation, etc.)
static boolean MANAGED_INJECTION_POINTS_ENABLED
           
 ScopeInstance singletonScope
           
 
Constructor Summary
Habitat()
           
Habitat(Habitat parent, String name)
           
 
Method Summary
 void add(Inhabitant<?> i)
          Adds a new inhabitant.
<T> void
addComponent(T component)
          Add an already instantiated component to this manager.
 void addHabitatListener(HabitatListener listener)
          Add a habitat listener with no contract-level filtering.
protected  void addHabitatListener(HabitatListener listener, Set<String> typeNames)
           
 void addHabitatListener(HabitatListener listener, String... typeNames)
          Add a habitat listener with contract-level filtering.
 void addIndex(Inhabitant<?> i, String index, String name)
          Adds a new index to look up the given inhabitant.
protected  void addIndex(Inhabitant<?> i, String index, String name, boolean notify)
           
 DynamicBinderFactory bindDynamically()
           
<U> ServiceLocator<U>
byType(Class<U> type)
           
 ServiceLocator<?> byType(String typeName)
           
<U> ContractLocator<U>
forContract(Class<U> contract)
           
 ContractLocator<?> forContract(String contractName)
           
<U> ContractLocator<U>
forContract(TypeLiteral<U> typeLiteral)
           
<T> Collection<T>
getAllByContract(Class<T> contractType)
          Gets all the inhabitants registered under the given Contract.
<T> Collection<T>
getAllByContract(String contractType)
           
<T> Collection<T>
getAllByType(Class<T> implType)
          Gets the object of the given type.
 Iterator<String> getAllContracts()
           
 Iterator<String> getAllTypes()
           
 Collection<Binding<?>> getBindings()
           
 Collection<Binding<?>> getBindings(Descriptor descriptor)
           
<T> T
getByContract(Class<T> contractType)
          Gets the object that has the given contract.
<T> T
getByContract(String contractType)
           
<T> T
getByType(Class<T> implType)
          Gets the object of the given type.
<T> T
getByType(String implType)
          Gets the object of the given type.
<T> T
getComponent(Class<T> clazz)
          Obtains a reference to the component inside the manager.
<T> T
getComponent(Class<T> contract, String name)
          Loads a component that implements the given contract and has the given name.
<T> T
getComponent(String fullQualifiedName, String name)
          Analogous to the following:
 Collection<Binding<?>> getDeclaredBindings()
           
 Collection<Binding<?>> getDeclaredBindings(Descriptor descriptor)
           
 Habitat getDefault()
           
<T> Inhabitant<T>
getInhabitant(Class<T> contract, String name)
          Gets a lazy reference to the component.
<T> Inhabitant<T>
getInhabitant(Type type, String name)
           
 Inhabitant<?> getInhabitantByAnnotation(Class<? extends Annotation> contract, String name)
          Gets the inhabitant that has the given contract annotation and the given name.
 Inhabitant<?> getInhabitantByContract(String typeName)
          Get the first inhabitant by contract
 Inhabitant getInhabitantByContract(String fullyQualifiedName, String name)
           
<T> Inhabitant<T>
getInhabitantByType(Class<T> implType)
          Gets a lazy reference to the component.
 Inhabitant<?> getInhabitantByType(String fullyQualifiedClassName)
           
<T> Inhabitant<T>
getInhabitantByType(Type implType)
           
<T> Collection<Inhabitant<? extends T>>
getInhabitants(Class<T> type)
          Gets all the inhabitants for a spcial contract.
<T> Iterable<Inhabitant<? extends T>>
getInhabitants(Class<T> contract, String name)
          Gets all the inhabitants that has the given contract and the given name

This method defers the actual instantiation of the component until Inhabitant.get() is invoked.

 Iterable<Inhabitant<?>> getInhabitantsByAnnotation(Class<? extends Annotation> contract, String name)
          Gets all the inhabitants that has the given contract annotation and the given name.
 Collection<Inhabitant<?>> getInhabitantsByContract(String fullyQualifiedClassName)
           
<T> Collection<Inhabitant<T>>
getInhabitantsByContract(Type contract)
          Gets all the inhabitants that has the given contract.
<T> Collection<Inhabitant<T>>
getInhabitantsByType(Class<T> implType)
          Gets all the inhabitants that has the given implementation type.
 Collection<Inhabitant<?>> getInhabitantsByType(String fullyQualifiedClassName)
          Gets all the inhabitants that has the given implementation type name.
<T> Inhabitant<T>
getProvider(String fullQualifiedName, String name)
           
<T> Inhabitant<T>
getProvider(Type type, String name)
          Gets an inhabitant from its type and optionally name
protected static Long getServiceRanking(Inhabitant<?> i, boolean wantNonNull)
           
 Habitat getServices(String moduleName)
           
 void initialized()
          FOR INTERNAL USE ONLY
<T> T
inject(Class<T> type)
          Instantiate the passed type and injects all the Inject annotated fields and methods
<T> T
inject(T object)
          Injects all the Inject annotated fields and methods of the passed instance.
 boolean isContextualFactoriesPresent()
          FOR INTERNAL USE
static boolean isContextualFactoriesPresentAnywhere()
          FOR INTERNAL USE
 boolean isContract(Class<?> type)
          Checks if the given type is a contract interface that has some implementations in this Habitat.
 boolean isContract(String fullyQualifiedClassName)
           
 boolean isContract(Type type)
           
 boolean isContractExt(Type type)
          A weaker test than isContract(Type).
 boolean isInitialized()
           
protected  boolean matches(Inhabitant<?> inhabitant, Object serviceOrInhabitant)
           
protected  void notify(Habitat.NotifyCall innerCall, Inhabitant<?> inhabitant, HabitatListener.EventType event, String index, Inhabitant<HabitatListener> extraListenerToBeNotified)
           
protected  void notify(Inhabitant<?> inhabitant, HabitatListener.EventType event, String index, Inhabitant<HabitatListener> extraListenerToBeNotified)
           
protected  void notify(Inhabitant<?> inhabitant, HabitatListener.EventType event, String index, String name, Object service, Inhabitant<HabitatListener> extraListenerToBeNotified)
           
 void notifyInhabitantChanged(Inhabitant<?> inhabitant, String... contracts)
          Trigger a notification that an inhabitant has changed.
 void release()
          Releases all the components.
 boolean remove(Inhabitant<?> inhabitant)
          Removes an inhabitant
 boolean removeAllByType(Class<?> type)
          Removes all inhabitants for a particular type
 boolean removeHabitatListener(HabitatListener listener)
          Remove a habitat listener.
 boolean removeIndex(String index, Object serviceOrInhabitant)
          Removes a Contracted service
 boolean removeIndex(String index, String name)
          Removes a NamedInhabitant for a specific contract
protected  Object service(Object serviceOrInhabitant)
           
 InhabitantTracker track(InhabitantTrackerContext itc, InhabitantTracker.Callback callback)
          Registers a dependency on the inhabitant with the given tracker context.
 Future<InhabitantTracker> trackFuture(InhabitantTrackerContext itc)
          Returns a future that can be checked asynchronously, and multiple times.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DEFAULT_NAME

public final String DEFAULT_NAME
Name to use to programmatically store default instances of a particular service.

See Also:
Constant Field Values

HK2_CONCURRENCY_CONTROLS

public static final String HK2_CONCURRENCY_CONTROLS
System property tag for concurrency controls (i.e., true for multi threaded injection, inhabitant activation, etc.)

See Also:
Constant Field Values

singletonScope

public final ScopeInstance singletonScope

MANAGED_INJECTION_POINTS_ENABLED

public static final boolean MANAGED_INJECTION_POINTS_ENABLED
See Also:
Constant Field Values
Constructor Detail

Habitat

public Habitat()

Habitat

public Habitat(Habitat parent,
               String name)
Method Detail

getDefault

public Habitat getDefault()

getServices

public Habitat getServices(String moduleName)

getDeclaredBindings

public Collection<Binding<?>> getDeclaredBindings()

getDeclaredBindings

public Collection<Binding<?>> getDeclaredBindings(Descriptor descriptor)

getBindings

public Collection<Binding<?>> getBindings()

getBindings

public Collection<Binding<?>> getBindings(Descriptor descriptor)

bindDynamically

public DynamicBinderFactory bindDynamically()

forContract

public <U> ContractLocator<U> forContract(Class<U> contract)

forContract

public ContractLocator<?> forContract(String contractName)

forContract

public <U> ContractLocator<U> forContract(TypeLiteral<U> typeLiteral)

byType

public <U> ServiceLocator<U> byType(Class<U> type)

byType

public ServiceLocator<?> byType(String typeName)

addHabitatListener

public void addHabitatListener(HabitatListener listener)
Add a habitat listener with no contract-level filtering. This API is primarily intended for internal cases within Hk2.

The listener with no contract-level filtering will be called for all change events within the habitat pertaining to inhabitants.

Parameters:
listener - The habitat Listener to be added
See Also:
#addHabitatListener(HabitatListener, String...)} is recommended for most cases

addHabitatListener

public void addHabitatListener(HabitatListener listener,
                               String... typeNames)
Add a habitat listener with contract-level filtering.

The listener will be called based on the set of contract filters provided.

Parameters:
listener - The habitat Listener to be added
typeNames - The contracts to filter on; this should be non-null

addHabitatListener

protected void addHabitatListener(HabitatListener listener,
                                  Set<String> typeNames)

removeHabitatListener

public boolean removeHabitatListener(HabitatListener listener)
Remove a habitat listener.

Parameters:
listener - The habitat Listener to be removed
Returns:
true; if the listener was indeed removed

track

public InhabitantTracker track(InhabitantTrackerContext itc,
                               InhabitantTracker.Callback callback)
                        throws ComponentException
Registers a dependency on the inhabitant with the given tracker context.

Once the criteria is met, any callback provided is called. This callback may occur asynchronously from the thread initiating the event.

Parameters:
itc - The tracking criteria.
callback - Optionally the callback.
Returns:
The tracker
Throws:
ComponentException

trackFuture

public Future<InhabitantTracker> trackFuture(InhabitantTrackerContext itc)
                                      throws ComponentException
Returns a future that can be checked asynchronously, and multiple times.

Implementation Note: The Future that is returned does not behave in the traditional sense in that it is NOT directly submitted to an ExecutorService. Each call to get() or get(timeout) may result in a [re]submission to an internally held executor. This means that a call to get(...) may return a tracker, and a subsequent call to get(...) may return null, or vice versa. This is true until the underlying tracker is released at which point a tracker is no longer usable.

Parameters:
itc - The tracking criteria.
Returns:
The tracker
Throws:
ComponentException

removeAllByType

public boolean removeAllByType(Class<?> type)
Removes all inhabitants for a particular type

Parameters:
type - of the component
Returns:
true if any inhabitants were removed

add

public void add(Inhabitant<?> i)
Adds a new inhabitant.

See Inhabitants for typical ways to create Inhabitants.


addIndex

public void addIndex(Inhabitant<?> i,
                     String index,
                     String name)
Adds a new index to look up the given inhabitant.

Parameters:
index - Primary index name, such as contract FQCN.
name - Name that identifies the inhabitant among other inhabitants in the same index. Can be null for unnamed inhabitants.

addIndex

protected void addIndex(Inhabitant<?> i,
                        String index,
                        String name,
                        boolean notify)

getServiceRanking

protected static Long getServiceRanking(Inhabitant<?> i,
                                        boolean wantNonNull)

remove

public boolean remove(Inhabitant<?> inhabitant)
Removes an inhabitant

Parameters:
inhabitant - inhabitant to be removed

removeIndex

public boolean removeIndex(String index,
                           String name)
Removes a NamedInhabitant for a specific contract

Parameters:
index - contract name
name - instance name
Returns:
true if the removal was successful

removeIndex

public boolean removeIndex(String index,
                           Object serviceOrInhabitant)
Removes a Contracted service

Parameters:
index - the contract name
serviceOrInhabitant - the service instance, or an Inhabitant instance

matches

protected boolean matches(Inhabitant<?> inhabitant,
                          Object serviceOrInhabitant)

service

protected Object service(Object serviceOrInhabitant)

notifyInhabitantChanged

public void notifyInhabitantChanged(Inhabitant<?> inhabitant,
                                    String... contracts)
Trigger a notification that an inhabitant has changed.

Parameters:
inhabitant - the inhabitant that has changed
contracts - the contracts associated with the inhabitant

initialized

public void initialized()
FOR INTERNAL USE ONLY


isInitialized

public boolean isInitialized()

isContextualFactoriesPresentAnywhere

public static boolean isContextualFactoriesPresentAnywhere()
FOR INTERNAL USE


isContextualFactoriesPresent

public boolean isContextualFactoriesPresent()
FOR INTERNAL USE


notify

protected void notify(Inhabitant<?> inhabitant,
                      HabitatListener.EventType event,
                      String index,
                      Inhabitant<HabitatListener> extraListenerToBeNotified)

notify

protected void notify(Inhabitant<?> inhabitant,
                      HabitatListener.EventType event,
                      String index,
                      String name,
                      Object service,
                      Inhabitant<HabitatListener> extraListenerToBeNotified)

notify

protected void notify(Habitat.NotifyCall innerCall,
                      Inhabitant<?> inhabitant,
                      HabitatListener.EventType event,
                      String index,
                      Inhabitant<HabitatListener> extraListenerToBeNotified)

isContract

public boolean isContract(Class<?> type)
Checks if the given type is a contract interface that has some implementations in this Habitat.

There are two ways for a type to be marked as a contract. Either it has Contract, or it's marked by ContractProvided from the implementation.

Note that just having Contract is not enough to make this method return true. It can still return false if the contract has no implementation in this habitat.

This method is useful during the injection to determine what lookup to perform, and it handles the case correctly when the type is marked as a contract by ContractProvided.


isContract

public boolean isContract(Type type)

isContract

public boolean isContract(String fullyQualifiedClassName)

isContractExt

public boolean isContractExt(Type type)
A weaker test than isContract(Type).

This will return true if either the type argument is annotated with Contract or if the isContract(Type) returns true.


getAllByContract

public <T> Collection<T> getAllByContract(Class<T> contractType)
Gets all the inhabitants registered under the given Contract. This is an example of heterogeneous type-safe container.

Specified by:
getAllByContract in interface BaseServiceLocator
Returns:
can be empty but never null.

getAllByContract

public <T> Collection<T> getAllByContract(String contractType)
Specified by:
getAllByContract in interface BaseServiceLocator

getAllByType

public <T> Collection<T> getAllByType(Class<T> implType)
Gets the object of the given type.

Returns:
can be empty but never null.

addComponent

public <T> void addComponent(T component)
                  throws ComponentException
Add an already instantiated component to this manager. The component has been instantiated by external code, however dependency injection, PostConstruct invocation and dependency extraction will be performed on this instance before it is store in the relevant scope's resource manager.

Parameters:
component - component instance
Throws:
ComponentException - if the passed object is not an HK2 component or injection/extraction failed.

getComponent

public <T> T getComponent(Class<T> clazz)
               throws ComponentException
Obtains a reference to the component inside the manager.

This is the "new Foo()" equivalent in the IoC world.

Depending on the Scope of the component, a new instance might be created, or an existing instance might be returned.

Specified by:
getComponent in interface BaseServiceLocator
Returns:
non-null.
Throws:
ComponentException - If failed to obtain a requested instance. In practice, failure only happens when we try to create a new instance of the component.

getComponent

public <T> T getComponent(Class<T> contract,
                          String name)
               throws ComponentException
Description copied from interface: BaseServiceLocator
Loads a component that implements the given contract and has the given name.

Specified by:
getComponent in interface BaseServiceLocator
name - can be null, in which case it'll only match to the unnamed component.
Returns:
null if no such service exists.
Throws:
ComponentException

getProvider

public <T> Inhabitant<T> getProvider(String fullQualifiedName,
                                     String name)
Specified by:
getProvider in interface SimpleServiceLocator

getComponent

public <T> T getComponent(String fullQualifiedName,
                          String name)
Description copied from interface: BaseServiceLocator
Analogous to the following:
 getComponent(contractClass.getName(), name);
 

Specified by:
getComponent in interface BaseServiceLocator
Parameters:
fullQualifiedName - the contract class name
name - can be null, in which case it'll only match to the unnamed component.
Returns:
null if no such service exists.

getInhabitant

public <T> Inhabitant<T> getInhabitant(Class<T> contract,
                                       String name)
                            throws ComponentException
Gets a lazy reference to the component.

This method defers the actual instantiation of the component until Inhabitant.get() is invoked.

Returns:
null if no such component is found.
Throws:
ComponentException

getInhabitant

public <T> Inhabitant<T> getInhabitant(Type type,
                                       String name)

getInhabitantByType

public <T> Inhabitant<T> getInhabitantByType(Class<T> implType)
Gets a lazy reference to the component.

This method defers the actual instantiation of the component until Inhabitant.get() is invoked.

Returns:
null if no such component is found.

getInhabitantByType

public <T> Inhabitant<T> getInhabitantByType(Type implType)

getInhabitantByType

public Inhabitant<?> getInhabitantByType(String fullyQualifiedClassName)

getInhabitantByAnnotation

public Inhabitant<?> getInhabitantByAnnotation(Class<? extends Annotation> contract,
                                               String name)
                                        throws ComponentException
Gets the inhabitant that has the given contract annotation and the given name.

This method defers the actual instantiation of the component until Inhabitant.get() is invoked.

Returns:
null if no such component is found.
Throws:
ComponentException

getInhabitants

public <T> Collection<Inhabitant<? extends T>> getInhabitants(Class<T> type)
Gets all the inhabitants for a spcial contract. FOR COMPATIBILITY REASONS

Type Parameters:
T - the parameterized type
Parameters:
type - the contract type
Returns:

getInhabitantsByContract

public <T> Collection<Inhabitant<T>> getInhabitantsByContract(Type contract)
                                                   throws ComponentException
Gets all the inhabitants that has the given contract.

Specified by:
getInhabitantsByContract in interface SimpleServiceLocator
Throws:
ComponentException

inject

public <T> T inject(T object)
Description copied from interface: Injector
Injects all the Inject annotated fields and methods of the passed instance.

Specified by:
inject in interface Injector
Parameters:
object - the instance to inject
Returns:
the passed parameter as a convenience

inject

public <T> T inject(Class<T> type)
Instantiate the passed type and injects all the Inject annotated fields and methods

Specified by:
inject in interface Injector
Type Parameters:
T - type of the requested instance
Parameters:
type - class of the requested instance
Returns:
the instantiated and injected instance

getInhabitantsByType

public <T> Collection<Inhabitant<T>> getInhabitantsByType(Class<T> implType)
                                               throws ComponentException
Gets all the inhabitants that has the given implementation type.

Specified by:
getInhabitantsByType in interface SimpleServiceLocator
Throws:
ComponentException

getInhabitantsByType

public Collection<Inhabitant<?>> getInhabitantsByType(String fullyQualifiedClassName)
Gets all the inhabitants that has the given implementation type name.

Specified by:
getInhabitantsByType in interface SimpleServiceLocator

getInhabitantByContract

public Inhabitant<?> getInhabitantByContract(String typeName)
Get the first inhabitant by contract

Parameters:
typeName - fullyQualifiedClassName
Returns:

getInhabitantsByContract

public Collection<Inhabitant<?>> getInhabitantsByContract(String fullyQualifiedClassName)
Specified by:
getInhabitantsByContract in interface SimpleServiceLocator

getAllContracts

public Iterator<String> getAllContracts()

getAllTypes

public Iterator<String> getAllTypes()

getInhabitantByContract

public Inhabitant getInhabitantByContract(String fullyQualifiedName,
                                          String name)

getInhabitants

public <T> Iterable<Inhabitant<? extends T>> getInhabitants(Class<T> contract,
                                                            String name)
                                                 throws ComponentException
Gets all the inhabitants that has the given contract and the given name

This method defers the actual instantiation of the component until Inhabitant.get() is invoked.

Returns:
Can be empty but never null.
Throws:
ComponentException

getInhabitantsByAnnotation

public Iterable<Inhabitant<?>> getInhabitantsByAnnotation(Class<? extends Annotation> contract,
                                                          String name)
                                                   throws ComponentException
Gets all the inhabitants that has the given contract annotation and the given name.

This method defers the actual instantiation of the component until Inhabitant.get() is invoked.

Returns:
Can be empty but never null.
Throws:
ComponentException

getByType

public <T> T getByType(Class<T> implType)
Description copied from interface: BaseServiceLocator
Gets the object of the given type.

Specified by:
getByType in interface BaseServiceLocator
Returns:
null if not found.

getByType

public <T> T getByType(String implType)
Description copied from interface: BaseServiceLocator
Gets the object of the given type.

Specified by:
getByType in interface BaseServiceLocator
Returns:
null if not found.

getProvider

public <T> Inhabitant<T> getProvider(Type type,
                                     String name)
Description copied from interface: SimpleServiceLocator
Gets an inhabitant from its type and optionally name

Specified by:
getProvider in interface SimpleServiceLocator
Parameters:
type - requested inhabitant type
name - optional name

getByContract

public <T> T getByContract(Class<T> contractType)
Gets the object that has the given contract.

If there are more than one of them, this method arbitrarily return one of them.

Specified by:
getByContract in interface BaseServiceLocator

getByContract

public <T> T getByContract(String contractType)
Specified by:
getByContract in interface BaseServiceLocator

release

public void release()
Releases all the components. Should be called for orderly shut-down of the system.

TODO: more javadoc needed



Copyright © 2012 Oracle Corporation. All Rights Reserved.