Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nateyolles/244f5db8f4d5a92048c2 to your computer and use it in GitHub Desktop.
Save nateyolles/244f5db8f4d5a92048c2 to your computer and use it in GitHub Desktop.
Example component consuming the custom OsgiConfigurationService service
package com.nateyolles.sling.publick.services.impl;
import java.util.HashMap;
import java.util.Map;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import com.nateyolles.sling.publick.services.OsgiConfigurationService;
import org.osgi.framework.Constants;
/**
* Sample service that uses the custom OSGiConfigurationService to
* read and write OSGi configuration properties.
*/
@Service(value = OsgiConfigurationServiceConsumerExampleImpl.class)
@Component(name = "com.nateyolles.sling.publick.services.impl.OsgiConfigurationServiceConsumerExampleImpl", description = "example service which updates OSGi configs")
@Properties({
@Property(name = OsgiConfigurationServiceConsumerExampleImpl.FOO_API_KEY, label = "Foo Key", description = "The Foo API key"),
@Property(name = OsgiConfigurationServiceConsumerExampleImpl.FOO_ENABLED, boolValue = OsgiConfigurationServiceConsumerExampleImpl.ENABLED_DEFAULT_VALUE, label = "Enabled", description = "Enable Foo"),
@Property(name = Constants.SERVICE_DESCRIPTION, value = "OsgiConfigurationServiceConsumerExample service"),
})
public class OsgiConfigurationServiceConsumerExampleImpl implements OsgiConfigurationServiceConsumerExample {
/** Service to get and set OSGi properties. */
@Reference
private OsgiConfigurationService osgiService;
/** PID of the current OSGi component */
private static final String COMPONENT_PID = "com.nateyolles.sling.publick.services.impl.OsgiConfigurationServiceConsumerExample";
/** OSGi property name for the API key */
public static final String FOO_API_KEY = "foo.apiKey";
/** OSGi property name for enabled */
public static final String FOO_ENABLED = "foo.enabled";
/** Default value for enabled */
public static final boolean ENABLED_DEFAULT_VALUE = false;
public void foo() {
/* Get OSGi value for enabled property */
boolean isEnabled = osgiService.getProperty(COMPONENT_PID, FOO_ENABLED, ENABLED_DEFAULT_VALUE);
/* Set the OSGi value for enabled property */
osgiService.setProperty(COMPONENT_PID, FOO_ENABLED, "true");
/* Set multiple OSGi property values */
Map<String, Object> properties = new HashMap<>();
properties.put(FOO_ENABLED, true);
properties.put(FOO_API_KEY, "foo");
osgiService.setProperties(COMPONENT_PID, properties);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment