Search code examples
configapache-commonsapache-commons-config

Detecting file reload in Apache Commons Configuration2


Using org.apache.commons:commons-configuration2:2.1 my application needs to know when a configuration file has been reloaded so that it can update some things in the program. Apache Commons Configuration2 uses a lot of strategies and factories, and usually that's great, but here it's getting so complicated I can't figure out where I need to install a listener.

The application has this:

configConfigurationBuilder = new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(
    PropertiesConfiguration.class)
        .configure(new Parameters().properties().setFile(getConfigFile()));
final PeriodicReloadingTrigger configReloadingTrigger = new PeriodicReloadingTrigger(
    configConfigurationBuilder.getReloadingController(), null, 1, TimeUnit.MINUTES);
configReloadingTrigger.start();

Which of these various things can I install a listener on? I just want to be notified when the configuration file is reloaded.

I notice that the ReloadingDetector interface has a reloadingPerformed() method, and that sounds like what I want. But how do I add my own ReloadingDetector? It seems like the ReloadingController only keeps one ReloadingDetector around. Surely I don't have to subclass ReloadingDetector and install a custom one, would I? I'm not wanting to specialize the reloading detection, so subclassing would not be appropriate --- I just want to be notified when something happens. Besides, it's not obvious to me where I would even hook into the ReloadingFileBasedConfigurationBuilder chain of events where it uses some internal factor to create the detector.

So how can I easily get Apache Commons Configuration2 to notify me when it reloads a configuration?


Solution

  • I posted this question to the Apache Commons mailing list, and Oliver Heger replied:

    You can add an event listener at the ReloadingController, then you receive notifications of type ReloadingEvent.

    Alternatively, you could also register a more generic listener for events on the configuration builder itself. When the builder's managed configuration is reset, a corresponding event is produced. This also happens during a reload operation.

    At first I was confused about whether these events are sent out when the need for a reload is detected or after the reload has occured, but he reminded me:

    Maybe a misunderstanding of the reloading mechanism: New data is not automatically pushed into a Configuration object you might have a reference to. Rather, the configuration builder is reset. So the next time you query the builder for a configuration you get a new one with updated data.

    When you receive one of the mentioned events the builder has been reset and thus you know that new data is available.

    That was a useful answer, which I'm sharing to help others. (I wish the Apache Commons developers monitored and were active on Stack Overflow.)