CQ5 - sling:OsgiConfig service in Java class

Tags: java osgi cq5 sling
Question!

I have created a sling:OsgiConfig node which is having a property paths of type String[]. I need to access this property in a java class. I want to make a method in java class that I would call from my JSP. I am doing this using taglib. I know we can achieve the same in JSP using the code below:

    Configuration conf = sling.getService(org.osgi.service.cm.ConfigurationAdmin.class).getConfiguration("Name of the config");
String[] myProp = (String[]) conf.getProperties().get("propertyPath");

How can I do this in a Java class.



Answers

You need to use that code in the activate method of your service. You can identify your class as a service by using annotations.

@Component(label = "Title", description = "Description.", immediate = true, metatype = true, policy = ConfigurationPolicy.REQUIRE)
@Service(value = {YourServiceInterface.class})
@Properties({
    @Property(name = "propertyPath", label = "Property Label", description = "Property Desc.")
})

Then you can define an activate method to pull them out.

protected void activate(ComponentContext context) throws RepositoryException {
    String[] myProp = (String[])context.getProperties().get("propertyPath");
    // or
    String[] myProp = PropertiesUtil.toStringArray(context.getProperties().get("propertyPath"));
}


This video can help you solving your question :)
By: admin