Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
OSGi - list all instances of a factory config
import aQute.bnd.annotation.metatype.Meta;
import com.liferay.portal.configuration.metatype.annotations.ExtendedObjectClassDefinition;
import com.liferay.portal.configuration.metatype.bnd.util.ConfigurableUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import java.io.IOException;
@Component
class ConfigsLister {
public void getConfigs() throws IOException, InvalidSyntaxException {
String filterString = String.format(
"(service.factoryPid=%s)", MyConfiguration.ID);
// You can even filter even on individual properties of the config, like 'myKey',
// to retrieve a single config (if you know its property you configured)
// String filterString = String.format(
// "(&(service.factoryPid=%s)(myKey=%s))",
// MyConfiguration.ID, "XYZ");
// retrieves all matching configs -- created for given factory from OSGi container
Configuration[] configurations =
_configurationAdmin.listConfigurations(filterString);
// _configurationAdmin::listConfigurations might return <null> (not empty array)
if (configurations == null) {
System.out.println("Sorry, no configs found with filter " + filterString);
return;
}
for(Configuration configuration: configurations) {
System.out.println(
"Found config: pid: " + configuration.getPid() + "), properties: " +
configuration.getProperties());
// Gives you an instance of MyConfiguration, to retrieve all your fields nicely typed
MyConfiguration typedConfig = ConfigurableUtil.createConfigurable(
MyConfiguration.class, configuration.getProperties());
String myKey = typedConfig.myKey();
// ...
}
}
@Reference
private ConfigurationAdmin _configurationAdmin;
// A sample OSGi config type
@ExtendedObjectClassDefinition(
category = "todo-my-category",
factoryInstanceLabelAttribute = "myKey",
scope = ExtendedObjectClassDefinition.Scope.SYSTEM
)
@Meta.OCD(
factory = true, id = MyConfiguration.ID,
localization = "content/Language", name = "todo-my-config.config-name"
)
public interface MyConfiguration {
String ID = "com.acme.MyConfiguration";
@Meta.AD(
name = "my-key", description = "my-key.description")
String myKey();
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment