home personal workZone travel about
code.pst » tech musings and code posts

Posts Tagged ‘Java’

Pure Java OSGi demo implementation

Thursday, September 24th, 2009

To interface with OSGi we need a handle to the BundleContext. OSGi provides for an ‘activator’ that is basically the main() method for when a bundle gets started. To create an activator we will implement the BundleActivator interface. The interface has start and stop methods which are invoked at times that their names suggest and you can control the behavior in your implementing class. Then in the Maven plugin (in the POM) add this instruction:

....
<Bundle-Activator>com.irahul.http.handler.Activator</Bundle-Activator>
....

The shared service: The interface for the shared service is one simple method

....
String doSomething();
....

Creating a service implementation: The ComplexService we defined now needs to be implemented and made available as an OSGi service. Here is the Activator:

public class Activator implements BundleActivator{
	public void start(BundleContext context) throws Exception {		
		//register the complex service impl		
		context.registerService("com.irahul.shared.ComplexService",				
				new ComplexService(){
					public String doSomething() {
						return "Hello from Version 1!";
					}			
				}, 
				null);
	}
	.....
}

The service is implemented and registered with the bundle context.

Creating the servlet: This is done by implementing the Servlet interface. The ComplexService does something and the response is sent back to the client. The service to be used is chosen at random in this simple example.

public class MyHandler implements Servlet {
	private List<ComplexService> complexServices = new ArrayList<ComplexService>();
 
	public synchronized void addComplexService(ComplexService service) {
		if(service==null)return;
		complexServices.add(service);
	}
 
	public synchronized void removeComplexService(ComplexService svc) {
		if(svc==null)return;
		complexServices.remove(svc);
	}
 
	public void service(ServletRequest request, ServletResponse response)
		throws ServletException, IOException {
 
		//we may have discovered more than 1 service
		if(complexServices==null|| complexServices.size()==0){
			response.getOutputStream().print("No Service found!");
		}
		else{
			//there are 1...n services, pick one
			//using a random pick
			response.getOutputStream().print(complexServices.get(
					new Random().nextInt(complexServices.size())).doSomething());
		}
	}
 
	....
}

Creating the http handler: The Activator for the HTTP Handler must now get a reference to this service and in turn register itself with the HTTP Server.

In addition to the BundleActivator I am also going to implement the ServiceListener interface. This allows us to get event notifications as services start/stop. We want to dynamically support multiple versions of the ComplexService. The Activator looks like this:

public class Activator implements BundleActivator, ServiceListener{
	private MyHandler myHandler;
	private BundleContext bundleContext;
 
	public void start(BundleContext context) throws Exception {
		//we need this later
		bundleContext = context;
 
		//we are interested in service updates
		context.addServiceListener(this);
 
		//load referenced services		
		//http service to register handler
		ServiceReference svcRef = context.getServiceReference("org.osgi.service.http.HttpService");
		HttpService httpService = (HttpService)context.getService(svcRef);
 
		//create and register http handler (catch all)
		myHandler = new MyHandler();		
		httpService.registerServlet("/", myHandler, null, null);
 
		//get a list of ComplexService (there may be more than 1)
		ServiceReference[] complexSvcRefs = context.getServiceReferences("com.irahul.shared.ComplexService",null);
		if(complexSvcRefs!=null){
			for(ServiceReference ref:complexSvcRefs){
				myHandler.addComplexService((ComplexService)context.getService(ref));
			}
		}
 
		System.err.println("http.handler started!");
	}
	....
	public void serviceChanged(ServiceEvent event) {
		//some service has been registred/removed
		Object svc=bundleContext.getService(event.getServiceReference());
 
		if(svc instanceof ComplexService){
			if(event.getType()==ServiceEvent.REGISTERED){
				System.err.println("New Service added");
				myHandler.addComplexService((ComplexService)svc);
			}
			else{
				System.err.println("Service stopped");
				myHandler.removeComplexService((ComplexService)svc);
			}
		}
	}
}

Download full source.

Next: Running this in Eclipse Equinox

Getting started with OSGi

Thursday, September 17th, 2009

This is the first part in a series for a presentation at the Silicon Valley Code Camp at Foothill college.

For a concise description read through the official OSGi Architecure page.

I’ll present a simple application that shows how to dynamically provide an application upgrade with zero downtime and no JVM restart. It will load a HTTP Server and then register a handler with it. This handler then processes the request using a ComplexService. Multiple bundles of this ComplexService implementation are possible (suppose V1 and V2). We can start the OSGi container with 0 or more of these and let the handler decide which one to use. If we start with suppose V1 then we can load V2 and stop V1, creating an update without a JVM restart.

The following sequence diagram shows the events.

Sequence diagram for OSGi example

Sequence diagram for OSGi example

With this simple set of bundles (less than 200 lines of code in all!) I can show the following:

Run multiple versions of your app simultaneously: If your application is designed with this mind, you can continue to run singletons of the http server and your data access layer, however you have multiple versions of your business logic which may be used dynamically.

Dynamic routing: Expanding on the point above you can build a smart routing mechanism to invoke the different versions of the services that are available.

Install new bundles to upgrade features: You may create new services and register them with the http server to provide new features all without a JVM restart.

Upgrade application version: You may install a new version of any service and shutdown and remove a previous version and have existing http services use this dynamically. Again no JVM restart.

Note on versioning: In OSGi it is possible to version packages exported/imported by bundles. For the purpose of this exercise I’ll keep things simple and not use it.

Download presentation: Getting started with OSGi

Next: Application design for this demo