2
votes

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.

2

2 Answers

6
votes

You didn't said in what type of Java class you'd like to get the configuration. Let's go through options:

1. Any OSGi service (like servlet, filter or event listener)

Add following field to the OSGi component class:

@Reference
private ConfigurationAdmin configurationAdmin;

and use it in the same way as in the JSP.

2. OSGi service to which the sling:OsgiConfig belongs

If you added sling:OsgiConfig node to configure your own OSGi component, follow Chris advice:

@Component
@Properties({
    @Property(name = "propertyPath")
})
public class MyComponent {

    private String[] propertyPath;

    @Activate
    public void activate(ComponentContext ctx) {
        propertyPath = PropertiesUtil.toStringArray(context.getProperties().get("propertyPath"));
    }

    public void myMethod() {
        // do something with the propertyPath field
    }
}

The activate method is invoked automatically by the OSGi. Qualified name of ComponentContext is org.osgi.service.component.ComponentContext

3. Plain Old Java Object

If your class is not an OSGi component, you need to have access at least to the SlingHttpServletRequest object. If you do, you can extract SlingScriptHelper from it and use it to obtain ConfigurationAdmin:

SlingHttpServletRequest request = ...;
SlingBindings bindings = (SlingBindings) request.getAttribute(SlingBindings.class.getName());
SlingScriptHelper sling = bindings.getSling();
// here you can use your JSP code
0
votes

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"));
}