It is very typical how have code which is supposed to run not on all environments, but only on some. For example you might have code which is supposed to import data only on the authoring instance.
Then code often looks like this:
if (isAuthoring) { // import data } boolean isAuthoring() { return slingSettingsService.getRunmodes().contains("author"); }
This code does what it’s supposed to do. But there can be a problem, that you want to run this code not only on authors, but (for whatever reasons) also on publish. Or you don’t want to run the code on UAT authors.
In such cases this code does not work anymore, because it’s not flexible enough (the runmode is hardcoded); any change requires a code change and deployment.
A better way is to reformulate the requirement a bit: “The data import will only run if there is the ‘importActive’ flag set to true”.
If you design this flag “importActive” as an OSGI config, and combine it with runmode dependent configuration, then you can achieve the same behaviour as above, but be much more flexible. You can even disable it (and if only for a certain time).
The code could then look like this
@Property (boolValue="true") private static final String IMPORT_ACTIVE_PROP = "importActive"; private boolean importActive(); Protected activate(ComponentContext ctx) { importActive = PropertiesUtil (ctx.getProperties().get(IMPORT_ACTIVE_PROP)); } if (importActive) { // import data }
Now you translate the requirement “imports should only happen on authoring” into a configuration decision, and it’s no longer hardcoded. And that’s why the reason why I will be picky on code reviews about it.
On my project we had similar task: import for pages should be performed only on author instance.
To implement this functionality, we used ConfigurationPolicy.REQUIRED for the service that performed import.
If on author instance there is no config file for this service, service doesn`t exist on author instance, and import is not performed.
In this case there is no need for creating an OSGI config with flag value and add check on Java code.
Yeah, that’s another approach which can often solve such requirements quite elegantly.