blob: fc4887d924923878cf58b3abb7bcc264a5b07327 [file] [log] [blame]
Karl Pauls78470432010-02-14 22:52:56 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html><head>
3
4
5
6 <title>Apache Felix - Apache Felix Framework Launching and Embedding</title>
7 <link rel="stylesheet" href="apache-felix-framework-launching-and-embedding_files/site.css" type="text/css" media="all">
8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
9 </head><body>
10 <div class="title"><div class="logo"><a href="http://felix.apache.org/site/index.html"><img alt="Apache Felix" src="apache-felix-framework-launching-and-embedding_files/logo.png" border="0"></a></div><div class="header"><a href="http://www.apache.org/"><img alt="Apache" src="apache-felix-framework-launching-and-embedding_files/apache.png" border="0"></a></div></div>
11 <div class="menu">
12<ul>
13 <li><a href="http://felix.apache.org/site/news.html" title="news">news</a></li>
14 <li><a href="http://felix.apache.org/site/license.html" title="license">license</a></li>
15 <li><a href="http://felix.apache.org/site/downloads.cgi" rel="nofollow">downloads</a></li>
16 <li><a href="http://felix.apache.org/site/documentation.html" title="documentation">documentation</a></li>
17 <li><a href="http://felix.apache.org/site/mailinglists.html" title="mailinglists">mailing lists</a></li>
18 <li><a href="http://felix.apache.org/site/contributing.html" title="Contributing">contributing</a></li>
19 <li><a href="http://www.apache.org/" rel="nofollow">asf</a></li>
20 <li><a href="http://www.apache.org/foundation/sponsorship.html" rel="nofollow">sponsorship</a></li>
21 <li><a href="http://www.apache.org/foundation/thanks.html" rel="nofollow">sponsors</a>
22<!-- ApacheCon Ad -->
23<iframe src="apache-felix-framework-launching-and-embedding_files/button.html" style="border-width: 0pt; float: left;" frameborder="0" height="135" scrolling="no" width="135"></iframe>
24<p style="height: 100px;">
25<!-- ApacheCon Ad -->
26</p></li></ul> </div>
27 <div class="main">
28<h1><a name="ApacheFelixFrameworkLaunchingandEmbedding-ApacheFelixFrameworkLaunchingandEmbedding"></a>Apache Felix Framework Launching and Embedding</h1>
29
30<p><em>[This document describes framework launching introduced in Felix
312.0.0 and is incompatible with older versions of the Felix framework.]</em></p>
32
33<ul>
34 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-introduction">Introduction</a></li>
35 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-overview">API Overview</a>
36 <ul>
37 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-creatingandconfiguring">Creating and Configuring the Framework Instance</a></li>
38 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-startinginstance">Starting the Framework Instance</a></li>
39 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-stoppinginstance">Stopping the Framework Instance</a></li>
40 </ul>
41 </li>
42 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-launching">Launching Felix</a>
43 <ul>
44 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-standardlauncher">Standard Felix Launcher</a></li>
45 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-customlauncher">Custom Felix Launcher</a></li>
46 </ul>
47 </li>
48 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-embedding">Embedding Felix</a>
49 <ul>
50 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-hostinteraction">Host/Felix Interaction</a></li>
51 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-hostservices">Providing Host Application Services</a></li>
52 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-hostserviceusage">Using Services Provided by Bundles</a>
53 <ul>
54 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-servicereflection">Using Bundle Services via Reflection</a></li>
55 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-serviceother">Other Approaches</a></li>
56 </ul>
57 </li>
58 </ul>
59 </li>
60 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-caveat">Caveat</a></li>
61 <li><a href="#ApacheFelixFrameworkLaunchingandEmbedding-feedback">Feedback</a></li>
62</ul>
63
64
65<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-introduction"></a></p>
66
67<h1><a name="ApacheFelixFrameworkLaunchingandEmbedding-Introduction"></a>Introduction</h1>
68
69<p>The Apache Felix framework is intended to be easily launchable and
70embeddable. For example, Felix avoids the use of system properties for
71configuration, since these are globals and can cause interference if
72multiple framework instances are created in the same VM. Felix also
73tries to multiplex singleton facilities, like the URL stream handler
74factory. The goal is to make it possible to use Felix in as many
75scenarios as possible; however, this is still just a goal. In other
76words, this is a work in progress and if any issues arise, it would be
77greatly appreciated if they are brought to the attention of the Felix
78community. The next section provides a Felix API overview, while the
79remainder of the document is divided into two sections, one focusing on
80how to launch Felix and one focusing on how to embed Felix into a host
81application.</p>
82
83<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-overview"></a></p>
84
85<h1><a name="ApacheFelixFrameworkLaunchingandEmbedding-APIOverview"></a>API Overview</h1>
86
87<p>The Felix framework is implemented by the <tt>org.apache.felix.framework.Felix</tt> class or just <tt>Felix</tt>
88for short. As part of the R4.2 OSGi specification, the launching and
89embedding API of the OSGi framework has been standardized. The approach
90is to have the framework implement the <tt>org.osgi.framework.launch.Framework</tt> interface, which extends the <tt>org.osgi.framework.Bundle</tt> interface. These interfaces provide the necessary means to launch and manage framework instances. The <tt>Bundle</tt> interface is defined as:</p>
91
92<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
93<pre class="code-java"><span class="code-keyword">public</span> <span class="code-keyword">interface</span> Bundle
94{
95 BundleContext getBundleContext();
96 <span class="code-object">long</span> getBundleId();
97 URL getEntry(<span class="code-object">String</span> name);
98 Enumeration getEntryPaths(<span class="code-object">String</span> path);
99 Enumeration findEntries(<span class="code-object">String</span> path, <span class="code-object">String</span> filePattern, <span class="code-object">boolean</span> recurse);
100 Dictionary getHeaders();
101 Dictionary getHeaders(<span class="code-object">String</span> locale);
102 <span class="code-object">long</span> getLastModified();
103 <span class="code-object">String</span> getLocation();
104 URL getResource(<span class="code-object">String</span> name);
105 Enumeration getResources(<span class="code-object">String</span> name) <span class="code-keyword">throws</span> IOException;
106 ServiceReference[] getRegisteredServices();
107 ServiceReference[] getServicesInUse();
108 <span class="code-object">int</span> getState();
109 <span class="code-object">String</span> getSymbolicName();
110 Version getVersion();
111 <span class="code-object">boolean</span> hasPermission(<span class="code-object">Object</span> obj);
112 <span class="code-object">Class</span> loadClass(<span class="code-object">String</span> name) <span class="code-keyword">throws</span> ClassNotFoundException;
113 void start() <span class="code-keyword">throws</span> BundleException;
114 void stop() <span class="code-keyword">throws</span> BundleException;
115 void uninstall() <span class="code-keyword">throws</span> BundleException;
116 void update() <span class="code-keyword">throws</span> BundleException;
117 void update(InputStream is) <span class="code-keyword">throws</span> BundleException;
118}
119</pre>
120</div></div>
121
122<p>The <tt>Framework</tt> interface is defined as:</p>
123
124<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
125<pre class="code-java"><span class="code-keyword">public</span> <span class="code-keyword">interface</span> Framework <span class="code-keyword">extends</span> Bundle
126{
127 void init();
128 FrameworkEvent waitForStop();
129}
130</pre>
131</div></div>
132
133<p>To actually construct a framework instance, the R4.2 specification defines the FrameworkFactory interface:</p>
134
135<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
136<pre class="code-java"><span class="code-keyword">public</span> <span class="code-keyword">interface</span> FrameworkFactory
137{
138 Framework newFramework(Map configMap);
139}
140</pre>
141</div></div>
142
143<p>The framework factory can be used to create configured framework instances. It is obtained following the standard <tt>META-INF/services</tt> approach.</p>
144
145<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-creatingandconfiguring"></a></p>
146
147<h2><a name="ApacheFelixFrameworkLaunchingandEmbedding-CreatingandConfiguringtheFrameworkInstance"></a>Creating and Configuring the Framework Instance</h2>
148
149<p>You use the framework factory to construct and configure a framework
150instance (or by directly instantiating the Felix class). The
151configuration map may contain the following OSGi standard properties:</p>
152
153<ul>
154 <li><tt>org.osgi.framework.system.packages</tt> - specifies a
155list of packages the system bundle should export from the environment;
156if this is not set, then the framework uses a reasonable default fault.</li>
157 <li><tt>org.osgi.framework.system.packages.extra</tt>
158- specifies a list of additional packages the system bundle should
159export from the environment that are appended to the packages specified
160in <tt>org.osgi.framework.system.packages</tt>; there is no default value for this property.</li>
161 <li><tt>org.osgi.framework.bootdelegation</tt>
162- specifies a list of packages that should be made implicitly available
163to all bundles from the environment (i.e., no need to import them);
164there is no default value for this property and its use should be
165avoided.</li>
166 <li><tt>org.osgi.framework.storage</tt> - specifies the
167path to a directory, which will be created if it does not exist, to use
168for bundle cache storage; the default value for this property is "<tt>felix-cache</tt>" in the current working directory.</li>
169 <li><tt>org.osgi.framework.storage.clean</tt>
170- specifies whether the bundle cache should be flushed; the default
171value for this property is "none", but it can be changed to
172"onFirstInit" to flush the bundle cache when the framework is
173initialized.</li>
174 <li><tt>org.osgi.framework.startlevel.beginning</tt> - specifies the start level the framework enters upon startup; the default value for this property is 1.</li>
175</ul>
176
177
178<p>Felix also has the following, non-standard configuration properties:</p>
179
180<ul>
181 <li><tt>felix.cache.rootdir</tt> - specifies which directory should be used to calculate absolute paths when relative paths are used for the <tt>org.osgi.framework.storage</tt> property; the default value for this property is the current working directory.</li>
182 <li><tt>felix.systembundle.activators</tt> - specifies a <tt>List</tt> of <tt>BundleActivator</tt>
183instances that are started/stopped when the System Bundle is
184started/stopped; the specified instances will receive the System
185Bundle's <tt>BundleContext</tt> when invoked.</li>
186 <li><tt>felix.log.logger</tt> - specifies an instance of <tt>org.apache.felix.framework.util.Logger</tt> that the framework uses as its default logger.</li>
187 <li><tt>felix.log.level</tt> - specifies an integer <tt>String</tt>
188whose value indicates the degree of logging reported by the framework;
189the default value is "1" and "0" turns off logging completely,
190otherwise log levels match those specified in the OSGi Log Service
191(i.e., 1 = error, 2 = warning, 3 = information, and 4 = debug).</li>
192 <li><tt>felix.startlevel.bundle</tt> - specifies the start level for newly installed bundles; the default value is 1.</li>
193 <li><tt>felix.bootdelegation.implicit</tt>
194- specifies whether or not the framework should try to guess when to
195boot delegate when external code tries to load classes or resources;
196the default value is "<tt>true</tt>".</li>
197 <li><tt>framework.service.urlhandlers</tt> - specifies whether or not to activate the URL Handlers service for the framework instance; the default value is "<tt>true</tt>", which results in the <tt>URL.setURLStreamHandlerFactory()</tt> and <tt>URLConnection.setContentHandlerFactory()</tt> being called.</li>
198</ul>
199
200
201<p>The configuration map is copied and the keys are treated as case
202insensitive. You are not able to change the framework's configuration
203after construction. If you need a different configuration, you must
204create a new framework instance.</p>
205
206<div class="panelMacro"><table class="warningMacro"><colgroup><col width="24"><col></colgroup><tbody><tr><td valign="top"><img src="apache-felix-framework-launching-and-embedding_files/forbidden.gif" alt="" align="absmiddle" border="0" height="16" width="16"></td><td><b>WARNING</b><br><p>Felix configuration properties have change considerably starting from <tt>1.4.0</tt>; if you are upgrading from an earlier version, the <a href="http://felix.apache.org/site/apache-felix-framework-usage-documentation.html#ApacheFelixFrameworkUsageDocumentation-migrating">usage document</a> describes the configuration property changes.</p></td></tr></tbody></table></div>
207
208<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-startinginstance"></a></p>
209
210<h2><a name="ApacheFelixFrameworkLaunchingandEmbedding-StartingtheFrameworkInstance"></a>Starting the Framework Instance</h2>
211
212<p>The <tt>start()</tt> method is used to start the framework instance. If the <tt>init()</tt> method was not invoked prior to calling <tt>start()</tt>, then it is invoked by <tt>start()</tt>. The two methods result in two different framework state transitions:</p>
213
214<ul>
215 <li><tt>init()</tt> results in the framework instance in the <tt>Bundle.STARTING</tt> state.</li>
216 <li><tt>start()</tt> results in the framework instance in the <tt>Bundle.ACTIVE</tt> state.</li>
217</ul>
218
219
220<p>The <tt>init()</tt> method is necessary since the framework does not have a <tt>BundleContext</tt> when it is first created, so a transition to the <tt>Bundle.STARTING</tt> state is required to acquire its context (via <tt>Bundle.getBundleContext()</tt>) for performing various tasks, such as installing bundles. Note that Felix also provides the <tt>felix.systembundle.activators</tt> property that serves a similar purpose, but is not standard. After the <tt>init()</tt> method completes, the follow actions have been performed:</p>
221
222<ul>
223 <li>Event handling is enabled.</li>
224 <li>The security manager is installed if it is enabled.</li>
225 <li>The framework is set to start level 0.</li>
226 <li>All bundles in the bundle caches are reified and their state is set to <tt>Bundle.INSTALLED</tt>.</li>
227 <li>The framework gets a valid <tt>BundleContext</tt>.</li>
228 <li>All framework-provided services are made available (e.g., PackageAdmin, StartLevel, etc.).</li>
229 <li>The framework enters the <tt>Bundle.STARTING</tt> state.</li>
230</ul>
231
232
233<p>A call to <tt>start()</tt> is necessary to start the framework instance, if the <tt>init()</tt> method is invoked manually. Invoking <tt>init()</tt> or <tt>start()</tt> on an already started framework as no effect.</p>
234
235<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-stoppinginstance"></a></p>
236
237<h2><a name="ApacheFelixFrameworkLaunchingandEmbedding-StoppingtheFrameworkInstance"></a>Stopping the Framework Instance</h2>
238
239<p>To stop the framework instance, invoke the <tt>stop()</tt> method, which will asynchronously stop the framework. To know when the framework has finished its shutdown sequence, use the <tt>waitForStop()</tt> method to wait until it is complete. A stopped framework will be in the <tt>Bundle.RESOLVED</tt> state. It is possible to restart the framework, using the normal combination of <tt>init()</tt>/<tt>start()</tt> methods as previously described.</p>
240
241<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-launching"></a></p>
242
243<h1><a name="ApacheFelixFrameworkLaunchingandEmbedding-LaunchingaFramework"></a>Launching a Framework</h1>
244
245<p>Launching a framework is fairly simple and involves only four steps:</p>
246
247<ol>
248 <li>Define some configuration properties.</li>
249 <li>Obtain framework factory.</li>
250 <li>Use factory to create framework with the configuration properties.</li>
251 <li>Invoke the <tt>Framework.start()</tt> method.</li>
252</ol>
253
254
255<p>In reality, the first step is optional, since all properties will
256have reasonable defaults, but if you are creating a launcher you will
257generally want to more than that, such as automatically installing and
258starting bundles when you start the framework instance. The default
259Felix launcher defines reusable functionality to automatically install
260and/or start bundles upon framework startup; see the <a href="http://felix.apache.org/site/apache-felix-framework-usage-documentation.html#ApacheFelixFrameworkUsageDocumentation-configuringfelix">usage document</a> for more information on configuring Felix and on the various configuration properties.</p>
261
262<p>The remainder of this section describes how the standard Felix
263launcher works as well as how to create a custom launcher for Felix.</p>
264
265<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-standardlauncher"></a></p>
266
267<h2><a name="ApacheFelixFrameworkLaunchingandEmbedding-StandardFelixFrameworkLauncher"></a>Standard Felix Framework Launcher</h2>
268
269<p>The standard Felix launcher is very simple and is not intended to
270solve every possible requirement; it is intended to work for most
271standard situations. Most special launching requirements should be
272resolved by creating a custom launcher. This section describes how the
273standard launcher works. The following code represents the complete <tt>main()</tt> method of the standard launcher, each numbered comment will be described in more detail below:</p>
274
275<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
276<pre class="code-java"><span class="code-keyword">public</span> <span class="code-keyword">static</span> void main(<span class="code-object">String</span>[] args) <span class="code-keyword">throws</span> Exception
277{
278 <span class="code-comment">// (1) Check <span class="code-keyword">for</span> command line arguments and verify usage.
279</span> <span class="code-object">String</span> bundleDir = <span class="code-keyword">null</span>;
280 <span class="code-object">String</span> cacheDir = <span class="code-keyword">null</span>;
281 <span class="code-object">boolean</span> expectBundleDir = <span class="code-keyword">false</span>;
282 <span class="code-keyword">for</span> (<span class="code-object">int</span> i = 0; i &lt; args.length; i++)
283 {
284 <span class="code-keyword">if</span> (args[i].equals(BUNDLE_DIR_SWITCH))
285 {
286 expectBundleDir = <span class="code-keyword">true</span>;
287 }
288 <span class="code-keyword">else</span> <span class="code-keyword">if</span> (expectBundleDir)
289 {
290 bundleDir = args[i];
291 expectBundleDir = <span class="code-keyword">false</span>;
292 }
293 <span class="code-keyword">else</span>
294 {
295 cacheDir = args[i];
296 }
297 }
298 <span class="code-keyword">if</span> ((args.length &gt; 3) || (expectBundleDir &amp;&amp; bundleDir == <span class="code-keyword">null</span>))
299 {
300 <span class="code-object">System</span>.out.println(<span class="code-quote">"Usage: [-b &lt;bundle-deploy-dir&gt;] [&lt;bundle-cache-dir&gt;]"</span>);
301 <span class="code-object">System</span>.exit(0);
302 }
303
304 <span class="code-comment">// (2) Load system properties.
305</span> Main.loadSystemProperties();
306
307 <span class="code-comment">// (3) Read configuration properties.
308</span> Properties configProps = Main.loadConfigProperties();
309 <span class="code-keyword">if</span> (configProps == <span class="code-keyword">null</span>)
310 {
311 <span class="code-object">System</span>.err.println(<span class="code-quote">"No "</span> + CONFIG_PROPERTIES_FILE_VALUE + <span class="code-quote">" found."</span>);
312 configProps = <span class="code-keyword">new</span> Properties();
313 }
314
315 <span class="code-comment">// (4) Copy framework properties from the system properties.
316</span> Main.copySystemProperties(configProps);
317
318 <span class="code-comment">// (5) Use the specified auto-deploy directory over <span class="code-keyword">default</span>.
319</span> <span class="code-keyword">if</span> (bundleDir != <span class="code-keyword">null</span>)
320 {
321 configProps.setProperty(AutoProcessor.AUTO_DEPLOY_DIR_PROPERY, bundleDir);
322 }
323
324 <span class="code-comment">// (6) Use the specified bundle cache directory over <span class="code-keyword">default</span>.
325</span> <span class="code-keyword">if</span> (cacheDir != <span class="code-keyword">null</span>)
326 {
327 configProps.setProperty(Constants.FRAMEWORK_STORAGE, cacheDir);
328 }
329
330 <span class="code-comment">// (7) Add a shutdown hook to clean stop the framework.
331</span> <span class="code-object">String</span> enableHook = configProps.getProperty(SHUTDOWN_HOOK_PROP);
332 <span class="code-keyword">if</span> ((enableHook == <span class="code-keyword">null</span>) || !enableHook.equalsIgnoreCase(<span class="code-quote">"<span class="code-keyword">false</span>"</span>))
333 {
334 <span class="code-object">Runtime</span>.getRuntime().addShutdownHook(<span class="code-keyword">new</span> <span class="code-object">Thread</span>() {
335 <span class="code-keyword">public</span> void run()
336 {
337 <span class="code-keyword">try</span>
338 {
339 <span class="code-keyword">if</span> (m_fwk != <span class="code-keyword">null</span>)
340 {
341 m_fwk.stop();
342 m_fwk.waitForStop(0);
343 }
344 }
345 <span class="code-keyword">catch</span> (Exception ex)
346 {
347 <span class="code-object">System</span>.err.println(<span class="code-quote">"Error stopping framework: "</span> + ex);
348 }
349 }
350 });
351 }
352
353 <span class="code-comment">// Print welcome banner.
354</span> <span class="code-object">System</span>.out.println(<span class="code-quote">"\nWelcome to Felix"</span>);
355 <span class="code-object">System</span>.out.println(<span class="code-quote">"================\n"</span>);
356
357 <span class="code-keyword">try</span>
358 {
359 <span class="code-comment">// (8) Create an instance and initialize the framework.
360</span> FrameworkFactory factory = getFrameworkFactory();
361 m_fwk = factory.newFramework(configProps);
362 m_fwk.init();
363 <span class="code-comment">// (9) Use the system bundle context to process the auto-deploy
364</span> <span class="code-comment">// and auto-install/auto-start properties.
365</span> AutoProcessor.process(configProps, m_fwk.getBundleContext());
366 <span class="code-comment">// (10) Start the framework.
367</span> m_fwk.start();
368 <span class="code-comment">// (11) Wait <span class="code-keyword">for</span> framework to stop to exit the VM.
369</span> m_fwk.waitForStop(0);
370 <span class="code-object">System</span>.exit(0);
371 }
372 <span class="code-keyword">catch</span> (Exception ex)
373 {
374 <span class="code-object">System</span>.err.println(<span class="code-quote">"Could not create framework: "</span> + ex);
375 ex.printStackTrace();
376 <span class="code-object">System</span>.exit(-1);
377 }
378}
379</pre>
380</div></div>
381
382<p>The general steps of the standard launcher are quite straightforward:</p>
383
384<ol>
385 <li>The launcher supports setting the auto-deploy directory (with the <tt>-b</tt>
386switch) and setting the bundle cache path with a single argument, so
387check for this and issue a usage message it there are more than one
388arguments.</li>
389 <li>Load any system properties specified in the <tt>system.properties</tt> file; this file is typically located in the <tt>conf/</tt> directory of the Felix installation directory, but it can be specified directly using the <tt>felix.system.properties</tt>
390system property. This file is not needed to launch Felix and is
391provided merely for convenience when system properties must be
392specified. The file is a standard Java properties file, but it also
393supports property substitution using <tt>${&lt;property-name</tt>} syntax. Property substitution can be nested; only system properties will be used for substitution.</li>
394 <li>Load any configuration properties specified in the <tt>config.properties</tt> file; this file is typically located in the <tt>conf/</tt> directory of the Felix installation directory, but it can be specified directly using the <tt>felix.config.properties</tt>
395system property. This file is used to configure the Felix instance
396created by the launcher. The file is a standard Java properties file,
397but it also supports property substitution using "<tt>${&lt;property-name&gt;</tt>}"
398syntax. Property substitution can be nested; configuration and system
399properties will be used for substitution with configuration properties
400having precedence.</li>
401 <li>For convenience, any configuration
402properties that are set as system properties are copied into the set of
403configuration properties. This provide an easy way to add to or
404override configuration properties specified in the <tt>config.properties</tt> file, since the Felix instance will never look at system properties for configuration.</li>
405 <li>If the <tt>-b</tt> switch was used to specify an auto-deploy directory, then use that to set the value of <tt>felix.auto.deploy.dir</tt>.</li>
406 <li>If a single command-line argument is specified, then use that to set the value of <tt>org.osgi.framework.storage</tt>; relative paths are relative to the current directory unless the <tt>felix.cache.rootdir</tt> property is set.</li>
407 <li>Add a shutdown hook to cleanly stop the framework, unless the hook is disabled.</li>
408 <li>Create a framework instance using the <tt>FrameworkFactory</tt> passing in the configuration properties, then initialize the factory instance; see the <a href="#ApacheFelixFrameworkLaunchingandEmbedding-customlauncher">custom launcher example</a> below to see how the META-INF/services <tt>FrameworkFactory</tt> is obtained.</li>
409 <li>Use <tt>org.apache.felix.main.AutoProcessor</tt>, which will automatically deploy any bundles in the auto-deploy directory as well as bundles specified in the <tt>felix.auto.install</tt> and <tt>felix.auto.start</tt>
410configuration properties during framework startup to automatically
411install and/or start bundles; see the usage document for more
412information <a href="http://felix.apache.org/site/apache-felix-framework-usage-documentation.html#ApacheFelixFrameworkUsageDocumentation-configuringframework">configuration properties</a> and <a href="http://felix.apache.org/site/apache-felix-framework-usage-documentation.html#ApacheFelixFrameworkUsageDocumentation-autodeploy">bundle auto-deploy</a>.</li>
413 <li>Invoke <tt>waitForStop()</tt> to wait for the framework to stop to force the VM to exit; this is necessary because the framework never calls <tt>System.exit()</tt> and some libraries (e.g., Swing) create threads that will not allow the VM to exit.</li>
414</ol>
415
416
417<p>The framework is not active until the <tt>start()</tt> method is
418called. If no shell bundles are installed and started or if there is
419difficulty locating the shell bundles specified in the auto-start
420property, then it will appear as if the framework is hung, but it is
421actually running without any way to interact with it since the shell
422bundles provide the only means of interaction.</p>
423
424<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-customlauncher"></a></p>
425
426<h2><a name="ApacheFelixFrameworkLaunchingandEmbedding-CustomFrameworkLauncher"></a>Custom Framework Launcher</h2>
427
428<p>This section creates a bare-bones launcher to demonstrate the
429minimum requirements for creating an interactive launcher for the Felix
430framework. This example uses the standard Felix shell bundles for
431interactivity, but any other bundles could be used instead. For
432example, the shell service and telnet bundles could be used to launch
433Felix and make it remotely accessible.</p>
434
435<p>This example launcher project has the following directory structure:</p>
436
437<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
438<pre>launcher/
439 lib/
440 org.apache.felix.main-2.0.0.jar
441 bundle/
442 org.apache.felix.shell-1.4.0.jar
443 org.apache.felix.shell.tui-1.4.0.jar
444 src/
445 example/
446 Main.java
447</pre>
448</div></div>
449
450<p>The <tt>lib/</tt> directory contains Felix' main JAR file, which
451also contains the OSGi core interfaces. The main JAR file is used so
452that we can reuse the default launcher's auto-install/auto-start
453configuration property handling; if these capabilities are not needed,
454then it would be possible to use the framework JAR file instead of the
455main JAR file. The <tt>bundle/</tt> directory contains the shell
456service and textual shell interface bundles that will be used for
457interacting with the framework instance. Note: If you do not launch
458Felix with interactive bundles, it will appear as if the framework
459instance is hung, but it is actually just sitting there waiting for
460someone to tell it to do something. The <tt>src/example/</tt> directory contains the following <tt>Main.java</tt> file, which is a very simplistic Felix launcher.</p>
461
462<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
463<pre class="code-java"><span class="code-keyword">package</span> example;
464
465<span class="code-keyword">import</span> java.io.*;
466<span class="code-keyword">import</span> org.osgi.framework.launch.*;
467<span class="code-keyword">import</span> org.apache.felix.main.AutoProcessor;
468
469<span class="code-keyword">public</span> class Main
470{
471 <span class="code-keyword">private</span> <span class="code-keyword">static</span> Framework m_fwk = <span class="code-keyword">null</span>;
472
473 <span class="code-keyword">public</span> <span class="code-keyword">static</span> void main(<span class="code-object">String</span>[] argv) <span class="code-keyword">throws</span> Exception
474 {
475 <span class="code-comment">// Print welcome banner.
476</span> <span class="code-object">System</span>.out.println(<span class="code-quote">"\nWelcome to Felix."</span>);
477 <span class="code-object">System</span>.out.println(<span class="code-quote">"=================\n"</span>);
478
479 <span class="code-keyword">try</span>
480 {
481 m_fwk = getFrameworkFactory().newFramework(<span class="code-keyword">null</span>);
482 m_fwk.init()
483 AutoProcessor.process(<span class="code-keyword">null</span>, m_fwk.getBundleContext());
484 m_fwk.start();
485 m_fwk.waitForStop();
486 <span class="code-object">System</span>.exit(0);
487 }
488 <span class="code-keyword">catch</span> (Exception ex)
489 {
490 <span class="code-object">System</span>.err.println(<span class="code-quote">"Could not create framework: "</span> + ex);
491 ex.printStackTrace();
492 <span class="code-object">System</span>.exit(-1);
493 }
494 }
495
496 <span class="code-keyword">private</span> <span class="code-keyword">static</span> FrameworkFactory getFrameworkFactory() <span class="code-keyword">throws</span> Exception
497 {
498 URL url = Main.class.getClassLoader().getResource(
499 <span class="code-quote">"META-INF/services/org.osgi.framework.launch.FrameworkFactory"</span>);
500 <span class="code-keyword">if</span> (url != <span class="code-keyword">null</span>)
501 {
502 BufferedReader br = <span class="code-keyword">new</span> BufferedReader(<span class="code-keyword">new</span> InputStreamReader(url.openStream()));
503 <span class="code-keyword">try</span>
504 {
505 <span class="code-keyword">for</span> (<span class="code-object">String</span> s = br.readLine(); s != <span class="code-keyword">null</span>; s = br.readLine())
506 {
507 s = s.trim();
508 <span class="code-comment">// Try to load first non-empty, non-commented line.
509</span> <span class="code-keyword">if</span> ((s.length() &gt; 0) &amp;&amp; (s.charAt(0) != '#'))
510 {
511 <span class="code-keyword">return</span> (FrameworkFactory) <span class="code-object">Class</span>.forName(s).newInstance();
512 }
513 }
514 }
515 <span class="code-keyword">finally</span>
516 {
517 <span class="code-keyword">if</span> (br != <span class="code-keyword">null</span>) br.close();
518 }
519 }
520
521 <span class="code-keyword">throw</span> <span class="code-keyword">new</span> Exception(<span class="code-quote">"Could not find framework factory."</span>);
522 }
523}
524</pre>
525</div></div>
526
527<p>This launcher relies on the default behavior of <tt>AutoProcessor</tt>
528to automatically deploy the shell bundles. This simple, generic
529launcher provides a good starting point if the default Felix launcher
530is not sufficient. Since very few configuration properties are
531specified, the default values are used. For the bundle auto-deploy
532directory, "<tt>bundle</tt>" in the current directory is used, while for the framework bundle cache, "<tt>felix-cache</tt>" in the current directory is used.</p>
533
534<p>By breaking down the above source code into small chunks, it is quite easy to see what is going on.</p>
535
536<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
537<pre class="code-java"> m_fwk = getFrameworkFactory().newFramework(<span class="code-keyword">null</span>);
538 m_fwk.init()
539</pre>
540</div></div>
541
542<p>These steps get a the framework factory service and use it to create
543a framework instance with a default configuration. Once the framework
544instance is created, it is initialized with <tt>init()</tt>.</p>
545
546<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
547<pre class="code-java"> AutoProcessor.process(<span class="code-keyword">null</span>, m_fwk.getBundleContext());
548</pre>
549</div></div>
550
551<p>The <tt>AutorProcessor</tt> will automatically deploy bundles in the
552auto-deploy directory and any referenced from the auto-install/start
553properties. Since we are using an empty configuration, the auto-deploy
554directory is the <tt>bundle</tt> directory in the current directory
555and there are no auto properties. Therefore, in this case, the two
556shell bundles will be installed.</p>
557
558<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
559<pre class="code-java"> m_fwk.start();
560 m_fwk.waitForStop();
561 <span class="code-object">System</span>.exit(0);
562</pre>
563</div></div>
564
565<p>These final steps start the framework and cause the launching
566application thread to wait for the framework to stop and when it does
567the launching thread calls <tt>System.exit()</tt> to make sure the VM actually exits.</p>
568
569<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
570<pre class="code-java"> <span class="code-keyword">private</span> <span class="code-keyword">static</span> FrameworkFactory getFrameworkFactory() <span class="code-keyword">throws</span> Exception
571 {
572 ...
573 }
574</pre>
575</div></div>
576
577<p>This method retrieves the framework factory service by doing a
578META-INF/services resource lookup, which it can use to obtain the
579concrete class name for the factory. If you are using Java 6, then you
580can use the <tt>ServiceLoader</tt> API in the JRE to further simplify the factory service lookup.</p>
581
582<p>The following command compiles the launcher when run from the root directory of the launcher project:</p>
583
584<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
585<pre>javac -d . -classpath lib/org.apache.felix.main-2.0.0.jar src/example/Main.java
586</pre>
587</div></div>
588
589<p>After executing this command, an <tt>example/</tt> directory is
590created in the current directory, which contains the generated class
591file. The following command executes the simple launcher when run from
592the root directory of the launcher project:</p>
593
594<div class="preformatted panel" style="border-width: 1px;"><div class="preformattedContent panelContent">
595<pre>java -cp .:lib/org.apache.felix.main-2.0.0.jar example.Main
596</pre>
597</div></div>
598
599<p>After executing this command, a "<tt>felix-cache/</tt>" directory is created that contains the cached bundles, which were installed from the <tt>bundle/</tt> directory.</p>
600
601<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-embedding"></a></p>
602
603<h1><a name="ApacheFelixFrameworkLaunchingandEmbedding-EmbeddingFelix"></a>Embedding Felix</h1>
604
605<p>Embedding Felix into a host application is a simple way to provide a
606sophisticated extensibility mechanism (i.e., a plugin system) to the
607host application. Embedding Felix is very similar to launching Felix as
608described above, the main difference is that the host application
609typically wants to interact with the framework instance and/or
610installed bundles/services from the outside. This is fairly easy to
611achieve with Felix, but there are some subtle issues to understand.
612This section presents the mechanisms for embedding Felix into a host
613application and the issues in doing so.</p>
614
615<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-hostinteraction"></a></p>
616
617<h2><a name="ApacheFelixFrameworkLaunchingandEmbedding-Host/FelixInteraction"></a>Host/Felix Interaction</h2>
618
619<p>In the section on <a href="#ApacheFelixFrameworkLaunchingandEmbedding-launching">launching</a> Felix above, the <tt>Felix</tt> accepts a configuration property called <tt>felix.systembundle.activators</tt>,
620which is a list of bundle activator instances. These bundle activator
621instances provide a convenient way for host applications to interact
622with the Felix framework. The ability offered by these activators can
623also be accomplished by invoking <tt>init()</tt> on the framework instance and the using <tt>getBundleContext()</tt> to get the System Bundle's context, but it can be more convenient to use an activator instance.</p>
624
625<p>Each activator instance passed into the constructor effectively becomes part of the System Bundle. This means that the <tt>start()</tt>/<tt>stop()</tt> methods of each activator instance in the list gets invoked when the System Bundle's activator <tt>start()</tt>/<tt>stop()</tt> methods gets invoked, respectively. Each activator instance will be given the System Bundle's <tt>BundleContext</tt> object so that they can interact with the framework. Consider following snippet of a bundle activator:</p>
626
627<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
628<pre class="code-java"><span class="code-keyword">public</span> class HostActivator <span class="code-keyword">implements</span> BundleActivator
629{
630 <span class="code-keyword">private</span> BundleContext m_context = <span class="code-keyword">null</span>;
631
632 <span class="code-keyword">public</span> void start(BundleContext context)
633 {
634 m_context = context;
635 }
636
637 <span class="code-keyword">public</span> void stop(BundleContext context)
638 {
639 m_context = <span class="code-keyword">null</span>;
640 }
641
642 <span class="code-keyword">public</span> Bundle[] getBundles()
643 {
644 <span class="code-keyword">if</span> (m_context != <span class="code-keyword">null</span>)
645 {
646 <span class="code-keyword">return</span> m_context.getBundles();
647 }
648 <span class="code-keyword">return</span> <span class="code-keyword">null</span>;
649 }
650}
651</pre>
652</div></div>
653
654<p>Given the above bundle activator, it is now possible to embed Felix
655into a host application and interact with it as the following snippet
656illustrates:</p>
657
658<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
659<pre class="code-java"><span class="code-keyword">public</span> class HostApplication
660{
661 <span class="code-keyword">private</span> HostActivator m_activator = <span class="code-keyword">null</span>;
662 <span class="code-keyword">private</span> Felix m_felix = <span class="code-keyword">null</span>;
663
664 <span class="code-keyword">public</span> HostApplication()
665 {
666 <span class="code-comment">// Create a configuration property map.
667</span> Map configMap = <span class="code-keyword">new</span> HashMap();
668 <span class="code-comment">// Create host activator;
669</span> m_activator = <span class="code-keyword">new</span> HostActivator();
670 List list = <span class="code-keyword">new</span> ArrayList();
671 list.add(m_activator);
672 configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
673
674 <span class="code-keyword">try</span>
675 {
676 <span class="code-comment">// Now create an instance of the framework with
677</span> <span class="code-comment">// our configuration properties.
678</span> m_felix = <span class="code-keyword">new</span> Felix(configMap);
679 <span class="code-comment">// Now start Felix instance.
680</span> m_felix.start();
681 }
682 <span class="code-keyword">catch</span> (Exception ex)
683 {
684 <span class="code-object">System</span>.err.println(<span class="code-quote">"Could not create framework: "</span> + ex);
685 ex.printStackTrace();
686 }
687 }
688
689 <span class="code-keyword">public</span> Bundle[] getInstalledBundles()
690 {
691 <span class="code-comment">// Use the system bundle activator to gain external
692</span> <span class="code-comment">// access to the set of installed bundles.
693</span> <span class="code-keyword">return</span> m_activator.getBundles();
694 }
695
696 <span class="code-keyword">public</span> void shutdownApplication()
697 {
698 <span class="code-comment">// Shut down the felix framework when stopping the
699</span> <span class="code-comment">// host application.
700</span> m_felix.stop();
701 m_felix.waitForStop();
702 }
703}
704</pre>
705</div></div>
706
707<p>Notice how the <tt>HostApplication.getInstalledBundles()</tt> method
708uses its activator instance to get access to the System Bundle's
709context in order to interact with the embedded Felix framework
710instance. This approach provides the foundation for all interaction
711between the host application and the embedded framework instance.</p>
712
713<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-hostservices"></a></p>
714
715<h2><a name="ApacheFelixFrameworkLaunchingandEmbedding-ProvidingHostApplicationServices"></a>Providing Host Application Services</h2>
716
717<p>Providing services from the host application to bundles inside the
718embedded Felix framework instance follows the basic approach laid out
719in <a href="#ApacheFelixFrameworkLaunchingandEmbedding-hostinteraction">above</a>.
720The main complication for providing a host application service to
721bundles is the fact that both the host application and the bundles must
722be using the same class definitions for the service interface classes.
723Since the host application cannot import classes from a bundle, this
724means that the service interface classes <b>must</b> be accessible on
725the class path, typically as part of the host application itself. The
726host application then must export the service interface package via the
727system bundle so that bundles installed into the embedded framework
728instance can import it. This is achieved using the <tt>org.osgi.framework.system.packages.extra</tt> configuration property previously presented.</p>
729
730<p>Consider the follow simple property lookup service:</p>
731
732<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
733<pre class="code-java"><span class="code-keyword">package</span> host.service.lookup;
734
735<span class="code-keyword">public</span> class Lookup
736{
737 <span class="code-keyword">public</span> <span class="code-object">Object</span> lookup(<span class="code-object">String</span> name);
738}
739</pre>
740</div></div>
741
742<p>This package is simply part of the host application, which is potentially packaged into a JAR file and started with the "<tt>java -jar</tt>"
743command. Now consider the following host application bundle activator,
744which will be used to register/unregister the property lookup service
745when the embedded framework instance starts/stops:</p>
746
747<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
748<pre class="code-java"><span class="code-keyword">package</span> host.core;
749
750<span class="code-keyword">import</span> java.util.Map;
751<span class="code-keyword">import</span> org.osgi.framework.BundleActivator;
752<span class="code-keyword">import</span> org.osgi.framework.BundleContext;
753<span class="code-keyword">import</span> org.osgi.framework.ServiceRegistration;
754<span class="code-keyword">import</span> host.service.lookup;
755
756<span class="code-keyword">public</span> class HostActivator <span class="code-keyword">implements</span> BundleActivator
757{
758 <span class="code-keyword">private</span> Map m_lookupMap = <span class="code-keyword">null</span>;
759 <span class="code-keyword">private</span> BundleContext m_context = <span class="code-keyword">null</span>;
760 <span class="code-keyword">private</span> ServiceRegistration m_registration = <span class="code-keyword">null</span>;
761
762 <span class="code-keyword">public</span> HostActivator(Map lookupMap)
763 {
764 <span class="code-comment">// Save a reference to the service's backing store.
765</span> m_lookupMap = lookupMap;
766 }
767
768 <span class="code-keyword">public</span> void start(BundleContext context)
769 {
770 <span class="code-comment">// Save a reference to the bundle context.
771</span> m_context = context;
772 <span class="code-comment">// Create a property lookup service implementation.
773</span> Lookup lookup = <span class="code-keyword">new</span> Lookup() {
774 <span class="code-keyword">public</span> <span class="code-object">Object</span> lookup(<span class="code-object">String</span> name)
775 {
776 <span class="code-keyword">return</span> m_lookupMap.get(name);
777 }
778 };
779 <span class="code-comment">// Register the property lookup service and save
780</span> <span class="code-comment">// the service registration.
781</span> m_registration = m_context.registerService(
782 Lookup.class.getName(), lookup, <span class="code-keyword">null</span>);
783 }
784
785 <span class="code-keyword">public</span> void stop(BundleContext context)
786 {
787 <span class="code-comment">// Unregister the property lookup service.
788</span> m_registration.unregister();
789 m_context = <span class="code-keyword">null</span>;
790 }
791}
792</pre>
793</div></div>
794
795<p>Given the above host application bundle activator, the following
796code snippet shows how the host application could create an embedded
797version of the Felix framework and provide the property lookup service
798to installed bundles:</p>
799
800<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
801<pre class="code-java"><span class="code-keyword">package</span> host.core;
802
803<span class="code-keyword">import</span> java.util.List;
804<span class="code-keyword">import</span> java.util.ArrayList;
805<span class="code-keyword">import</span> java.util.Map;
806<span class="code-keyword">import</span> java.util.HashMap;
807<span class="code-keyword">import</span> host.service.lookup.Lookup;
808<span class="code-keyword">import</span> org.apache.felix.framework.Felix;
809<span class="code-keyword">import</span> org.apache.felix.framework.util.FelixConstants;
810<span class="code-keyword">import</span> org.osgi.framework.Constants;
811
812<span class="code-keyword">public</span> class HostApplication
813{
814 <span class="code-keyword">private</span> HostActivator m_activator = <span class="code-keyword">null</span>;
815 <span class="code-keyword">private</span> Felix m_felix = <span class="code-keyword">null</span>;
816 <span class="code-keyword">private</span> Map m_lookupMap = <span class="code-keyword">new</span> HashMap();
817
818 <span class="code-keyword">public</span> HostApplication()
819 {
820 <span class="code-comment">// Initialize the map <span class="code-keyword">for</span> the property lookup service.
821</span> m_lookupMap.put(<span class="code-quote">"name1"</span>, <span class="code-quote">"value1"</span>);
822
823 m_lookupMap.put(<span class="code-quote">"name2"</span>, <span class="code-quote">"value2"</span>);
824 m_lookupMap.put(<span class="code-quote">"name3"</span>, <span class="code-quote">"value3"</span>);
825 m_lookupMap.put(<span class="code-quote">"name4"</span>, <span class="code-quote">"value4"</span>);
826
827 <span class="code-comment">// Create a configuration property map.
828</span> Map configMap = <span class="code-keyword">new</span> HashMap();
829 <span class="code-comment">// Export the host provided service <span class="code-keyword">interface</span> <span class="code-keyword">package</span>.
830</span> configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA,
831 <span class="code-quote">"host.service.lookup; version=1.0.0"</span>);
832 <span class="code-comment">// Create host activator;
833</span> m_activator = <span class="code-keyword">new</span> HostActivator(m_lookupMap);
834 List list = <span class="code-keyword">new</span> ArrayList();
835 list.add(m_activator);
836 configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
837
838 <span class="code-keyword">try</span>
839 {
840 <span class="code-comment">// Now create an instance of the framework with
841</span> <span class="code-comment">// our configuration properties.
842</span> m_felix = <span class="code-keyword">new</span> Felix(configMap);
843 <span class="code-comment">// Now start Felix instance.
844</span> m_felix.start();
845 }
846 <span class="code-keyword">catch</span> (Exception ex)
847 {
848 <span class="code-object">System</span>.err.println(<span class="code-quote">"Could not create framework: "</span> + ex);
849 ex.printStackTrace();
850 }
851 }
852
853 <span class="code-keyword">public</span> void shutdownApplication()
854 {
855 <span class="code-comment">// Shut down the felix framework when stopping the
856</span> <span class="code-comment">// host application.
857</span> m_felix.stop();
858 m_felix.waitForStop();
859 }
860}
861</pre>
862</div></div>
863
864<p>Rather than having the host application bundle activator register
865the service, it is also possible for the the host application to simply
866get the bundle context from the bundle activator and register the
867service directly, but the presented approach is perhaps a little
868cleaner since it allows the host application to register/unregister the
869service when the system bundle starts/stops.</p>
870
871<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-hostserviceusage"></a></p>
872
873<h2><a name="ApacheFelixFrameworkLaunchingandEmbedding-UsingServicesProvidedbyBundles"></a>Using Services Provided by Bundles</h2>
874
875<p>Using services provided by bundles follows the same general approach
876of using a host application bundle activator. The main complication for
877the host application using a service from a bundle is the fact that
878both the host application and the bundle must be using the same class
879definitions for the service interface classes. Since the host
880application cannot import classes from a bundle, this means that the
881service interface classes <b>must</b> be accessible on the class path,
882typically as part of the host application itself. The host application
883then must export the service interface package via the system bundle so
884that bundles installed into the embedded framework instance can import
885it. This is achieved using the <tt>org.osgi.framework.system.packages.extra</tt> configuration property previously presented.</p>
886
887<p>Consider the following simple command service interface for which
888bundles provide implementations, such as might be used to create an
889extensible interactive shell:</p>
890
891<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
892<pre class="code-java"><span class="code-keyword">package</span> host.service.command;
893
894<span class="code-keyword">public</span> class Command
895{
896 <span class="code-keyword">public</span> <span class="code-object">String</span> getName();
897 <span class="code-keyword">public</span> <span class="code-object">String</span> getDescription();
898 <span class="code-keyword">public</span> <span class="code-object">boolean</span> execute(<span class="code-object">String</span> commandline);
899}
900</pre>
901</div></div>
902
903<p>This package is simply part of the host application, which is potentially packaged into a JAR file and started with the "<tt>java -jar</tt>"
904command. Now consider the previously introduced host application bundle
905activator below, which simply provides access to the system bundle
906context:</p>
907
908<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
909<pre class="code-java"><span class="code-keyword">package</span> host.core;
910
911<span class="code-keyword">import</span> org.osgi.framework.BundleActivator;
912<span class="code-keyword">import</span> org.osgi.framework.BundleContext;
913
914<span class="code-keyword">public</span> class HostActivator <span class="code-keyword">implements</span> BundleActivator
915{
916 <span class="code-keyword">private</span> BundleContext m_context = <span class="code-keyword">null</span>;
917
918 <span class="code-keyword">public</span> void start(BundleContext context)
919 {
920 m_context = context;
921 }
922
923 <span class="code-keyword">public</span> void stop(BundleContext context)
924 {
925 m_context = <span class="code-keyword">null</span>;
926 }
927
928 <span class="code-keyword">public</span> BundleContext getContext()
929 {
930 <span class="code-keyword">return</span> m_context;
931 }
932}
933</pre>
934</div></div>
935
936<p>With this bundle activator, the host application can use command
937services provided by bundles installed inside its embedded Felix
938framework instance. The following code snippet illustrates one possible
939approach:</p>
940
941<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
942<pre class="code-java"><span class="code-keyword">package</span> host.core;
943
944<span class="code-keyword">import</span> java.util.List;
945<span class="code-keyword">import</span> java.util.ArrayList;
946<span class="code-keyword">import</span> java.util.Map;
947<span class="code-keyword">import</span> host.service.command.Command;
948<span class="code-keyword">import</span> org.apache.felix.framework.Felix;
949<span class="code-keyword">import</span> org.apache.felix.framework.util.FelixConstants;
950<span class="code-keyword">import</span> org.apache.felix.framework.cache.BundleCache;
951<span class="code-keyword">import</span> org.osgi.framework.Constants;
952<span class="code-keyword">import</span> org.osgi.util.tracker.ServiceTracker;
953
954<span class="code-keyword">public</span> class HostApplication
955{
956 <span class="code-keyword">private</span> HostActivator m_activator = <span class="code-keyword">null</span>;
957 <span class="code-keyword">private</span> Felix m_felix = <span class="code-keyword">null</span>;
958 <span class="code-keyword">private</span> ServiceTracker m_tracker = <span class="code-keyword">null</span>;
959
960 <span class="code-keyword">public</span> HostApplication()
961 {
962 <span class="code-comment">// Create a configuration property map.
963</span> Map configMap = <span class="code-keyword">new</span> HashMap();
964 <span class="code-comment">// Export the host provided service <span class="code-keyword">interface</span> <span class="code-keyword">package</span>.
965</span> configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA,
966 <span class="code-quote">"host.service.command; version=1.0.0"</span>);
967 <span class="code-comment">// Create host activator;
968</span> m_activator = <span class="code-keyword">new</span> HostActivator();
969 List list = <span class="code-keyword">new</span> ArrayList();
970 list.add(m_activator);
971 configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
972
973 <span class="code-keyword">try</span>
974 {
975 <span class="code-comment">// Now create an instance of the framework with
976</span> <span class="code-comment">// our configuration properties.
977</span> m_felix = <span class="code-keyword">new</span> Felix(configMap);
978 <span class="code-comment">// Now start Felix instance.
979</span> m_felix.start();
980 }
981 <span class="code-keyword">catch</span> (Exception ex)
982 {
983 <span class="code-object">System</span>.err.println(<span class="code-quote">"Could not create framework: "</span> + ex);
984 ex.printStackTrace();
985 }
986
987 m_tracker = <span class="code-keyword">new</span> ServiceTracker(
988 m_activator.getContext(), Command.class.getName(), <span class="code-keyword">null</span>);
989 m_tracker.open();
990 }
991
992 <span class="code-keyword">public</span> <span class="code-object">boolean</span> execute(<span class="code-object">String</span> name, <span class="code-object">String</span> commandline)
993 {
994 <span class="code-comment">// See <span class="code-keyword">if</span> any of the currently tracked command services
995</span> <span class="code-comment">// match the specified command name, <span class="code-keyword">if</span> so then execute it.
996</span> <span class="code-object">Object</span>[] services = m_tracker.getServices();
997 <span class="code-keyword">for</span> (<span class="code-object">int</span> i = 0; (services != <span class="code-keyword">null</span>) &amp;&amp; (i &lt; services.length); i++)
998 {
999 <span class="code-keyword">try</span>
1000 {
1001 <span class="code-keyword">if</span> (((Command) services[i]).getName().equals(name))
1002 {
1003 <span class="code-keyword">return</span> ((Command) services[i]).execute(commandline);
1004 }
1005 }
1006 <span class="code-keyword">catch</span> (Exception ex)
1007 {
1008 <span class="code-comment">// Since the services returned by the tracker could become
1009</span> <span class="code-comment">// invalid at any moment, we will <span class="code-keyword">catch</span> all exceptions, log
1010</span> <span class="code-comment">// a message, and then ignore faulty services.
1011</span> <span class="code-object">System</span>.err.println(ex);
1012 }
1013 }
1014 <span class="code-keyword">return</span> <span class="code-keyword">false</span>;
1015 }
1016
1017 <span class="code-keyword">public</span> void shutdownApplication()
1018 {
1019 {
1020 <span class="code-comment">// Shut down the felix framework when stopping the
1021</span> <span class="code-comment">// host application.
1022</span> m_felix.stop();
1023 m_felix.waitForStop();
1024 }
1025}
1026</pre>
1027</div></div>
1028
1029<p>The above example is overly simplistic with respect to concurrency
1030issues and error conditions, but it demonstrates the overall approach
1031for using bundle-provided services from the host application.</p>
1032
1033<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-servicereflection"></a></p>
1034
1035<h3><a name="ApacheFelixFrameworkLaunchingandEmbedding-UsingBundleServicesviaReflection"></a>Using Bundle Services via Reflection</h3>
1036
1037<p>It possible for the host application to use services provided by
1038bundles without having access to the service interface classes and thus
1039not needing to put the service interface classes on the class path. To
1040do this, the host application uses the same general approach to acquire
1041the system bundle context object, which it can use to look up service
1042objects. Using either an LDAP filter or the service interface class
1043name, the host application can retrieve the service object and then use
1044standard Java reflection to invoke methods on the service object.</p>
1045
1046<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-serviceother"></a></p>
1047
1048<h3><a name="ApacheFelixFrameworkLaunchingandEmbedding-OtherApproaches"></a>Other Approaches</h3>
1049
1050<p>The <a href="http://code.google.com/p/transloader/" rel="nofollow">Transloader</a> project is another attempt at dealing with issues of classes loaded from different class loaders and may be of interest.</p>
1051
1052<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-caveat"></a></p>
1053
1054<h1><a name="ApacheFelixFrameworkLaunchingandEmbedding-Caveat"></a>Caveat</h1>
1055
1056<p>The code in this document has not been thoroughly tested nor even
1057compiled and may be out of date with respect to the current Felix
1058source code. If you find errors please report them so the that they can
1059be corrected.</p>
1060
1061<p><a name="ApacheFelixFrameworkLaunchingandEmbedding-feedback"></a></p>
1062
1063<h2><a name="ApacheFelixFrameworkLaunchingandEmbedding-Feedback"></a>Feedback</h2>
1064
1065<p>Subscribe to the Felix users mailing list by sending a message to <a href="mailto:users-subscribe@felix.apache.org" rel="nofollow">users-subscribe@felix.apache.org</a>; after subscribing, email questions or feedback to <a href="mailto:users@felix.apache.org" rel="nofollow">users@felix.apache.org</a>.</p>
1066 </div>
1067 </body></html>