ConfigurationAdmin Through OSGI Component Service

One of the fundamental requirement to create a OSGi service to read OSGI config to read  configurable properties .

1. Create Osgi Config Node under your apps  and read that through Service like this

2. Sample OSGI Component reads default com.day.cq.mailer.DefaultMailService PID.

package com.abc.ch.service;
import java.io.IOException;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(immediate=true)
@Service(AbcOsgiConfigService.class)
public class AbcOsgiConfigService {
    
    private final Logger LOGGER = LoggerFactory
            .getLogger(AbcOsgiConfigService.class);
    
    @Reference
    ConfigurationAdmin configurationAdmin;
    
    public void activate(ComponentContext ctx){
        LOGGER.info(” activating “);
        BundleContext bundleCtx=ctx.getBundleContext();
        ServiceReference ref = bundleCtx.getServiceReference(ConfigurationAdmin.class.getName());
        
        if (ref != null) {
            configurationAdmin = (ConfigurationAdmin) bundleCtx.getService(ref);
            Configuration config;
            try {
              config = configurationAdmin.getConfiguration(“com.day.cq.mailer.DefaultMailService”);
              LOGGER.info(” Got the Config”+config.getProperties().get(“smtp.host”).toString());
            } catch (IOException e) {
                LOGGER.error(“Error trying to look up datasource configuration”, e);
            }
          }       
    }   
}

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s