Return-Path: Delivered-To: apmail-felix-commits-archive@www.apache.org Received: (qmail 97152 invoked from network); 6 Nov 2008 16:24:03 -0000 Received: from hermes.apache.org (HELO mail.apache.org) (140.211.11.2) by minotaur.apache.org with SMTP; 6 Nov 2008 16:24:03 -0000 Received: (qmail 91272 invoked by uid 500); 6 Nov 2008 16:24:10 -0000 Delivered-To: apmail-felix-commits-archive@felix.apache.org Received: (qmail 91192 invoked by uid 500); 6 Nov 2008 16:24:10 -0000 Mailing-List: contact commits-help@felix.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@felix.apache.org Delivered-To: mailing list commits@felix.apache.org Received: (qmail 91183 invoked by uid 99); 6 Nov 2008 16:24:10 -0000 Received: from athena.apache.org (HELO athena.apache.org) (140.211.11.136) by apache.org (qpsmtpd/0.29) with ESMTP; Thu, 06 Nov 2008 08:24:10 -0800 X-ASF-Spam-Status: No, hits=-1999.6 required=10.0 tests=ALL_TRUSTED,SUBJECT_FUZZY_TION X-Spam-Check-By: apache.org Received: from [140.211.11.4] (HELO eris.apache.org) (140.211.11.4) by apache.org (qpsmtpd/0.29) with ESMTP; Thu, 06 Nov 2008 16:22:48 +0000 Received: by eris.apache.org (Postfix, from userid 65534) id C38972388920; Thu, 6 Nov 2008 08:23:30 -0800 (PST) Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: svn commit: r711894 [1/2] - in /felix/trunk/main: ./ doc/ doc/apache-felix-framework-launching-and-embedding_files/ doc/apache-felix-framework-launching-and-embedding_files/button_data/ doc/apache-felix-usage-documentation_files/ doc/apache-felix-usage... Date: Thu, 06 Nov 2008 16:23:16 -0000 To: commits@felix.apache.org From: pauls@apache.org X-Mailer: svnmailer-1.0.8 Message-Id: <20081106162330.C38972388920@eris.apache.org> X-Virus-Checked: Checked by ClamAV on apache.org Author: pauls Date: Thu Nov 6 08:22:54 2008 New Revision: 711894 URL: http://svn.apache.org/viewvc?rev=711894&view=rev Log: Prepare 1.4.0 release Added: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding.html felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/ felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/apache.png (with props) felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/button.html felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/button_data/ felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/button_data/2008-usa-125x125.png (with props) felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/forbidden.gif (with props) felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/linkext7.gif (with props) felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/logo.png (with props) felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/mail_small.gif (with props) felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/site.css felix/trunk/main/doc/apache-felix-usage-documentation_files/button.html felix/trunk/main/doc/apache-felix-usage-documentation_files/button_data/ felix/trunk/main/doc/apache-felix-usage-documentation_files/button_data/2008-usa-125x125.png (with props) felix/trunk/main/doc/apache-felix-usage-documentation_files/information.gif (with props) Removed: felix/trunk/main/doc/launching-and-embedding-apache-felix.html felix/trunk/main/doc/launching-and-embedding-apache-felix_files/ Modified: felix/trunk/main/doc/apache-felix-usage-documentation.html felix/trunk/main/doc/changelog.txt felix/trunk/main/pom.xml felix/trunk/main/src/main/resources/config.properties Added: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding.html URL: http://svn.apache.org/viewvc/felix/trunk/main/doc/apache-felix-framework-launching-and-embedding.html?rev=711894&view=auto ============================================================================== --- felix/trunk/main/doc/apache-felix-framework-launching-and-embedding.html (added) +++ felix/trunk/main/doc/apache-felix-framework-launching-and-embedding.html Thu Nov 6 08:22:54 2008 @@ -0,0 +1,981 @@ + + + + + + Apache Felix - Apache Felix Framework Launching and Embedding + + + +
Apache
+ +
+

Apache Felix Framework Launching and Embedding

+ +

[This document is based on Felix 1.4.0.]

+ + + + +

+ +

Introduction

+ +

The Apache Felix framework is intended to be easily launchable and +embeddable. For example, Felix avoids the use of system properties for +configuration, since these are globals and can cause interference if +multiple framework instances are created in the same VM. Felix also +tries to multiplex singleton facilities, like the URL stream handler +factory. The goal is to make it possible to use Felix in as many +scenarios as possible; however, this is still just a goal. In other +words, this is a work in progress and if any issues arise, it would be +greatly appreciated if they are brought to the attention of the Felix +community. The next section provides a Felix API overview, while the +remainder of the document is divided into two sections, one focusing on +how to launch Felix and one focusing on how to embed Felix into a host +application.

+ +

+ +

API Overview

+ +

The Felix framework is implemented by the org.apache.felix.framework.Felix class or just Felix +for short. As part of the ongoing OSGi specification process, there is +a movement to standardize the API for launching and embedding OSGi +framework implementations. The approach is to have the framework +implement the org.osgi.framework.launch.Framework interface, which extends the org.osgi.framework.Bundle interface. These interfaces provide the necessary means to launch and manage framework instances. The Bundle interface is defined as:

+ +
+
public interface Bundle
+{
+    BundleContext getBundleContext();
+    long getBundleId();
+    URL getEntry(String name);
+    Enumeration getEntryPaths(String path);
+    Enumeration findEntries(String path, String filePattern, boolean recurse);
+    Dictionary getHeaders();
+    Dictionary getHeaders(String locale);
+    long getLastModified();
+    String getLocation();
+    URL getResource(String name);
+    Enumeration getResources(String name) throws IOException;
+    ServiceReference[] getRegisteredServices();
+    ServiceReference[] getServicesInUse();
+    int getState();
+    String getSymbolicName();
+    boolean hasPermission(Object obj);
+    Class loadClass(String name) throws ClassNotFoundException;
+    void start() throws BundleException;
+    void stop() throws BundleException;
+    void uninstall() throws BundleException;
+    void update() throws BundleException;
+    void update(InputStream is) throws BundleException;
+}
+
+ +

The Framework interface is defined as:

+ +
+
public interface Framework extends Bundle
+{
+    void init();
+    FrameworkEvent waitForStop();
+}
+
+ +

An additional requirement for framework implementations not captured +in the interface definitions is that they must implement a public +constructor that accepts a Map, which is used to pass in configuration properties. When you instantiate the Felix +class, the resulting object is the actual System Bundle that bundles +inside the framework will see if they get bundle 0, which is the System +Bundle as defined by the OSGi specification.

+ +
WARNING
+

This API is undergoing changes and is not completely finalized, so future changes are possible.

+ +

+ +

Creating and Configuring the Framework Instance

+ +

To create a framework instance, simply instantiate the Felix class. A newly created framework instance is in the Bundle.INSTALLED state. You configure the instance by passing the constructor a Map containing its configurations properties. The configuration map may contain the following OSGi standard properties:

+ +
    +
  • org.osgi.framework.system.packages - specifies a +list of packages the system bundle should export from the environment; +if this is not set, then the framework uses a reasonable default fault.
  • +
  • org.osgi.framework.system.packages.extra +- specifies a list of additional packages the system bundle should +export from the environment that are appended to the packages specified +in org.osgi.framework.system.packages; there is no default value for this property.
  • +
  • org.osgi.framework.bootdelegation +- specifies a list of packages that should be made implicitly available +to all bundles from the environment (i.e., no need to import them); +there is no default value for this property and its use should be +avoided.
  • +
  • org.osgi.framework.storage - specifies the +path to a directory, which will be created if it does not exist, to use +for bundle cache storage; the default value for this property is "felix-cache" in the current working directory.
  • +
  • org.osgi.framework.storage.clean +- specifies whether the bundle cache should be flushed; the default +value for this property is "none", but it can be changed to +"onFirstInit" to flush the bundle cache when the framework is +initialized.
  • +
  • org.osgi.framework.startlevel - specifies the start level the framework enters upon startup; the default value for this property is 1.
  • +
+ + +

Felix also has the following, non-standard configuration properties:

+ +
    +
  • felix.cache.rootdir - specifies which directory should be used to calculate absolute paths when relative paths are used for the org.osgi.framework.storage property; the default value for this property is the current working directory.
  • +
  • felix.systembundle.activators - specifies a List of BundleActivator +instances that are started/stopped when the System Bundle is +started/stopped; the specified instances will receive the System +Bundle's BundleContext when invoked.
  • +
  • felix.log.logger - specifies an instance of org.apache.felix.framework.util.Logger that the framework uses as its default logger.
  • +
  • felix.log.level - specifies an integer String +whose value indicates the degree of logging reported by the framework; +the default value is "1" and "0" turns off logging completely, +otherwise log levels match those specified in the OSGi Log Service +(i.e., 1 = error, 2 = warning, 3 = information, and 4 = debug).
  • +
  • felix.startlevel.bundle - specifies the start level for newly installed bundles; the default value is 1.
  • +
  • framework.service.urlhandlers +- 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.
  • +
+ + +

The configuration map passed into the constructor is copied and the +keys are treated as case insensitive. You are not able to change the +framework's configuration after construction. If you need a different +configuration, you must create a new framework instance.

+ +

+ +

Starting the Framework Instance

+ +

The start() method is used to start the framework instance. If the init() method was not invoked prior to calling start(), then it is implicitly invoked from start(). The two methods result in two different framework state transitions:

+ +
    +
  • init() results in the framework instance in the Bundle.STARTING state.
  • +
  • start() results in the framework instance in the Bundle.ACTIVE state.
  • +
+ + +

The init()} method is necessary since the framework does not have a {{BundleContext when it is first created, so a transition to the Bundle.STARTING state is required to acquire its context (via Bundle.getBundleContext()) for performing various tasks, such as installing bundles. Note that Felix also provides the felix.systembundle.activators property that serves a similar purpose. After the init() method completes, the follow actions have been performed:

+ +
    +
  • Event handling is enabled.
  • +
  • The security manager is installed if it is enabled.
  • +
  • The framework is set to start level 0.
  • +
  • All bundles in the bundle caches are reified and their state is set to Bundle.INSTALLED.
  • +
  • The framework gets a valid BundleContext.
  • +
  • All framework-provided services are made available (e.g., PackageAdmin, StartLevel, etc.).
  • +
  • The framework enters the Bundle.STARTING state.
  • +
+ + +

A call to start() is necessary to start the framework instance, if the init() method is invoked manually. Invoking init() or start() on an already started framework as no effect.

+ +

+ +

Stopping the Framework Instance

+ +

To stop the framework instance, invoke the stop() method, which will asynchronously stop the framework. To know when the framework has finished its shutdown sequence, use the waitForStop() method to wait until it is complete. A stopped framework will be in the Bundle.RESOLVED state. It is possible to restart the framework, using the normal combination of init()/start() methods as previously described.

+ +

+ +

Launching Felix

+ +

Launching Felix is fairly simple and involves only three steps:

+ +
    +
  1. Define some configuration properties.
  2. +
  3. Create an instance of org.apache.felix.framework.Felix with the configuration properties.
  4. +
  5. Invoke the org.apache.felix.framework.Felix.start() method.
  6. +
+ + +

In reality, the first step is optional, since all properties will +have reasonable defaults, but if you are creating a launcher you will +generally want to more than that, such as automatically installing and +starting bundles when you start the framework instance. The default +Felix launcher defines reusable functionality to automatically install +and/or start bundles upon framework startup; see the usage document for more information on configuring Felix and on the various configuration properties.

+ +

The remainder of this section describes how the standard Felix +launcher works as well as how to create a custom launcher for Felix.

+ +

+ +

Standard Felix Launcher

+ +

The standard Felix launcher is very simple and is not intended to +solve every possible requirement; it is intended to work for most +standard situations. Most special launching requirements should be +resolved by creating a custom launcher. This section describes how the +standard launcher works. The following code represents the complete main() method of the standard launcher, each numbered comment will be described in more detail below:

+ +
+
public static void main(String[] argv) throws Exception
+{
+    // (1) Check for proper command line usage.
+    if (args.length > 1)
+    {
+        System.out.println("Usage: [<bundle-cache-dir>]");
+        System.exit(0);
+    }
+
+    // (2) Load system properties.
+    Main.loadSystemProperties();
+
+    // (3) Read configuration properties.
+    Properties configProps = Main.loadConfigProperties();
+
+    // (4) Copy framework properties from the system properties.
+    Main.copySystemProperties(configProps);
+
+    // (5) If specified, use command-line argument as path to bundle cache.
+    if (args.length > 0)
+    {
+        configProps.setProperty(Constants.FRAMEWORK_STORAGE, args[0]);
+    }
+
+    // (6) Create a list for custom framework activators and
+    // add an instance of the auto-activator it for processing
+    // auto-install and auto-start properties. Add this list
+    // to the configuration properties.
+    List list = new ArrayList();
+    list.add(new AutoActivator(configProps));
+    configProps.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
+
+    // Print welcome banner.
+    System.out.println("\nWelcome to Felix.");
+    System.out.println("=================\n");
+
+    try
+    {
+        // (7) Create an instance and start the framework.
+
+        m_felix = new Felix(configProps);
+        m_felix.start();
+        // (8) Wait for framework to stop to exit the VM.
+        m_felix.waitForStop();
+        System.exit(0);
+    }
+    catch (Exception ex)
+    {
+        System.err.println("Could not create framework: " + ex);
+        ex.printStackTrace();
+        System.exit(-1);
+    }
+}
+
+ +

The general steps of the standard launcher are quite straightforward:

+ +
    +
  1. The launcher only supports a single, optional command-line +argument, which is the path to the bundle cache, so check for this and +issue a usage message it there are more than one arguments.
  2. +
  3. Load any system properties specified in the system.properties file; this file is typically located in the conf/ directory of the Felix installation directory, but it can be specified directly using the felix.system.properties +system property. This file is not needed to launch Felix and is +provided merely for convenience when system properties must be +specified. The file is a standard Java properties file, but it also +supports property substitution using ${<property-name} syntax. Property substitution can be nested; only system properties will be used for substitution.
  4. +
  5. Load any configuration properties specified in the config.properties file; this file is typically located in the conf/ directory of the Felix installation directory, but it can be specified directly using the felix.config.properties +system property. This file is used to configure the Felix instance +created by the launcher. The file is a standard Java properties file, +but it also supports property substitution using "${<property-name}" +syntax. Property substitution can be nested; configuration and system +properties will be used for substitution with configuration properties +having precedence.
  6. +
  7. For convenience, any configuration +properties that are set as system properties will be copied into the +set of configuration properties to provide an easy way to add to or +override configuration properties specified in the config.properties file.
  8. +
  9. If there is a single command-line argument, then use that to set the value of org.osgi.framework.storage; relative paths are relative to the current directory unless the felix.cache.rootdir property is set.
  10. +
  11. Create a list to hold custom framework activators and add an instance of org.apache.felix.main.AutoActivator, which will process felix.auto.install and felix.auto.start configuration properties during framework startup to automatically install and/or start bundles; see the usage document for more information configuration properties.
  12. +
  13. Create the Felix instance passing in the configuration properties, then call start().
  14. +
  15. Invoke waitForStop() to wait for the framework to stop to force the VM to exit; this is necessary because the framework never calls System.exit() and some libraries (e.g., Swing) create threads that will not allow the VM to exit.
  16. +
+ + +

The framework is not active until the start() method is +called. If no shell bundles are installed and started or if there is +difficulty locating the shell bundles specified in the auto-start +property, then it will appear as if the framework is hung, but it is +actually running without any way to interact with it since the shell +bundles provide the only means of interaction.

+ +

+ +

Custom Felix Launcher

+ +

This section creates a bare-bones launcher to demonstrate the +minimum requirements for creating an interactive launcher for the Felix +framework. This example uses the standard Felix shell bundles for +interactivity, but any other bundles could be used instead. For +example, the shell service and telnet bundles could be used to launch +Felix and make it remotely accessible.

+ +

This example launcher project has the following directory structure:

+ +
+
launcher/
+   lib/
+      org.apache.felix.main-1.4.0.jar
+   bundle/
+      org.apache.felix.shell-1.0.2.jar
+      org.apache.felix.shell.tui-1.0.2.jar
+   src/
+      example/
+         Main.java
+
+
+ +

The lib/ directory contains Felix' main JAR file, which +also contains the OSGi core interfaces. The main JAR file is used so +that we can reuse the default launcher's auto-install/auto-start +configuration property handling; if these capabilities are not needed, +then it would be possible to use the framework JAR file instead of the +main JAR file. The bundle/ directory contains the shell +service and textual shell interface bundles that will be used for +interacting with the framework instance. Note: If you do not launch +Felix with interactive bundles, it will appear as if the framework +instance is hung, but it is actually just sitting there waiting for +someone to tell it to do something. The src/example/ directory contains the following Main.java file, which is a very simplistic Felix launcher.

+ +
+
package example;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.HashMap;
+import org.osgi.framework.Constants;
+import org.apache.felix.framework.Felix;
+import org.apache.felix.framework.util.FelixConstants;
+import org.apache.felix.main.AutoActivator;
+
+public class Main
+{
+    private static Felix m_felix = null;
+
+    public static void main(String[] argv) throws Exception
+    {
+        // Print welcome banner.
+        System.out.println("\nWelcome to Felix.");
+        System.out.println("=================\n");
+
+        Map configMap = new HashMap();
+        configMap.put(AutoActivator.AUTO_START_PROP + ".1",
+            "file:bundle/org.apache.felix.shell-1.0.2.jar " +
+            "file:bundle/org.apache.felix.shell.tui-1.0.2.jar");
+        List list = new ArrayList();
+        list.add(new AutoActivator(configMap));
+        configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
+
+        try
+        {
+            m_felix = new Felix(configMap);
+            m_felix.start();
+            m_felix.waitForStop();
+            System.exit(0);
+        }
+        catch (Exception ex)
+        {
+            System.err.println("Could not create framework: " + ex);
+            ex.printStackTrace();
+            System.exit(-1);
+        }
+    }
+}
+
+ +

This launcher has all information hard coded in it, unlike the +default Felix launcher, which loads configuration properties from files +and performs variable substitution. This simple launcher provides a +good starting point if the features of the default launcher are not +necessary. Since very few configuration properties are specified, the +default values are used. In the case of the framework bundle cache, it +will use "felix-cache" in the current directory.

+ +

By breaking down the above source code into small chunks, it is quite easy to see what is going on.

+ +
+
Map configMap = new HashMap();
+
+ +

This simply creates a map to hold configuration properties.

+ +
+
configMap.put(AutoActivator.AUTO_START_PROP + ".1",
+            "file:bundle/org.apache.felix.shell-1.0.2.jar " +
+            "file:bundle/org.apache.felix.shell.tui-1.0.2.jar");
+
+ +

This sets the AutoActivator.AUTO_START_PROP configuration property (string value "felix.auto.start"), +which is a space-delimited list of bundle URLs that the framework will +automatically install and start when the framework starts. However, +this property key cannot be used as is; it must be appended with a "." +and then a number, where the number represents the start level for the +bundle when it is installed. In this particular example, ".1" is +appended to the property name, thus the two bundles will be installed +into start level one. This example uses relative file: URLs, which will load the bundles from the bundle/ +directory assuming that the launcher is started from the root directory +of the launcher project. It is also possible to specify absolute URLs +or remote URLs.

+ +
+
List list = new ArrayList();
+        list.add(new AutoActivator(configMap));
+        configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
+
+ +

This above creates a list to hold custom framework activators and adds an instance of org.apache.felix.main.AutoActivator +to it, which will process the auto-install and auto-start configuration +properties during framework startup. The list of activators is then +added to the configuration map.

+ +
+
m_felix = new Felix(configMap);
+            m_felix.start();
+
+ +

These steps create the framework instance and start it. The configuration property map is passed into the Felix constructor.

+ +
+
m_felix.waitForStop();
+            System.exit(0);
+
+ +

These final steps cause the launching application thread to wait for +the framework to stop and when it does the launching thread calls System.exit() to make sure the VM actually exits.

+ +

The following command compiles the launcher when run from the root directory of the launcher project:

+ +
+
javac -d . -classpath lib/org.apache.felix.main-1.4.0.jar src/example/Main.java
+
+
+ +

After executing this command, an example/ directory is +created in the current directory, which contains the generated class +file. The following command executes the simple launcher when run from +the root directory of the launcher project:

+ +
+
java -cp .:lib/org.apache.felix.main-1.4.0.jar example.Main
+
+
+ +

After executing this command, a "felix-cache/" directory is created that contains the installed bundles, which were installed from the bundle/ directory.

+ +

+ +

Embedding Felix

+ +

Embedding Felix into a host application is a simple way to provide a +sophisticated extensibility mechanism (i.e., a plugin system) to the +host application. Embedding Felix is very similar to launching Felix as +described above, the main difference is that the host application +typically wants to interact with the framework instance and/or +installed bundles/services from the outside. This is fairly easy to +achieve with Felix, but there are some subtle issues to understand. +This section presents the mechanisms for embedding Felix into a host +application and the issues in doing so.

+ +

+ +

Host/Felix Interaction

+ +

In the section on launching Felix above, the Felix accepts a configuration property called felix.systembundle.activators, +which is a list of bundle activator instances. These bundle activator +instances provide a convenient way for host applications to interact +with the Felix framework. The ability offered by these activators can +also be accomplished by invoking init() on the framework instance and the using getBundleContext() to get the System Bundle's context, but it can be more convenient to use an activator instance.

+ +

Each activator instance passed into the constructor effectively becomes part of the System Bundle. This means that the start()/stop() methods of each activator instance in the list gets invoked when the System Bundle's activator start()/stop() methods gets invoked, respectively. Each activator instance will be given the System Bundle's BundleContext object so that they can interact with the framework. Consider following snippet of a bundle activator:

+ +
+
public class HostActivator implements BundleActivator
+{
+    private BundleContext m_context = null;
+
+    public void start(BundleContext context)
+    {
+        m_context = context;
+    }
+
+    public void stop(BundleContext context)
+    {
+        m_context = null;
+    }
+
+    public Bundle[] getBundles()
+    {
+        if (m_context != null)
+        {
+            return m_context.getBundles();
+        }
+        return null;
+    }
+}
+
+ +

Given the above bundle activator, it is now possible to embed Felix +into a host application and interact with it as the following snippet +illustrates:

+ +
+
public class HostApplication
+{
+    private HostActivator m_activator = null;
+    private Felix m_felix = null;
+
+    public HostApplication()
+    {
+        // Create a configuration property map.
+        Map configMap = new HashMap();
+        // Create host activator;
+        m_activator = new HostActivator();
+        List list = new ArrayList();
+        list.add(m_activator);
+        configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
+
+        try
+        {
+            // Now create an instance of the framework with
+            // our configuration properties.
+            m_felix = new Felix(configMap);
+            // Now start Felix instance.
+            m_felix.start();
+        }
+        catch (Exception ex)
+        {
+            System.err.println("Could not create framework: " + ex);
+            ex.printStackTrace();
+        }
+    }
+
+    public Bundle[] getInstalledBundles()
+    {
+        // Use the system bundle activator to gain external
+        // access to the set of installed bundles.
+        return m_activator.getBundles();
+    }
+
+    public void shutdownApplication()
+    {
+        // Shut down the felix framework when stopping the
+        // host application.
+        m_felix.stop();
+        m_felix.waitForStop();
+    }
+}
+
+ +

Notice how the HostApplication.getInstalledBundles() method +uses its activator instance to get access to the System Bundle's +context in order to interact with the embedded Felix framework +instance. This approach provides the foundation for all interaction +between the host application and the embedded framework instance.

+ +

+ +

Providing Host Application Services

+ +

Providing services from the host application to bundles inside the +embedded Felix framework instance follows the basic approach laid out +in above. +The main complication for providing a host application service to +bundles is the fact that both the host application and the bundles must +be using the same class definitions for the service interface classes. +Since the host application cannot import classes from a bundle, this +means that the service interface classes must be accessible on +the class path, typically as part of the host application itself. The +host application then must export the service interface package via the +system bundle so that bundles installed into the embedded framework +instance can import it. This is achieved using the org.osgi.framework.system.packages.extra configuration property previously presented.

+ +

Consider the follow simple property lookup service:

+ +
+
package host.service.lookup;
+
+public class Lookup
+{
+    public Object lookup(String name);
+}
+
+ +

This package is simply part of the host application, which is potentially packaged into a JAR file and started with the "java -jar" +command. Now consider the following host application bundle activator, +which will be used to register/unregister the property lookup service +when the embedded framework instance starts/stops:

+ +
+
package host.core;
+
+import java.util.Map;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceRegistration;
+import host.service.lookup;
+
+public class HostActivator implements BundleActivator
+{
+    private Map m_lookupMap = null;
+    private BundleContext m_context = null;
+    private ServiceRegistration m_registration = null;
+
+    public HostActivator(Map lookupMap)
+    {
+        // Save a reference to the service's backing store.
+        m_lookupMap = lookupMap;
+    }
+
+    public void start(BundleContext context)
+    {
+        // Save a reference to the bundle context.
+        m_context = context;
+        // Create a property lookup service implementation.
+        Lookup lookup = new Lookup() {
+            public Object lookup(String name)
+            {
+                return m_lookupMap.get(name);
+            }
+        };
+        // Register the property lookup service and save
+        // the service registration.
+        m_registration = m_context.registerService(
+            Lookup.class.getName(), lookup, null);
+    }
+
+    public void stop(BundleContext context)
+    {
+        // Unregister the property lookup service.
+        m_registration.unregister();
+        m_context = null;
+    }
+}
+
+ +

Given the above host application bundle activator, the following +code snippet shows how the host application could create an embedded +version of the Felix framework and provide the property lookup service +to installed bundles:

+ +
+
package host.core;
+
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.HashMap;
+import host.service.lookup.Lookup;
+import org.apache.felix.framework.Felix;
+import org.apache.felix.framework.util.FelixConstants;
+import org.osgi.framework.Constants;
+
+public class HostApplication
+{
+    private HostActivator m_activator = null;
+    private Felix m_felix = null;
+    private Map m_lookupMap = new HashMap();
+
+    public HostApplication()
+    {
+        // Initialize the map for the property lookup service.
+        m_lookupMap.put("name1", "value1");
+
+        m_lookupMap.put("name2", "value2");
+        m_lookupMap.put("name3", "value3");
+        m_lookupMap.put("name4", "value4");
+
+        // Create a configuration property map.
+        Map configMap = new HashMap();
+        // Export the host provided service interface package.
+        configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA,
+            "host.service.lookup; version=1.0.0");
+        // Create host activator;
+        m_activator = new HostActivator(m_lookupMap);
+        List list = new ArrayList();
+        list.add(m_activator);
+        configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
+
+        try
+        {
+            // Now create an instance of the framework with
+            // our configuration properties.
+            m_felix = new Felix(configMap);
+            // Now start Felix instance.
+            m_felix.start();
+        }
+        catch (Exception ex)
+        {
+            System.err.println("Could not create framework: " + ex);
+            ex.printStackTrace();
+        }
+    }
+
+    public void shutdownApplication()
+    {
+        // Shut down the felix framework when stopping the
+        // host application.
+        m_felix.stop();
+        m_felix.waitForStop();
+    }
+}
+
+ +

Rather than having the host application bundle activator register +the service, it is also possible for the the host application to simply +get the bundle context from the bundle activator and register the +service directly, but the presented approach is perhaps a little +cleaner since it allows the host application to register/unregister the +service when the system bundle starts/stops.

+ +

+ +

Using Services Provided by Bundles

+ +

Using services provided by bundles follows the same general approach +of using a host application bundle activator. The main complication for +the host application using a service from a bundle is the fact that +both the host application and the bundle must be using the same class +definitions for the service interface classes. Since the host +application cannot import classes from a bundle, this means that the +service interface classes must be accessible on the class path, +typically as part of the host application itself. The host application +then must export the service interface package via the system bundle so +that bundles installed into the embedded framework instance can import +it. This is achieved using the org.osgi.framework.system.packages.extra configuration property previously presented.

+ +

Consider the following simple command service interface for which +bundles provide implementations, such as might be used to create an +extensible interactive shell:

+ +
+
package host.service.command;
+
+public class Command
+{
+    public String getName();
+    public String getDescription();
+    public boolean execute(String commandline);
+}
+
+ +

This package is simply part of the host application, which is potentially packaged into a JAR file and started with the "java -jar" +command. Now consider the previously introduced host application bundle +activator below, which simply provides access to the system bundle +context:

+ +
+
package host.core;
+
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+
+public class HostActivator implements BundleActivator
+{
+    private BundleContext m_context = null;
+
+    public void start(BundleContext context)
+    {
+        m_context = context;
+    }
+
+    public void stop(BundleContext context)
+    {
+        m_context = null;
+    }
+
+    public BundleContext getContext()
+    {
+        return m_context;
+    }
+}
+
+ +

With this bundle activator, the host application can use command +services provided by bundles installed inside its embedded Felix +framework instance. The following code snippet illustrates one possible +approach:

+ +
+
package host.core;
+
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Map;
+import host.service.command.Command;
+import org.apache.felix.framework.Felix;
+import org.apache.felix.framework.util.FelixConstants;
+import org.apache.felix.framework.cache.BundleCache;
+import org.osgi.framework.Constants;
+import org.osgi.util.tracker.ServiceTracker;
+
+public class HostApplication
+{
+    private HostActivator m_activator = null;
+    private Felix m_felix = null;
+    private ServiceTracker m_tracker = null;
+
+    public HostApplication()
+    {
+        // Create a configuration property map.
+        Map configMap = new HashMap();
+        // Export the host provided service interface package.
+        configMap.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA,
+            "host.service.command; version=1.0.0");
+        // Create host activator;
+        m_activator = new HostActivator();
+        List list = new ArrayList();
+        list.add(m_activator);
+        configMap.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);
+
+        try
+        {
+            // Now create an instance of the framework with
+            // our configuration properties.
+            m_felix = new Felix(configMap);
+            // Now start Felix instance.
+            m_felix.start();
+        }
+        catch (Exception ex)
+        {
+            System.err.println("Could not create framework: " + ex);
+            ex.printStackTrace();
+        }
+
+        m_tracker = new ServiceTracker(
+            m_activator.getContext(), Command.class.getName(), null);
+        m_tracker.open();
+    }
+
+    public boolean execute(String name, String commandline)
+    {
+        // See if any of the currently tracked command services
+        // match the specified command name, if so then execute it.
+        Object[] services = m_tracker.getServices();
+        for (int i = 0; (services != null) && (i < services.length); i++)
+        {
+            try
+            {
+                if (((Command) services[i]).getName().equals(name))
+                {
+                    return ((Command) services[i]).execute(commandline);
+                }
+            }
+            catch (Exception ex)
+            {
+                // Since the services returned by the tracker could become
+                // invalid at any moment, we will catch all exceptions, log
+                // a message, and then ignore faulty services.
+                System.err.println(ex);
+            }
+        }
+        return false;
+    }
+
+    public void shutdownApplication()
+    {
+    {
+        // Shut down the felix framework when stopping the
+        // host application.
+        m_felix.stop();
+        m_felix.waitForStop();
+    }
+}
+
+ +

The above example is overly simplistic with respect to concurrency +issues and error conditions, but it demonstrates the overall approach +for using bundle-provided services from the host application.

+ +

+ +

Using Bundle Services via Reflection

+ +

It possible for the host application to use services provided by +bundles without having access to the service interface classes and thus +not needing to put the service interface classes on the class path. To +do this, the host application uses the same general approach to acquire +the system bundle context object, which it can use to look up service +objects. Using either an LDAP filter or the service interface class +name, the host application can retrieve the service object and then use +standard Java reflection to invoke methods on the service object.

+ +

+ +

Other Approaches

+ +

The Transloader project is another attempt at dealing with issues of classes loaded from different class loaders and may be of interest.

+ +

+ +

Caveat

+ +

The code in this document has not been thoroughly tested nor even +compiled and may be out of date with respect to the current Felix +source code. If you find errors please report them so the that they can +be corrected.

+ +

+ +

Feedback

+ +

Subscribe to the Felix users mailing list by sending a message to users-subscribe@felix.apache.org; after subscribing, email questions or feedback to users@felix.apache.org.

+
+ Added: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/apache.png URL: http://svn.apache.org/viewvc/felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/apache.png?rev=711894&view=auto ============================================================================== Binary file - no diff available. Propchange: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/apache.png ------------------------------------------------------------------------------ svn:mime-type = application/octet-stream Added: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/button.html URL: http://svn.apache.org/viewvc/felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/button.html?rev=711894&view=auto ============================================================================== --- felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/button.html (added) +++ felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/button.html Thu Nov 6 08:22:54 2008 @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file Added: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/button_data/2008-usa-125x125.png URL: http://svn.apache.org/viewvc/felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/button_data/2008-usa-125x125.png?rev=711894&view=auto ============================================================================== Binary file - no diff available. Propchange: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/button_data/2008-usa-125x125.png ------------------------------------------------------------------------------ svn:mime-type = application/octet-stream Added: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/forbidden.gif URL: http://svn.apache.org/viewvc/felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/forbidden.gif?rev=711894&view=auto ============================================================================== Binary file - no diff available. Propchange: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/forbidden.gif ------------------------------------------------------------------------------ svn:mime-type = application/octet-stream Added: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/linkext7.gif URL: http://svn.apache.org/viewvc/felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/linkext7.gif?rev=711894&view=auto ============================================================================== Binary file - no diff available. Propchange: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/linkext7.gif ------------------------------------------------------------------------------ svn:mime-type = application/octet-stream Added: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/logo.png URL: http://svn.apache.org/viewvc/felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/logo.png?rev=711894&view=auto ============================================================================== Binary file - no diff available. Propchange: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/logo.png ------------------------------------------------------------------------------ svn:mime-type = application/octet-stream Added: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/mail_small.gif URL: http://svn.apache.org/viewvc/felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/mail_small.gif?rev=711894&view=auto ============================================================================== Binary file - no diff available. Propchange: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/mail_small.gif ------------------------------------------------------------------------------ svn:mime-type = application/octet-stream Added: felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/site.css URL: http://svn.apache.org/viewvc/felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/site.css?rev=711894&view=auto ============================================================================== --- felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/site.css (added) +++ felix/trunk/main/doc/apache-felix-framework-launching-and-embedding_files/site.css Thu Nov 6 08:22:54 2008 @@ -0,0 +1,25 @@ +/* @override http://felix.apache.org/site/media.data/site.css */ + +body { background-color: #ffffff; color: #3b3b3b; font-family: Tahoma, Arial, sans-serif; font-size: 10pt; line-height: 140% } +h1, h2, h3, h4, h5, h6 { font-weight: normal; color: #000000; line-height: 100%; margin-top: 0px} +h1 { font-size: 200% } +h2 { font-size: 175% } +h3 { font-size: 150% } +h4 { font-size: 140% } +h5 { font-size: 130% } +h6 { font-size: 120% } +a { color: #1980af } +a:visited { color: #1980af } +a:hover { color: #1faae9 } +.title { position: absolute; left: 1px; right: 1px; top:25px; height: 81px; background: url(http://felix.apache.org/site/media.data/gradient.png) repeat-x; background-position: bottom; } +.logo { position: absolute; width: 15em; height: 81px; text-align: center; } +.header { text-align: right; margin-right: 20pt; margin-top: 30pt;} +.menu { border-top: 10px solid #f9bb00; position: absolute; top: 107px; left: 1px; width: 15em; bottom: 0px; padding: 0px; background-color: #fcfcfc } +.menu ul { background-color: #fdf5d9; list-style: none; padding-left: 4em; margin-top: 0px; padding-top: 2em; padding-bottom: 2em; margin-left: 0px; color: #4a4a43} +.menu a { text-decoration: none; color: #4a4a43 } +.main { position: absolute; border-top: 10px solid #cde0ea; top: 107px; left: 15em; right: 1px; margin-left: 2px; padding-right: 4em; padding-left: 1em; padding-top: 1em;} +.code { background-color: #eeeeee; border: solid 1px black; padding: 0.5em } +.code-keyword { color: #880000 } +.code-quote { color: #008800 } +.code-object { color: #0000dd } +.code-java { margin: 0em } \ No newline at end of file