Configure Your OSGi Services with Apache Felix File Install
A recent post about Managed Services reminded me of a feature in Apache Felix File Install that I found worth mentioning. While working on a project with Holger, I learned from him that File Install cannot only be used to manage bundles. It also monitors configuration files and updates Managed Services when their respective configuration changes.
File Install can also configure Manged Service Factories and more. Yet, I found it particularly useful for Managed Services whose configuration data is usually environment-specific (e.g. printer URLs, database URLs, TCP ports). And the best thing is: it frees you from programmatically fiddling with the Configuration Admin.
How it works
File Install can be told to watch a certain folder (usually through a system property). You can then place configuration files (plain Java property file) into that folder. Configuration files are associated to Managed Services by a naming convention. The file name must have the form <pid>.cfg. If there is a Managed Service with a matching PID, it is updated whenever the file changes.
Example
I put a minimal self-contained example on GitHub. It has a single bundle that provides an EchoService implemented like this:
public class EchoService implements ManagedService { public void updated( Dictionary<String, ?> properties ) { if( properties != null ) { System.out.println( "port = " + properties.get( "port" ) ); } } }
Easy to spot: its whole purpose is to print out the configuration whenever it changes.
The EchoService is registered with a PID of echoservice
. Besides the bundle is a project that contains the configuration file. It is named echoservice.cfg
and holds a single property: port = 7
.
The launch configuration puts together the neccessary bundles: OSGi framework (Equinox here), the example bundle, Felix Gogo Shell (to diagnose problems if any) and File Install along with the Configuration Admin. And these VM arguments
-Dfelix.fileinstall.dir="${project_loc:com.codeaffine.fileinstall.example.config}" -Dfelix.fileinstall.noInitialDelay=true -Dfelix.fileinstall.poll=1000
tell File Install to watch the project folder and check every Second for changes. Thanks to the project_loc
variable the launch configuration is portable across development environments.
Now that we start the OSGi framework, the console output will look like this:
port = 7
If we make a change to echoservice.cfg
file and wait a little, we will see that the EchoService is updated. The new configuration appears in the console log.
More of this
If this drew your interest you may want to have a deeper look at File Install. It also supports Managed Service Factories, can write back configuration changes, can substitue property values, and watch multiple folders. The documentation page has all the details.