Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Service Dependency Management

The dependency handler manages OSGi service dependencies/requirements. It allows a component to consume service without managing service discovery, tracking and binding. The handler manages all this interaction and injects required service in the component.

Service Requirement

What's a service requirement?

A requirement represents a required service. Therefore, it manages the service lookup and the service binding. When an instance requires a service, the handler injects directly a service object inside a field, or invokes a method when a consistent service appears (or disappears). Service requirements can be:

  • Simple / Aggregate : the component can require one or several service providers
  • Mandatory / Optional : a component can declare an optional dependency
  • Filtered : a component can filter available providers
  • Dynamic / Static / Dynamic-Priority : the component can specify the binding policy

Dynamism & Instance Lifecycle

In OSGi™, services can appear and disappear dynamically. This implies dependencies can target a provdier provider which can appear or disappear dynamically.  So, dependencies need to manage this dynamism by tracking every time available services. At any moment, a dependency can be unresolved (i.e. no more provider can fulfill the requirement).  In the case of a mandatory requirement, the instance becomes invalid (an invalid instance is no more accessible externally, for example provided service are unpublished). If a service, resolving the unfilled dependency appears, the instance becomes valid. In consequence, dependencies affect directly the instance state, and must manage correctly OSGi dynamism to allow a complete unloading when a service goes away. As soon a mandatory dependency cannot be fulfilled, the instance is invalidated.

...

  • Static : if a bound service disappears, the instance is invalidated and cannot be revalidated (binding broken)
  • Dynamic-Priority: at each injection, the best provider is injected, or the providers array is sorted according to the OSGi Ranking policy.

Service Requirement Injection Mechanisms

The handler manages two types of injections:

...

Moreover, the two injections type can be merged. A component can declare a requirement containing both a field and 'binding'.

Field injection

Imagine a Hello service with one method 'getMessage' returning a "Hello Message". The following component implementation can use this service by attaching this service to a field and by using the field:

Code Block
java
java
public class HelloConsumer {
                private Hello m_hello;
                public doSomething() {
                               System.out.println(m_hello.getMesage());
                }
}

For this component, metadata could be:

Code Block
xml
xml
<component classname="...HelloConsumer">
    <requires field="m_hello"/>
    ...
</component>

The metadata contains a 'requires' element (representing the service dependency). This element has a field attribute. This attribute is the name of the field representing the service dependency in the implementation class. The implementation uses the field as a normal field without managing service interactions.

Method invocation

The second injection mechanism uses methods in the implementation class. By this way, the dynamics can be managed directly by the developer. Each dependency declares can declare two methods:

  • A bind method called when a service appears
  • An unbind method called when a service disappears

Moreover, callbacks can be in the component super class (in this case methods must be public).

...

These methods can have one of these four signatures:

  • Without any argument: the method is just a notification (method())
  • With the service object : the object is the implicated service object (method(Service svc))
  • With an OSGi service reference: the service reference appearing or disappearing (method(ServiceReference ref))
  • With the service object and the OSGi service reference (method(Service svc, ServiceReference ref))

The following component implementation shows an example of implementation using this mechanism:

Code Block
java
java
public class HelloConsumer {
  private Hello m_hello;

  public void bindHello(Hello h) { m_hello = h; }
  public void unbindHello() { m_hello = null; }
  public doSomething() { System.out.println(m_hello.getMesage()); }
}

For this component, metadata could be:

Code Block
xml
xml
<component classname="...HelloConsumer">
<requires>
    <callback type="bind" method="bindHello">
    <callback type="unbind" method="unbindHello">
</requires>
...
</component>

Note, that the bind the unbind method can be have different signaturesignatures. By using this mechanism, you need to be sure to manage the dynamism correctly.
(see See note on type discovery)

Field injections and Method invocations

The two mechanisms can be merged used together. In this case, the field receives the value before the bind method invocation. The following component shows an example of implementation using So, if the field is use in the method, the returned value will be up to date. The following component implementation uses this mechanism:

Code Block
java
java
public class HelloConsumer {
     private Hello m_hello; // Injected Field 

     public void bindHello() { System.out.println("Hello appears"); }
     public void unbindHello() { System.out.println("Hello disapears"); }
     public doSomething() { System.out.println(m_hello.getMesage()); }
}

For this component, metadata could be:

Code Block
xml
xml
<component classname="...HelloConsumer">
    <requires  field="m_hello">
        <callback type="bind" method="bindHello">
        <callback type="unbind" method="unbindHello">
    </requires>
    ...
</component>

Injection mechanisms &

...

lazy object creation

IPOJO creates objects only when required. When needed, iPOJO invokes the constructor of the implementation class. The implementation class can use field requirement because values are already injected. However, method dependencies are called just after the constructor. If the service already presents, the invocation of the methods are delayed just after the constructor invocation.

Some Examples

Simple Requirement

By default, a requirement is mandatory, non-filtered and simple (non-aggregate). The two previous examples illustrate this kind of dependency. When services goes away and appears, the service substitution is hidden. Field Fields attached to simple requirement points point always a consistent service object. For a simple dependency, the bind method is called once time at the beginning. If the service disappear when the service appears or just after the POJO constructor invocation is the service is available. When the service disappears the unbind method is called. The bind method is re-invoked as soon as another service provider is available. If This invocation occurs immediately if another service provider is presents when the used one disappearsif available. In this case, the instance is not invalidated.

Aggregate Requirement

When a component requires several providers of the same service, it declares an aggregate dependency.

Aggregate Dependency with field injection

Code Block
java
java
public class HelloConsumer {
     private Hello m_hellos[];
     public doSomething() {
             for(int I = 0; I < m_hellos.length; i++) { System.out.println(m_hellos[i].getMessage());}
       }
}

For this component, metadata could be:

Code Block
xml
xml
<component classname="...HelloConsumer">
    <requires field="m_hellos"/>
    ...
</component>

To declare an aggregate field for field requirement, you only need to declare an array (instead of a simple scalar type). IPOJO will create and inject the service object array. IPOJO discover that the dependency is aggregate during the bytecode introspection.

Note: The synchronization is managed by iPOJO. As soon as you are 'touching' a dependency in a method, iPOJO ensure that you will keep these objects until the end of the method. Imbricated Nested methods will share the same service object set.

Aggregate Dependency with method invocation

Code Block
java
java


public class HelloConsumer {
      private List m_hellos= new ArrayList();
      private void bindHello(Hello h) { m_hellos.add(h); }
      private void unbindHello(Hello h) { m_hellos.remove(h); }
      public synchronized doSomething() {
                     for(int I = 0; I < m_hellos.size(); i++) { System.out.println(m_hellos.get(i).getMessage());}
                }
        }
}

For this component, metadata could beThis requirement is configured as following:

Code Block
xml
xml
<dependency<requires  aggregate="true">
    <callback type="bind" method="bindHello">
    <callback type="unbind" method="unbindHello">
</dependency>requires>

In this case, iPOJO cannot detect if the dependency is aggregate or not. So, you need to add the 'aggregate' attribute. The bindHello and unbindHello will be called each time a Hello service appears or disappears.
Note: To avoid the list modification during the loop, you need synchronized the block. Indeed, as the field is not an iPOJO requirement, iPOJO will not manage the synchronization.

Optional

...

Requirement (non-aggregate)

An optional requirement does not invalidate the instance if it is not resolveddespite no providers are available. Moreover, it is possible to inject a default service implementation when no real providers are available.

Optional Requirement with field injection

Code Block
java
java
public class HelloConsumer {
         private Hello m_hello;
         public doSomething() {  System.out.println(m_hello.getMesage());  }
}

For this component, metadata could be:

Code Block
xml
xml
<component classname="...HelloConsumer">
<dependency    <requires field="m_hello" optional="true"/>
    ...
</component>

To declare an optional requirement, you need to add the 'optional' attribute. To avoid null pointer exception, iPOJO injects a Nullable object in the field when no service provider is available. The nullableobject implements the service interface, but does nothing. For further information see refer to the note about nullable object. Moreover, it is possible to set a default-implementation for the service. A default-implementation is a class implementing the service but used only when no others service providers are available. The default-implementation object will be injected instead of the Nullable objet.

Optional Dependency with method invocation

Code Block
java
java
public class HelloConsumer {
     private Hello m_hello;
     public void bindHello(Hello h) { m_hello = h; }
     public void unbindHello() { m_hello = null; }
     public doSomething() { if(m_hello != null) { System.out.println(m_hello.getMesage()); } }
}

For this component, metadata should be:

Code Block
xml
xml
<component classname="...HelloConsumer">
<requires optional="true">
    <callback type="bind" method="bindHello">
    <callback type="unbind" method="unbindHello">
</requires>
...
</component>

As for field requirement, the dependency metadata needs to contain the optional attribute. IPOJO invokes the method only when a 'real' service is available, so you need to test if m_hello is null before to use it.

Aggregate & Optional

...

Requirement

A dependency can be both aggregate and optional.

Aggregate & Optional Dependency with field injection

Code Block
java
java
public class HelloConsumer {
     private Hello m_hellos[];
     public doSomething() {
           for(int I = 0; I < m_hellos.length; i++) { System.out.println(m_hellos[i].getMessage());}
     }
}

For this component, metadata could be:

Code Block
xml
xml
<component classname="...HelloConsumer">
<requires field="m_hellos" optional="true"/>
...
</component>

To declare an optional & aggregate field requirement you need to write the optional attribute in the dependency metadata and to point on a field array. If no service available, iPOJO injects an empty array.

Aggregate & Optional Requirement with method invocation

Code Block
java
java


public class HelloConsumer {
     private List m_hellos<Hello> = new ArrayList<Hello>();
     private void bindHello(Hello h) { m_hellos.add(h); }
     private void unbindHello(Hello h) { m_hellos.remove(h); }
     public doSomething() {
        synchronized(m_hellossynchronized doSomething() {
               for(int I = 0; I < m_hellos.size(); i++) { System.out.println(m_hellos.get(i).getMessage());}
        }
     }
}

For this component, metadata could be:

Code Block
xml
xml
<requires aggregate="true" optional="true">
     <callback type="bind" method="bindHello">
     <callback type="unbind" method="unbindHello">
</requires>

In this case, you need to add the _'aggregate'_attribute and the _'optional'_attribute. The bindHello and unbindHello will be called each time a Hello service appears or disappears. These bind / unbind methods are not called when binding / unbinding a Nullable object (when both field and method are used).

Filtered Requirement

A filtered dependency applies an LDAP filter on service provider. IPOJO reuses OSGi LDAP filter ability. The following metadata illustrates how to use filters:

Code Block
xml
xml
<component classname="...HelloConsumer">
<requires filter="(language=fr)">
     <callback type="bind" method="bindHello">
     <callback type="unbind" method="unbindHello">
</requires>
...
</component>

To add a filter, just add a 'filter' attribute in your dependency containing the LDAP filter. IPOJO will select only provider matching with this filter.

Moreover, filters can be customize customized instance by instance. It is possible to specialize / change / add the filter of a component in the instance description. It is useful when you want to create different instances of the same component, with different filter. To do it, you have to identify your dependency with an 'id' attribute. Then, you can specialize adapt the filter of the dependency in the instance description by using the property "requires.filters". In this property you can specify each dependency identified by its id and the new value of the filter.

Code Block
xml
xml
<component className="org.apache.felix.ipojo.example.FilteredDependency" name="FOO">
	<requires field="m_foo" fiter="(foo.property=FOO)" id="id1">
		<callback type="bind" method="bind"/>
		<callback type="unbind" method="unbind"/>
	</requires>
</component>

<instance name="FOO1" component="FOO"/>

<instance name="FOO2" component="FOO">
	<property name="requires.filters">
		<property name="id1" value="(foo.property=BAR)"/>
	</property>
</instance>

<instance name="FOO3" component="FOO">
	<property name="requires.filters">
		<property name="id1" value="(foo.property=BAZ)"/>
	</property>
</instance>

The FOO component type declares a service dependency with the 'id1' id. This dependency has no filter by default. The first instance is just an instance of the FOO component type and does not modify the dependency. The second one adds a filter to the declared dependency to target providers with foo.property = BAR. The last one add adds another filter to the declared dependency. By using instance filter customization, it is possible to create complex applications where you avoid boinding problem binding problems by filtering dependencies instance by instance.

Binding Policies 

Three binding policies are supported inside iPOJO.

  • Dynamic policy (default): the binding are managed dynamically. At each injection, the same provider is injected if the provider is always available. Else a new one is chosen. For aggregate dependency, the array order does not change, ; new providers are placed at the end of the array.
  • Static policy: the binding is static. So, once bound a provider cannot disappear. If it disappears, the instance is invalidated and cannot be revalidated without stopping and restarting the instance.
  • Dynamic-priority policy: the binding is managed dynamically but the injected provider is selected by using the OSGi a ranking policy. Two injections can return two different providers, is a new provider is 'better' than the previous one, despite the first one is alway always available. For aggregate dependency, the array is sorted.

A static binding is declared as following:

Code Block
xml
xml
<component classname="...HelloConsumer">
    <requires field="m_hellos" policy="static"/>
    ...
</component>

A dynamic-priority binding is declared as following:

Code Block
xml
xml
<component classname="...HelloConsumer">
    <requires field="m_hellos" policy="dynamic-priority"/>
    ...
</component>

Requires Metadata

A requires element metadata can contains :

  • Field : name of the field representing the dependency in the component class
  • Interface : service interface
  • Optional: is the dependency an optional dependency?
  • Aggregate: is the dependency an aggregate dependency?
  • Filter : filter selecting service provider
  • Callback : allow to call a method on the component instances when a service provider (matching with the dependency) appears or disappears

Some of these attributes are optional. Indeed, either the component implementation contains the information; either iPOJO uses default behavior.

The field attribute is optional if callbacks are specified. The field attribute contains the name of the field of the component attached with this dependency.

The interface attribute describes the required service. This element is optional because the component implementation contains the same information (the type of the field). If the interface attribute has a value, the consistency of the information is checked. However, sometimes this attribute is mandatory if iPOJO cannot discover the type of the dependency.

The optional attribute describes if the dependency is optional or not. An optional dependency is always valid, and does not interact with the instance state. On the other hand, when a mandatory is no more valid the component state becomes INVALID.

The aggregate attribute determines if the dependency needs to inject several providers on just one. This attribute is optional if the dependency point on a field array.

The filter attribute contains the LDAP request on the service provider. By default, iPOJO use no filter, but you can specify a filter. For further information, see the OSGi specification.

The callback elements contain the name of method to call when a service provider matching with the dependency appears or disappears. This allows the component to be notified when a service provider arrives or goes away.

Technical details on service discovery and service invocation

...

By default, the dynamic-priority policy uses the OSGi service ranking policy. However, it is possible to customize the policy by adding the 'comparator' attribute. This attribute indicates the class name of a class implementing the java.util.Comparator interface. IPOJO will create an instance of your comparator and use it to sort service references (so your customized comparator needs to be able to sort OSGi Service Reference).

Code Block
xml
xml

<component classname="...HelloConsumer">
    <requires field="m_hellos" policy="dynamic-priority" comparator="my.comparator"/>
    ...
</component>

Note about nullable object & default-implementation

The instance implementation can use an optional dependency without any checking. Indeed, when an instance declares an optional dependency using field injection, iPOJO create on the fly a Nullable class implementing the service specification but doing nothing (mock object). Therefore, iPOJO cannot return a service to the instance, for an optional dependency, it returns a nullable object.

...

You can check if the returned object is a nullable object with the test: _m_ "myservice instanceof Nullable".

However, you can indicates indicate a default-implementation for your optional service. In this case, if no providers are found, iPOJO creates an instance of the default-implementation and injects it. The default-implementation attribute describes the class name of your implementation. The given class MUSTimplement the required service interface.

For example, the following componentr component uses a default implementation for a Log Service dependency:

Code Block
xml
xml
<component classname="...LogExample">
    <requires field="m_log" optional="true" default-implementation="org.apache.felix.ipojo.example.default.MyLogService"/>
    ...
</component>

If the log service is not available, iPOJO creates an object of the 'org.apache.felix.ipojo.example.default.MyLogService' class. This object is injected instead of a Nullable object. For instance, the default implementation can print messages on the System.err stream. The nullable object does no display anything.

Note about Callbacks

Dependency manages two type of callback: bind and unbind. A callback with a type "bind" is called each type that a service provider arrives and the binding is necessary. According to the cardinality of the dependency it means:

...

The method can receive in argument the service object or the service reference (in order to obtain service properties). The bind methods are delayed since a component instance POJO object is created.

Note on service interface discovery

The 'interface' attribute is generally optional except when iPOJO cannot discover the type of the service. IPOJO cannot infer the type when the dependency has no field and no callbacks do not receive the service object in parameter. In this case, you need to declare the service interface.