Working with Properties Files

Bundles, just like any Java code, sometimes wish to work with properties. While it is always possible to define System properties when the Java VM is started using the Java VM argument -D, this is not convenient for bundles that are loaded and unloaded without restarting the Java VM.

Another approach is for a bundle to add its properties to the System properties when it starts, and to remove its properties from the System properties when it stops. The BaseBundleActivator class does not do this for you, but does provide API that makes it easier for a bundle to do exactly this.

Once you've defined where the bundle will load its properties from, the properties are accessed using the BaseBundleActivator method getProperties(). The getProperties method lazily creates and caches the Properties() object, allowing the bundle to work with the properties however it wishes. For example, the bundle could add the properties to the System properties in its start() method and remove the properties from the System properties in its stop() method. This might be done as follows:

public class Activator extends BaseBundleActivator {
  ...
  protected InputStream getPropertiesInputStream() throws IOException {
    return getFilePropertiesInputStream();
  }

  protected void handleFailedToFindProperties(String filename) {
    // No-op: It is OK for properties to not exist.
  }

  protected void start() throws Exception {
    Properties properties = getProperties();
    Enumeration keys = properties.propertyNames();
    Map sysProps = System.getProperties();

    while (keys.hasMoreElements() == true) {
      String key = (String) keys.nextElement();
      Object value = properties.getProperty(key);
      sysProps.put(key, value);
  }

  protected void stop() throws Exception {
    Properties properties = getProperties();
    Enumeration keys = properties.propertyNames();
    Map sysProps = System.getProperties();

    while (keys.hasMoreElements() == true) {
      String key = (String) keys.nextElement();
      sysProps.remove(key);
    }
  }
}