Annotations - Writing Components

Component Types

Before diving into all annotations, we must first introduce the different types of components DependencyManager is supporting. In Dependency Manager, you may use the following types of components, depending on what you need:

  • Component: Components are the main building blocks for OSGi applications. They can publish themselves as a service, and/or they can have dependencies. These dependencies will influence their life cycle as component will only be activated when all required dependencies are available.
  • Aspect Service: A service that provides a non-functional aspect on top of an existing service. In aspect oriented programming, an aspect, or interceptor can sit between a client and another target service used by the client. An Aspect Service first tracks a target service and is created once the target service is detected. Then the Aspect Service is provided, but with a higher ranking, and the client is transparently updated with the aspect. Aspects can be chained and may apply to the same target service (and in this case, the ranking of the Aspect service is used to chain aspects in the proper order).
  • Adapter Service: A Service that adapts another existing service into a new one. Like with aspects, sometimes you want to create adapters for certain services, which add certain behavior that results in the publication of (in this case) a different service. Adapters can dynamically be added and removed and allow you to keep your basic services implementations clean and simple, adding extra features on top of them in a modular way.

Now we have introduced the different types of components, here is the list of annotations, allowing to declare DependencyManager service components:

  • @Component: for declaring a Component that eventually publishes a singleton OSGi service as long as its dependencies are resolved.
  • @AspectService: provides a non-functional aspect on top of an existing service.
  • @AdapterService: creates an OSGi service that adapts another existing service into a new interface.
  • @BundleAdapterService: creates an OSGi service a service on top of a given bundle.
  • @ResourceAdapterService: creates an OSGi service on top of a specific Resource.
  • @FactoryConfigurationAdapterService: creates an OSGi service from ConfigAdmin, using a factoryPid, and a ManagedServiceFactory.

@Component

This annotation annotates an implementation class that optionally publishes an OSGi service, and optionally has some dependencies, with a managed lifecycle. The annotation has the following attributes:

  • provides: By default, the component is registered into the OSGi registry under all directly implemented interfaces. If no interfaces are implemented, then the component is not registered, but it still has a managed lifecycle, and may have some dependencies. If you need to explicitly define the list of interfaces (or classes) under which the component must be registered in the OSGi registry, then use the provides attribute. You can also set this property to an empty array of classes if you don't want at all your component to be exposed in the OSGi registry (even if it implements some interfaces).
  • properties: enumerates the list of properties that are part of the Service exposed by the component in the OSGi Registry. Each property is defined using the @Property annotation, which represents a key/value pair. When a value is actually an array of strings, then the values attribute of the @Property annotation can be used. This attribute is not the only way to specify OSGi Service properties (see Setting Service properties in the lifecycle section).
  • factoryMethod: may match a static method name from the annotated class which can be used to instantiate the component instance. Normally, DependencyManager instantiates the component using its class name, and with the default constructor of the class, but there are some cases where it is required to take control of how the component is created. For instance, this method may be used to create the component as a dynamic proxy ...
  • factorySet: The component factory ID. By default, a component is automatically instantiated as a singleton when the bundle is started, and when all required dependencies are satisfied. But when a component must be created, configured, or disposed dynamically, and when multiple instances of the same component are needed, a factorySet should be used. When you use this attribute, a java.util.Set<Dictionary> object is registered into the OSGi regitry, with a specific dm.factory.name property matching the ID you specify in the attribute. This Set<Dictionary> will act as a Factory API, and another component may define a dependency on this Set and add some configuration dictionaries in it, in order to fire some component instantiation/activation. There is one component instantiated per added dictionary, which is passed to component instances via a configurable callback method (using the factoryConfigure attribute). All public properties will be propagated along with eventual published service. A public property is a property which does not start with a dot ("."). Properties starting with a dot are considered private to the component, and won't be propagated to published service. This model is actually similar to the Declarative Service "Component Factories" concept, except that you don't have a dependency on a specific API, but rather on a basic jdk class (java.util.Set<Dictionary>). Notice that, unlike in Declarative Service, the component factory is provided once the component bundle is started, even if required dependencies are not satisfied. This is useful when the component want to dynamically configure its dependency filters. So, to summarize:
    • Each time a new Dictionary is added into the Set, then a new instance of the annotated component will be instantiated, and this dictionary is passed to the component callback specified with the factoryConfigure attribute.
    • Each time an existing Dictionary is re-added into the Set, then the corresponding component instance is updated, and the updated dictionary is also passed to the callback specified in the factoryConfigure attribute.
    • Each time an existing Dictionary is removed from the Set, then the corresponding component instance will be stopped and destroyed.
  • factoryConfigure: Sets the "configure" method name to be called with the factory configuration. This attribute only makes sense if the factorySet() attribute is used. If specified, then this attribute references a component callback method, which is called for providing the configuration supplied by the factory that instantiated this component. The current Service properties will be also updated with all public properties (which don't start with a dot).

Usage example:

 /**
   * This component will be activated once the bundle is started and when all required dependencies
   * are available.
   */
 @Component
 class X implements Z {
     @ConfigurationDependency(pid="MyPid")
     void configure(Dictionary conf) {
          // Configure or reconfigure our service.
     }

     @Start
     void start() {
         // Our component is starting and is about to be registered in the OSGi registry as a Z service.
     }

     public void doService() {
         // ...
     }
 }

Example using a factorySet, where the X component is instantiated/updated/disposed by another Y component:

  @Component(factorySet="MyComponentFactory", factoryConfigure="configure")
  class X implements Z {
      void configure(Dictionary conf) {
          // Configure or reconfigure our component. The conf is provided by the factory,
          // and all public properties (which don't start with a dot) are propagated with the
          // Service properties eventually specified in the properties annotation attribute.
      }

      @ServiceDependency
      void bindOtherService(OtherService other) {
          // store this require dependency
      }

      @Start
      void start() {
          // Our component is starting and is about to be registered in the OSGi registry as a Z service.
      }

      public void doService() {
          // ... part of Z interface
      }
  }

  /**
    * This class will instantiate some X component instances
    */
  @Component
  class Y {
      @ServiceDependency(filter="(dm.factory.name=MyComponentFactory)")
      Set<Dictionary> _XFactory; // This Set acts as a Factory API for creating X component instances.

      @Start
      void start() {
          // Instantiate a X component instance
          Dictionary x1 = new Hashtable() {{ put("foo", "bar1"); }};
          _XFactory.add(x1);

          // Instantiate another X component instance
          Dictionary x2 = new Hashtable() {{ put("foo", "bar2"); }};
          _XFactory.add(x2);

          // Update the first X component instance
          x1.put("foo", "bar1_modified");
          _XFactory.add(x1);

          // Destroy all components (Notice that invoking _XFactory.clear() also destroys every X instances)
          _XFactory.remove(x1);
          _XFactory.remove(x2);
      }
  }

@AspectService

Aspects allow you to define an interceptor, or chain of interceptors for a service (to add features like caching or logging, etc ...). The dependency manager intercepts the original service, and allows you to execute some code before invoking the original service ... The aspect will be applied to any service that matches the specified interface and filter and will be registered with the same interface and properties as the original service, plus any extra properties you supply here. It will also inherit all dependencies, and if you declare the original service as a member it will be injected.

Annotation attributes:

  • ranking: Sets the ranking of this aspect. Since aspects are chained, the ranking defines the order in which they are chained. Chain ranking is implemented as a service ranking so service lookups automatically retrieve the top of the chain.
  • service: Sets the service interface to apply the aspect to. By default, the directly implemented interface is used.
  • filter: Sets the filter condition to use with the service interface this aspect is applying to.
  • properties: Sets Additional properties to use with the aspect service registration.
  • field: Sets the field name where to inject the original service. By default, the original service is injected in any attributes in the aspect implementation that are of the same type as the aspect interface.
  • factoryMethod: Sets the static method used to create the AspectService implementation instance. The default constructor of the annotated class is used. The factoryMethod can be used to provide a specific aspect implements, like a DynamicProxy.

Usage example:

 @AspectService(ranking=10), properties={@Property(name="param", value="value")})
 class AspectService implements InterceptedService {
     // The service we are intercepting (injected by reflection)
     protected InterceptedService intercepted;
   
     public void doWork() {
        intercepted.doWork();
     }
 }

@AdapterService

Adapters, like with @AspectService, are used to "extend" existing services, and can publish different services based on the existing one. An example would be implementing a management interface for an existing service, etc .... When you annotate an adapter class with the @AdapterService annotation, it will be applied to any service that matches the implemented interface and filter. The adapter will be registered with the specified interface and existing properties from the original service plus any extra properties you supply here. If you declare the original service as a member it will be injected.

Annotation attributes:

  • adapteeService: Sets the adaptee service interface this adapter is applying to.
  • provides: Sets the adapter service interface(s). By default, the directly implemented interface(s) is (are) used.
  • properties: Sets some additional properties to use with the adapter service registration. By default, the adapter will inherit all adaptee service properties.
  • adapteeFilter: Sets the filter condition to use with the adapted service interface.
  • factoryMethod: Sets the static method used to create the adapter service implementation instance. By default, the default constructor of the annotated class is used.

Usage example: Here, the AdapterService is registered into the OSGI registry each time an AdapteeService is found from the registry. The AdapterImpl class adapts the AdapteeService to the AdapterService. The AdapterService will also have a service property (param=value), and will also include eventual service properties found from the AdapteeService:

 @AdapterService(adapteeService = AdapteeService.class, properties={@Property(name="param", value="value")})
 class AdapterImpl implements AdapterService {
     // The service we are adapting (injected by reflection)
     protected AdapteeService adaptee;
   
     public void doWork() {
        adaptee.mehod1();
        adaptee.method2();
     }
 }

@BundleAdapterService

Bundle adapters are similar to AdapterService, but instead of adapting a service, they adapt a bundle with a certain set of states (STARTED|INSTALLED|...), and provide a service on top of it.

The bundle adapter will be applied to any bundle that matches the specified bundle state mask and filter conditions, which may match some of the bundle OSGi manifest headers. For each matching bundle an adapter will be created based on the adapter implementation class. The adapter will be registered with the specified interface and with service properties found from the original bundle OSGi manifest headers plus any extra properties you supply here. If you declare the original bundle as a member it will be injected.

Annotation attributes:

  • filter: The filter used to match some OSGi manifest headers from a given bundle.
  • provides: The interface(s) to use when registering adapters. By default, the interface(s) directly implemented by the annotated class is (are) used.
  • properties: Additional properties to use with the service registration.
  • stateMask: the bundle state mask to apply. The mask is made up of the flags provided by the org.osgi.framework.Bundle states (UNINSTALLED | INSTALLED | RESOLVED | STARTING | STARTED | ACTIVE).
  • propagate: Specifies if manifest headers from the bundle should be propagated to the exposed service properties.
  • factoryMethod: Sets the static method used to create the BundleAdapterService implementation instance.

Usage Examples

In the following example, a "VideoPlayer" Service is registered into the OSGi registry each time an active bundle containing a "Video-Path" manifest header is detected:

 @BundleAdapterService(filter = "(Video-Path=*)", stateMask = Bundle.ACTIVE, propagate=true)
 public class VideoPlayerImpl implements VideoPlayer {
     Bundle bundle; // Injected by reflection
         
     void play() {
         URL mpegFile = bundle.getEntry(bundle.getHeaders().get("Video-Path"));
         // play the video provided by the bundle ...
     }
       
     void stop() {}
 }

@ResourceAdapterService

Resource adapters are things that adapt a resource instead of a service, and provide an adapter service on top of this resource. Resources are an abstraction that is introduced by the dependency manager, represented as a URL. They can be implemented to serve resources embedded in bundles, somewhere on a file system or in an http content repository server, or database.

The adapter will be applied to any resource that matches the specified filter condition, which can match some part of the resource URL (with "path", "protocol", "port", or "host" filters). For each matching resource an adapter will be created based on the adapter implementation class. The adapter will be registered with the specified interface and with any extra service properties you supply here. Moreover, the following service properties will be propagated from the resource URL:

  • host: this property exposes the host part of the resource URL
  • path: the resource URL path
  • protocol: the resource URL protocol
  • port: the resource URL port

Usage Examples:

Here, the "VideoPlayer" service provides a video service on top of any movie resources, with service properties "host"/"port"/"protocol"/"path" extracted from the resource URL:

     
 @ResourceAdapterService(filter = "(&(path=/videos/*.mkv)(host=localhost))", propagate = true)
 public class VideoPlayerImpl implements VideoPlayer {
     // Injected by reflection
     URL resource;
         
     void play() {} // play video referenced by this.resource     
     void stop() {} // stop playing the video
     void transcode() {} // ...
 }

@FactoryConfigurationAdapterService

Annotates a class that acts as a Factory Configuration Adapter Service. For each new Config Admin factory configuration matching the specified factoryPid, an instance of this service will be created. The adapter will be registered with the specified interface, and with the specified adapter service properties. Depending on the propagate parameter, every public factory configuration properties (which don't start with ".") will be propagated along with the adapter service properties.

Like in @ConfigurationDependency, you can optionally specify the meta types of your configurations for Web Console GUI customization (configuration heading/descriptions/default values/etc ...).

Annotation attributes:

  • provides: The interface(s) to use when registering adapters. By default, directly implemented interfaces will be registered in the OSGi registry.
  • properties: Adapter Service properties. Notice that public factory configuration is also registered in service properties, (only if propagate is true). Public factory configuration properties are those which don't starts with a dot (".").
  • factoryPid: Returns the factory pid whose configurations will instantiate the annotated service class. (By default, the pid is the service class name).
  • updated: The Update method to invoke (defaulting to "updated"), when a factory configuration is created or updated
  • propagate: Returns true if the configuration properties must be published along with the service. Any additional service properties specified directly are merged with these.
  • heading: The label used to display the tab name (or section) where the properties are displayed. Example: "Printer Service".
  • description: A human readable description of the PID this annotation is associated with. Example: "Configuration for the PrinterService bundle".
  • factoryMethod: Sets the static method used to create the adapter instance.
  • metadata: an array of "PropertyMetaData[]" annotations, specifying property types used to expose properties in web console

PropertyMetaData anotation attribute:

  • description: Returns the property description. The description may be localized and must describe the semantics of this type and any constraints. Example: "Select the log level for the Printer Service".
  • type: Return the property primitive type (java.lang.String.class by default). If must be either one of the following types:
    • String.class
    • Long.class
    • Integer.class
    • Character.class
    • Byte.class
    • Double.class
    • Float.class
    • Boolean.class
  • defaults: Return a default for this property. The object must be of the appropriate type as defined by the cardinality and getType(). The return type is a list of String objects that can be converted to the appropriate type. The cardinality of the return array must follow the absolute cardinality of this type. E.g. if the cardinality = 0, the array must contain 1 element. If the cardinality is 1, it must contain 0 or 1 elements. If it is -5, it must contain from 0 to max 5 elements. Note that the special case of a 0 cardinality, meaning a single value, does not allow arrays or vectors of 0 elements.
  • cardinality: Return the cardinality of this property (0 by default). The OSGi environment handles multi valued properties in arrays ([]) or in Vector objects. The return value is defined as follows:
    • x = Integer.MIN_VALUE no limit, but use Vector
    • x < 0 -x = max occurrences, store in Vector
    • x > 0 x = max occurrences, store in array []
    • x = Integer.MAX_VALUE no limit, but use array []
    • x = 0 1 occurrence required
  • required: Tells if this property is required or not.
  • optionLabels: Return a list of valid option labels for this property. The purpose of this method is to allow menus with localized labels. It is associated with the optionValues attribute. The labels returned here are ordered in the same way as the optionValues attribute values.
  • optionValues: Return a list of option values that this property can take. This list must be in the same sequence as the optionLabels attribute.

Usage Examples
Here, a "Dictionary" service instance is instantiated for each existing factory configuration instances matching the factory pid "DictionaryServiceFactory".

     @FactoryConfigurationAdapterService(factoryPid="DictionaryServiceFactory", updated="updated")
     public class DictionaryImpl implements DictionaryService
     {
         /**
          * The key of our config admin dictionary language.
          */
         final static String LANG = "lang";
         
         /**
          * The key of our config admin dictionary values.
          */
         final static String WORDS = "words";
         
         /**
          * We store all configured words in a thread-safe data structure, because ConfigAdmin
          * may invoke our updated method at any time.
          */
         private CopyOnWriteArrayList<String> m_words = new CopyOnWriteArrayList<String>();
         
         /**
          * Our Dictionary language.
          */
         private String m_lang;
     
         protected void updated(Dictionary<String, ?> config) {
             m_lang = (String) config.get(LANG);
             m_words.clear();
             String[] words = (String[]) config.get(WORDS);
             for (String word : words) {
                 m_words.add(word);
             }
         }   
         ...
     }

Here, this is the same example as above, but using meta types:

     @FactoryConfigurationAdapterService(
         factoryPid="DictionaryServiceFactory", 
         propagate=true, 
         updated="updated",
         heading="Dictionary Services",
         description="Declare here some Dictionary instances, allowing to instantiates some DictionaryService services for a given dictionary language",
         metadata={
             @PropertyMetaData(
                 heading="Dictionary Language",
                 description="Declare here the language supported by this dictionary. " +
                     "This property will be propagated with the Dictionary Service properties.",
                 defaults={"en"},
                 id=DictionaryImpl.LANG,
                 cardinality=0),
             @PropertyMetaData(
                 heading="Dictionary words",
                 description="Declare here the list of words supported by this dictionary. This properties starts with a Dot and won't be propagated with Dictionary OSGi service properties.",
                 defaults={"hello", "world"},
                 id=DictionaryImpl.WORDS,
                 cardinality=Integer.MAX_VALUE)
         }
     )  
     public class DictionaryImpl implements DictionaryService
     {
         /**
          * The key of our config admin dictionary language.
          */
         final static String LANG = "lang";
         
         /**
          * The key of our config admin dictionary values.
          */
         final static String WORDS = "words";
         
         /**
          * We store all configured words in a thread-safe data structure, because ConfigAdmin
          * may invoke our updated method at any time.
          */
         private CopyOnWriteArrayList<String> m_words = new CopyOnWriteArrayList<String>();
         
         /**
          * Our Dictionary language.
          */
         private String m_lang;
     
         protected void updated(Dictionary<String, ?> config) {
             m_lang = (String) config.get(LANG);
             m_words.clear();
             String[] words = (String[]) config.get(WORDS);
             for (String word : words) {
                 m_words.add(word);
             }
         }
         
         ...
     }
  • No labels