gdrooid
gdrooid

Reputation: 158

Pretty URLs in OSGi ServiceTracker

I need to register servlets with a ServiceTracker using pretty URLs à la api/item/5.

Looking for a way to do it I found a SO answer that looks like it should do exactly what I'm trying to do, but it doesn't work for me. when I register a servlet with a URL like api/item/*, to access it I have to use exactly that URL, * included. It doesn't treat * as a wildcard.

Is there any way to get pretty URLs in OSGi, or using api/item?id=5 style URLs is the only way? If it's possible, how?

This is my code:

package hmi;

import hmi.api.get.*;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpService;
import org.osgi.util.tracker.ServiceTracker;

public class HMIServiceTracker extends ServiceTracker {

    public HMIServiceTracker (BundleContext context) {
        super (context, HttpService.class.getName(), null);
    }

    public Object addingService (ServiceReference reference) {
        HttpService httpService = (HttpService) super.addingService (reference);
        if (httpService == null) {
            return null;
        }

        try {
            httpService.registerServlet ("/hmi/api/get/appliance_list", new ApplianceList(), null, null);
            httpService.registerServlet ("/hmi/api/get/appliance/*", new Appliance(), null, null);
            httpService.registerResources ("/hmi", "/web", null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return httpService;
    }

    public void removedService (ServiceReference reference, Object service) {
        HttpService httpService = (HttpService) service;

        httpService.unregister ("/hmi/api/get/appliance_list");
        httpService.unregister ("/hmi/api/get/appliance/*");
        httpService.unregister ("/hmi");

        super.removedService (reference, service);
    }
}

Upvotes: 0

Views: 108

Answers (1)

Gunnar
Gunnar

Reputation: 2359

As per the HTTP service specification, all paths are matched by prefix matching. Thus, you should drop the /* from the url. If you register the servlet using api/item then everything below that url will also trigger your servlet.

Within the servlet, use HttpServletRequest#getPathInfo() to obtain everything after api/item.

Upvotes: 2

Related Questions