0

II have a servlet (example" localhost:4502/bin/my-servlet-here) where I would need to access an OSGI service.

I've tried several stuff I saw online but I cannot get access/reference to the OSGI service from my servlet.

Any ideas on how it can be done?

In the code servlet class below, I was debugging in my IDE (IntelliJ) and it's hanging/not responding on the line that starts with "ServiceReference reference"

Thanks


my servlet class

package com.myhost.core.servlets;

import com.myhost.core.services.MyService;
import javax.annotation.Resource;
import javax.inject.Inject;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

@SlingServlet(paths = "/bin/myservlet", methods = "GET", metatype = true)
public class MyServlet extends SlingAllMethodsServlet {

    @Resource(name="BundleContext")
    private BundleContext context;

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {

    ServiceReference reference = context.getServiceReference(MyService.class.getName());
    MyService service = (MyService)context.getService(reference);

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json;charset=UTF-8");

    // the code the populates the JSON variable has been taken out

    printWriter.write(jsonObject.toString());
}

my service class

package com.myhost.core.services;

public interface MyService {
    String getPassword(String type);
}

my service class implementation

package com.myhost.core.services.impl;

import com.myhost.core.services.MyService;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.osgi.PropertiesUtil;
import java.util.Map;

@Service
@Component(metatype = true, label = "My Service Implementation")
public class MyServiceImpl implements MyService {    
    @Property(label = "property1")
    private static final String Property1 = "com.myhost.core.services.MyService.property1";
    private String property1;

    @Property(label = "property2")
    private static final String Property2 = "com.myhost.core.services.MyService.property2";
    private String property2;

    @Activate
    protected void activate(Map<String, Object> properties) {
        this.property1 = PropertiesUtil.toString(properties.get(Property1), null);
        this.property2 = PropertiesUtil.toString(properties.get(Property2), null);
    }

    @Override
    public String getProperty(int temp) {
        switch (temp) {
            case 1:
                return property1;
            case 2:
                return property2;
            default:
                return "";
        }
    }
}

4 Answers 4

2

You can use @Reference annotation and felix will inject it for you-

//MyServlet.class
.
.
@Reference
MyService service;
.
.

Here is an example for reference.

3
  • Thanks for the reply. I tried your suggestion and service=null. Any more ideas? Thank you
    – mrjayviper
    Commented Jun 25, 2019 at 1:15
  • what version of felix-scr-plugin and maven-bundle-pluging you are using? do you see scr descriptors generated in target/classes/OSGI-INF folder, if they are there you can go to /system/console/components on aem and search for your service, see that its in active status. also check error.log for any erros when installing bundle.
    – awd
    Commented Jun 25, 2019 at 3:57
  • also - though aem6.4 supports felix annotations, you should use osgi annotations as the other answer suggested, with latest version of maven bundle plugin.
    – awd
    Commented Jun 25, 2019 at 3:58
2

If you are using AEM 6.3 or above I would suggest using the OSGI declarative services. If less then SCR annotations. Below is a code snippet using the declarative services which I use for 6.3 and above

   //My sevlet Practice Servlet
@Component(service=Servlet.class,
property={
        Constants.SERVICE_DESCRIPTION + "=Practice Servlet",
        "sling.servlet.methods=" + HttpConstants.METHOD_GET,
        "sling.servlet.paths="+ "/bin/practice"
})


public class PracticeServlet extends SlingSafeMethodsServlet{

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Reference
    private PracticeService pracService;

My service class: PracticeService.java that I used above in the servlet

public interface PracticeService {

    public void printLogs(String Name);
}

My service implementation class: PracticeServiceImpl.java which implementing the above service class.

import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import aemdemo.core.service.PracticeService;

    @Component(service=PracticeService.class)
    public class PracticeServiceImpl implements PracticeService{

        private Logger log = LoggerFactory.getLogger(this.getClass());

        @Override
        public void printLogs(String name) {

            log.debug("Inside service!!!!!"+name);

        }

    }
3
  • Thanks for the reply. What should I use for the @reference in the servlet? Also I tried your suggestion of using org.osgi.service.component.annotations.Component. This piece of code stopped working: this.property1 = PropertiesUtil.toString(properties.get(Property1), null) It was working when I was still using org.apache.felix.scr.annotations.Component
    – mrjayviper
    Commented Jun 25, 2019 at 1:14
  • I've looking at org.osgi.service.component.annotations and it seems it doesn't have an equivalent property type like org.apache.felix
    – mrjayviper
    Commented Jun 25, 2019 at 1:25
  • see Migrating Properties section here -cqdump.wordpress.com/2019/01/03/…
    – awd
    Commented Jun 25, 2019 at 4:01
0

You should use @Reference, but not from Felix SCR. Use native OSGi annotations instead.

import org.osgi.service.component.annotations.*;


@Reference
private ResourceResolverFactory factory;

The felix annotations are in maintenance mode now... Ideally your whole project will run without felix scr. See http://www.nateyolles.com/blog/2017/05/osgi-declarative-services-annotations-in-aem for further explanations.

0

Since you are working with AEM 6.4.x, I would suggest using OSGi declarative service annotations instead of Felix SCR annotations as suggested by other community members.

To use those annotations, I have converted your code to use OSGi annotations by replacing Felix SCR annotations.

MyService.java

package org.redquark.aem.extensions.core.services;

public interface MyService {

    /**
     * This method returns the entered password into a hash equivalent with some
     * properties passed by the user
     * 
     * @param type
     * @return {@link String}
     */
    String getPassword(String type);
}

MyServiceImpl.java

package org.redquark.aem.extensions.core.services.impl;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.metatype.annotations.Designate;
import org.redquark.aem.extensions.core.config.MyConfiguration;
import org.redquark.aem.extensions.core.services.MyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(service = MyService.class, 
           property = {
                   "label=My Service Implementation"
                   }
        )
@Designate(ocd = MyConfiguration.class)
public class MyServiceImpl implements MyService {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    // Two properties to be read
    private String propertyOne;
    private String propertyTwo;

    @Activate
    protected void activate(MyConfiguration config) {
        // Reading properties from the configuration
        propertyOne = config.getPropertyOne();
        propertyTwo = config.getPropertyTwo();

    }

    @Override
    public String getPassword(String type) {

        // MD5 equivalent of password string
        String passwordHash = null;

        try {

            type = type + propertyOne + propertyTwo;

            log.info("Resulant password: " + type);

            // Convert string to bytes - this is for the sample implementation (for show casing)
            byte[] passwordByte = type.getBytes("UTF-8");

            // Getting instance of MessageDigest
            MessageDigest md = MessageDigest.getInstance("MD5");

            // Convert bytes array to hash using MD5 algorithm
            byte[] digest = md.digest(passwordByte);

            passwordHash = new String(digest);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return passwordHash;
    }

}

We are reading our custom properties in the activate method of service implementation.

SCR property annotations give you a lot of freedom. You can annotate them on top of the class (using the @Properties annotation as a container with nested @Property annotations), you can annotate individual constant values to be properties. You can make them visible in the OSGI web console (technically you are creating a metatype for them), or you can mark them as private (not metatype is created).

With OSGI annotations this is different.

Metatype properties are handled in the dedicated configuration class marked with @ObjectClassDefinition. They cannot be private. Properties which are considered to be private are attached to the @Component annotation. They cannot be changed anymore.

So, to handle these properties, we will create a separate interface with @ObjectClassDesfinition annotation and each property is annotated with @AttributeType annotation.

MyConfiguration.java

package org.redquark.aem.extensions.core.config;

import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.AttributeType;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;

@ObjectClassDefinition(name = "My Configuration", 
                       description = "This configuration will be used to read the value of properties.")
public @interface MyConfiguration {

    @AttributeDefinition(name = "Property One", description = "Read property one", type = AttributeType.STRING)
    public String getPropertyOne() default "Property One";

    @AttributeDefinition(name = "Property Two", description = "Read property two", type = AttributeType.STRING)
    public String getPropertyTwo() default "Property Two";
}

Now, finally comes your servlet -

MyServlet.java

package org.redquark.aem.extensions.core.servlets;

import java.io.IOException;

import javax.servlet.Servlet;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.redquark.aem.extensions.core.services.MyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(service = Servlet.class, property = { "sling.servlet.methods=" + HttpConstants.METHOD_GET,
        "sling.servlet.paths=" + "/bin/myservlet" })
public class MyServlet extends SlingAllMethodsServlet {

    // Generated serialVersionUID
    private static final long serialVersionUID = -8720724011172847122L;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    // Injecting reference of your service - No need to use BundleContext
    @Reference
    private MyService myService;

    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {

        try {

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");

            // Calling the method implementation from your service
            String password = myService.getPassword("Sample Type");

            log.info("Writing password to the browser...");

            response.getWriter().write(password);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

For the demo purpose, I have taken the liberty to create an MD5 hash equivalent of the password which also depends on the custom properties (propertyOne and propertyTwo). You can write your JSON implementation here.

You can check for another example with the Scheduler service here - https://aem.redquark.org/2018/10/day-13-schedulers-in-aem.html

I hope this helps to resolve your issue. Happy Coding! Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.