felix-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache Felix > Apache Felix Dependency Manager - Using Annotations - Dependencies
Date Mon, 07 Feb 2011 22:48:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/2036/9/1/_/styles/combined.css?spaceKey=FELIX&amp;forWysiwyg=true"
type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
    <h2><a href="https://cwiki.apache.org/confluence/display/FELIX/Apache+Felix+Dependency+Manager+-+Using+Annotations+-+Dependencies">Apache
Felix Dependency Manager - Using Annotations - Dependencies</a></h2>
    <h4>Page <b>edited</b> by             <a href="https://cwiki.apache.org/confluence/display/~pderop">Pierre
De Rop</a>
    </h4>
        <br/>
                         <h4>Changes (2)</h4>
                                 
    
<div id="page-diffs">
                    <table class="diff" cellpadding="0" cellspacing="0">
    
            <tr><td class="diff-snipped" >...<br></td></tr>
            <tr><td class="diff-unchanged" >{code} <br> <br></td></tr>
            <tr><td class="diff-changed-lines" >Usage example of a Service whose
dependency filter is configured from <span class="diff-deleted-words"style="color:#999;background-color:#fdd;text-decoration:line-through;">ConfigAdmin:</span>
<span class="diff-added-words"style="background-color: #dfd;">ConfigAdmin, using a &quot;named&quot;
dependency</span> <br></td></tr>
            <tr><td class="diff-added-lines" style="background-color: #dfd;">(please
check [Apache Felix Dependency Manager - Using Annotations - Lifecycle#Dynamic Dependency
Configuration] for more informations about &quot;named&quot; dependencies): <br></td></tr>
            <tr><td class="diff-unchanged" > <br>{code} <br></td></tr>
            <tr><td class="diff-snipped" >...<br></td></tr>
    
            </table>
    </div>                            <h4>Full Content</h4>
                    <div class="notificationGreySide">
        <h1><a name="ApacheFelixDependencyManager-UsingAnnotations-Dependencies-AnnotationsDependencies"></a>Annotations
- Dependencies</h1>

<p>This section describes the various dependencies supported with annotations.</p>

<h2><a name="ApacheFelixDependencyManager-UsingAnnotations-Dependencies-@ServiceDependency"></a>@ServiceDependency</h2>

<p>Annotates a method or a field for injecting a Service Dependency. When applied on
a class field, optional unavailable dependencies are injected with a NullObject.</p>

<p>Annotation attributes:</p>

<ul>
	<li><b>added</b>: The callback method to be invoked when the service is
available. This attribute is only meaningful when the annotation is applied on a class field.</li>
	<li><b>changed</b>: The callback method to be invoked when the service
properties have changed.</li>
	<li><b>removed</b>: The callback method to invoke when the service is lost.</li>
	<li><b>timeout</b>: The max time in millis to wait for when the dependency
is temporarily unavailable. Specifying a positive number allow to block the caller thread
between service updates. Only useful for required stateless dependencies that can be replaced
transparently. A Dynamic Proxy is used to wrap the actual service dependency (which must be
an interface). When the dependency goes away, an attempt is made to replace it with another
one which satisfies the service dependency criteria. If no service replacement is available,
then any method invocation (through the dynamic proxy) will block during a configurable timeout.
On timeout, an unchecked IllegalStateException exception is raised (but the service is not
deactivated).<br/>
Notice that the changed/removed callbacks are not used when the timeout parameter is &gt;
&#45;1.<br/>
&#45;1 means no timeout at all (default). 0 means that invocation on a missing service
will fail immediately. A positive number represents the max timeout in millis to wait for
the service availability.</li>
	<li><b>name</b>: The name used when dynamically configuring this dependency
from the init method. Specifying this attribute allows to dynamically configure the dependency
filter and required flag from the Service's init method. All unnamed dependencies will be
injected before the init() method; so from the init() method, you can then pick up whatever
information needed from already injected (unnamed) dependencies, and configure dynamically
your named dependencies, which will then be calculated once the init() method returns. Please
refer to <a href="/confluence/display/FELIX/Apache+Felix+Dependency+Manager+-+Using+Annotations+-+Lifecycle#ApacheFelixDependencyManager-UsingAnnotations-Lifecycle-DynamicDependencyConfiguration">Apache
Felix Dependency Manager &#45; Using Annotations &#45; Lifecycle#Dynamic Dependency
Configuration</a>.</li>
	<li><b>propagate</b>: Returns true if the dependency service properties
must be published along with the service. Any additional service properties specified directly
are merged with these.</li>
</ul>


<p>Usage Example: Here, the MyComponent component is injected with a dependency over
a "MyDependency" service.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
     @Component
     class MyComponent {
         @ServiceDependency(timeout=15000)
         MyDependency dependency;
         ...
     }
</pre>
</div></div>

<p>Usage example of a Service whose dependency filter is configured from ConfigAdmin,
using a "named" dependency<br/>
(please check <a href="/confluence/display/FELIX/Apache+Felix+Dependency+Manager+-+Using+Annotations+-+Lifecycle#ApacheFelixDependencyManager-UsingAnnotations-Lifecycle-DynamicDependencyConfiguration">Apache
Felix Dependency Manager &#45; Using Annotations &#45; Lifecycle#Dynamic Dependency
Configuration</a> for more informations about "named" dependencies):</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
      /**
        * A Service whose service dependency <span class="code-quote">"otherService"</span>
filter is configured from ConfigAdmin
        */
      @Service
      class X {
          <span class="code-keyword">private</span> Dictionary m_config;

          /**
           * Initialize our service from config ... and store the config <span class="code-keyword">for</span>
later usage (from our init method)
           */
          @ConfigurationDependency(pid=<span class="code-quote">"MyPid"</span>)
          void configure(Dictionary conf) {
               m_config = config;
          }

          /**
           * All unnamed dependencies are injected: we can now configure other named
           * dependencies, using the already injected configuration.
           * The returned Map will be used to configure our <span class="code-quote">"otherService"</span>
Dependency.
           */
          @Init
          Map init() {
              <span class="code-keyword">return</span> <span class="code-keyword">new</span>
HashMap() {{
                  put(<span class="code-quote">"otherService.filter"</span>, m_config.get(<span
class="code-quote">"filter"</span>));
                  put(<span class="code-quote">"otherService.required"</span>,
m_config.get(<span class="code-quote">"required"</span>));
              }};
          }

          /**
           * This named dependency filter/required flag will be configured by our init method
(see above).
           */
          @ServiceDependency(name=<span class="code-quote">"otherService"</span>)
          void bindOtherService(OtherService other) {
          }

          /**
           * All dependencies are injected and our service is now ready to be published.
           * Notice that you can also use the publisher service attribute <span class="code-keyword">if</span>
you need
           * to take control on service exposition.
           */
          @Start
          void start() {
          }
      }
</pre>
</div></div>




<h2><a name="ApacheFelixDependencyManager-UsingAnnotations-Dependencies-@ConfigurationDependency"></a>@ConfigurationDependency</h2>

<p>A configuration dependency is always required, and allows you to depend on the availability
of a valid configuration for your component. This dependency requires the OSGi Configuration
Admin Service.</p>

<p>Annotation attributes:</p>

<ul>
	<li><b>pid</b>: Returns the pid for a given service (by default, the pid
is the service class name).</li>
	<li><b>propagate</b>: Returns true if the configuration properties must
be published along with the service. Any additional service properties specified directly
are merged with these.</li>
	<li><b>heading</b>: The label used to display the tab name (or section)
where the properties are displayed. Example: "Printer Service".</li>
	<li><b>description</b>: A human readable description of the PID this annotation
is associated with. Example: "Configuration for the PrinterService bundle".</li>
	<li><b>metadata</b>: an array of PropertyMetadaData[] annotation describing
property types (see the FactoryConfigurationAdapterService section in the "Writing Components"
section.</li>
</ul>


<p>Usage Examples</p>

<p>In the following example, the "Printer" component depends on a configuration whose
PID name is "org.apache.felix.sample.Printer". This service will initialize its ip/port number
from the provided configuration:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
     <span class="code-keyword">package</span> org.apache.felix.sample;

     @Component
     <span class="code-keyword">public</span> class Printer {
         @ConfigurationDependency
         void updated(Dictionary config) {
             <span class="code-comment">// load printer ip/port from the provided dictionary.
</span>         }
     }
</pre>
</div></div>
<p>This other example shows how to specify a configuration dependency, as well as meta
data used to customize the WebConsole GUI. Using these meta data, you can specify for example
the default value for your configurations data, some descriptions, the cardinality of configuration
values, etc ...</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
     <span class="code-keyword">package</span> org.apache.felix.sample;

     @Component
     <span class="code-keyword">public</span> class Printer {
         @ConfigurationDependency(
             heading = <span class="code-quote">"Printer Service"</span>,
             description = <span class="code-quote">"Declare here parameters used to
configure the Printer service"</span>,
             metadata = {
                 @PropertyMetaData(heading = <span class="code-quote">"Ip Address"</span>,
                                   description = <span class="code-quote">"Enter the
ip address <span class="code-keyword">for</span> the Printer service"</span>,
                                   defaults = { <span class="code-quote">"127.0.0.1"</span>
},
                                   type = <span class="code-object">String</span>.class,
                                   id = <span class="code-quote">"IPADDR"</span>,
                                   cardinality = 0),
                 @PropertyMetaData(heading = <span class="code-quote">"Port <span
class="code-object">Number</span>"</span>,
                                   description = <span class="code-quote">"Enter the
port number <span class="code-keyword">for</span> the Printer service"</span>,
                                   defaults = { <span class="code-quote">"4444"</span>
},
                                   type = <span class="code-object">Integer</span>.class,
                                   id = <span class="code-quote">"PORTNUM"</span>,
                                   cardinality = 0)

             }
         )
         void updated(Dictionary config) {
             <span class="code-comment">// load configuration from the provided dictionary.
</span>         }
</pre>
</div></div>

<h2><a name="ApacheFelixDependencyManager-UsingAnnotations-Dependencies-@BundleDependency"></a>@BundleDependency</h2>

<p>A bundle dependency allows you to depend on a bundle in a certain set of states (INSTALLED&#124;RESOLVED&#124;STARTED&#124;...),
as indicated by a state mask. You can also use a filter condition that is matched against
all manifest entries. When applied on a class field, optional unavailable dependencies are
injected with a NullObject.</p>

<p>Attributes:</p>

<ul>
	<li><b>changed</b>: Returns the callback method to be invoked when the
service have changed.</li>
	<li><b>removed</b>: Returns the callback method to invoke when the service
is lost.</li>
	<li><b>required</b>: Returns whether the dependency is required or not.</li>
	<li><b>filter</b>: Returns the filter dependency</li>
	<li><b>stateMask</b>: Returns the bundle state mask (Bundle.INSTALLED &#124;
Bundle.ACTIVE etc ...).</li>
	<li><b>propagate</b>: Specifies if the manifest headers from the bundle
should be propagated to the service properties.</li>
	<li><b>name</b>: The name used when dynamically configuring this dependency
from the init method. Specifying this attribute allows to dynamically configure the dependency
filter and required flag from the Service's init method. All unnamed dependencies will be
injected before the init() method; so from the init() method, you can then pick up whatever
information needed from already injected (unnamed) dependencies, and configure dynamically
your named dependencies, which will then be calculated once the init() method returns.<br/>
Please refer to <a href="/confluence/display/FELIX/Apache+Felix+Dependency+Manager+-+Using+Annotations+-+Lifecycle#ApacheFelixDependencyManager-UsingAnnotations-Lifecycle-DynamicDependencyConfiguration">Apache
Felix Dependency Manager &#45; Using Annotations &#45; Lifecycle#Dynamic Dependency
Configuration</a>.</li>
</ul>


<p>Usage Examples</p>

<p>In the following example, the "SCR" Component allows to track all bundles containing
a specific "Service-Component" OSGi header, in order to load and manage all Declarative Service
components specified in the SCR xml documents referenced by the header:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
     @Component
     <span class="code-keyword">public</span> class SCR {
         @BundleDependency(required = <span class="code-keyword">false</span>,
                           removed = <span class="code-quote">"unloadServiceComponents"</span>,
                           filter = <span class="code-quote">"(Service-Component=*)"</span>)
         void loadServiceComponents(Bundle b) {
             <span class="code-object">String</span> descriptorPaths = (<span
class="code-object">String</span>) b.getHeaders().get(<span class="code-quote">"Service-Component"</span>);
             <span class="code-comment">// load all service component specified in the
XML descriptorPaths files ...
</span>         }

         void unloadServiceComponents(Bundle b) {
             <span class="code-comment">// unload all service component we loaded from
our <span class="code-quote">"loadServiceComponents"</span> method.
</span>         }
     }
</pre>
</div></div>
<h2><a name="ApacheFelixDependencyManager-UsingAnnotations-Dependencies-@ResourceDependency"></a>@ResourceDependency</h2>

<p>Annotates a method of field as a Resource Dependency. A resource dependency allows
you to depend on a 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.<br/>
A resource is a URL and you can use a filter condition based on protocol, host, port, and
path.</p>

<p>Attributes:</p>

<ul>
	<li><b>added</b>: Returns the callback method to be invoked when the service
is available. This attribute is only meaningful when the annotation is applied on a class
field.</li>
	<li><b>changed</b>: Returns the callback method to be invoked when the
service properties have changed.</li>
	<li><b>removed</b>: Returns the callback method to invoke when the service
is lost.</li>
	<li><b>required</b>: Returns whether the Service dependency is required
or not.</li>
	<li><b>filter</b>: Returns the Service dependency OSGi filter.</li>
	<li><b>propagate</b>: Specifies if the resource URL properties must be
propagated. If set to true, then the URL properties ("protocol"/"host"/"port"/"path") will
be propagated to the service properties of the component which is using this dependency.</li>
	<li><b>name</b>: The name used when dynamically configuring this dependency
from the init method. Specifying this attribute allows to dynamically configure the dependency
filter and required flag from the Service's init method. All unnamed dependencies will be
injected before the init() method; so from the init() method, you can then pick up whatever
information needed from already injected (unnamed) dependencies, and configure dynamically
your named dependencies, which will then be calculated once the init() method returns. Please
refer to <a href="/confluence/display/FELIX/Apache+Felix+Dependency+Manager+-+Using+Annotations+-+Lifecycle#ApacheFelixDependencyManager-UsingAnnotations-Lifecycle-DynamicDependencyConfiguration">Apache
Felix Dependency Manager &#45; Using Annotations &#45; Lifecycle#Dynamic Dependency
Configuration</a>.</li>
</ul>


<p>Usage Examples<br/>
Here, the "VideoPlayer" component plays any provided MKV video resources</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
     @Component
     <span class="code-keyword">public</span> class VideoPlayer {
         @ResourceDependency(required=<span class="code-keyword">false</span>,
filter=<span class="code-quote">"(path=/videos/*.mkv)"</span>)
         void playResource(URL video) { ... }
     }
</pre>
</div></div>
<p>And here is an example of a VideoProvider, which provides some videos using a web
URL. Notice that Resource providers need to depend on the DependencyManager API:</p>

<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">
     <span class="code-keyword">import</span> java.net.MalformedURLException;
     <span class="code-keyword">import</span> java.net.URL;
     <span class="code-keyword">import</span> java.util.HashMap;
     <span class="code-keyword">import</span> java.util.Map;

     <span class="code-keyword">import</span> org.apache.felix.dm.ResourceHandler;
     <span class="code-keyword">import</span> org.apache.felix.dm.ResourceUtil;
     <span class="code-keyword">import</span> org.apache.felix.dm.annotation.api.Component;
     <span class="code-keyword">import</span> org.apache.felix.dm.annotation.api.Init;
     <span class="code-keyword">import</span> org.apache.felix.dm.annotation.api.ServiceDependency;
     <span class="code-keyword">import</span> org.osgi.framework.BundleContext;
     <span class="code-keyword">import</span> org.osgi.framework.Filter;
     <span class="code-keyword">import</span> org.osgi.framework.InvalidSyntaxException;

     @Component
     <span class="code-keyword">public</span> class VideoProvider
     {
         <span class="code-comment">// Injected by reflection
</span>         <span class="code-keyword">private</span> <span class="code-keyword">volatile</span>
BundleContext context;
         <span class="code-comment">// List of known resource handlers
</span>         <span class="code-keyword">private</span> Map&lt;ResourceHandler,
Filter&gt; m_handlers = <span class="code-keyword">new</span> HashMap&lt;ResourceHandler,
Filter&gt;();
         <span class="code-comment">// List of known video resources
</span>         <span class="code-keyword">private</span> URL[] m_videos;

         @Init
         void init() <span class="code-keyword">throws</span> MalformedURLException
         {
            m_videos = <span class="code-keyword">new</span> URL[] {
                    <span class="code-keyword">new</span> URL(<span class="code-quote">"http:<span
class="code-comment">//localhost:8080/videos/video1.mkv"</span>),
</span>                    <span class="code-keyword">new</span> URL(<span
class="code-quote">"http:<span class="code-comment">//localhost:8080/videos/video2.mkv"</span>),
</span>             };
         }

         <span class="code-comment">// Track resource handlers
</span>         @ServiceDependency(required = <span class="code-keyword">false</span>)
         <span class="code-keyword">public</span> void add(Map&lt;<span
class="code-object">String</span>, <span class="code-object">String</span>&gt;
serviceProperties, ResourceHandler handler) <span class="code-keyword">throws</span>
InvalidSyntaxException
         {
             <span class="code-object">String</span> filterString = serviceProperties.get(<span
class="code-quote">"filter"</span>);
             filterString = (filterString != <span class="code-keyword">null</span>)
? filterString : <span class="code-quote">"(path=*)"</span>;
             Filter filter = context.createFilter(filterString);
             <span class="code-keyword">synchronized</span> (<span class="code-keyword">this</span>)
             {
                 m_handlers.put(handler, filter);
             }
             <span class="code-keyword">for</span> (URL video : m_videos)
             {
                 <span class="code-keyword">if</span> (filter.match(ResourceUtil.createProperties(video)))
                 {
                     handler.added(video);
                 }
             }
         }
     }
</pre>
</div></div>
    </div>
        <div id="commentsSection" class="wiki-content pageSection">
        <div style="float: right;">
            <a href="https://cwiki.apache.org/confluence/users/viewnotifications.action"
class="grey">Change Notification Preferences</a>
        </div>
        <a href="https://cwiki.apache.org/confluence/display/FELIX/Apache+Felix+Dependency+Manager+-+Using+Annotations+-+Dependencies">View
Online</a>
        |
        <a href="https://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=23335754&revisedVersion=8&originalVersion=7">View
Changes</a>
                |
        <a href="https://cwiki.apache.org/confluence/display/FELIX/Apache+Felix+Dependency+Manager+-+Using+Annotations+-+Dependencies?showComments=true&amp;showCommentArea=true#addcomment">Add
Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message