Monday, September 28, 2009

Spring DM OSGi demo app

As you will see Spring DM makes life much simpler! It manages all “OSGi aware” pieces of the application for you and you can rid of the Activators.
The bundles we need now are similar as before. I will prefix “spring” to the artifactId just so its easier.
The shared service: We don’t need to change anything in shared so just use the older one as-is.
Creating a service implementation: The ComplexService we defined now needs to be implemented and made available as an OSGi service. Lets create a simple ComplexServiceImpl:
public class ComplexServiceImpl implements ComplexService {
 public String doSomething() {
  return "Hello from Version 1!";
To register the service we now use the OSGi extender provided by Spring DM. All we need to do is create some XML configs.
<?xml version="1.0" encoding="UTF-8"?>
<beans ..... >
  <!-- Create bean -->
  <bean id="complexService" class="com.irahul.spring.complexapp.ComplexServiceImpl"/>
  <!-- register service -->
  <osgi:service ref="complexService" interface="com.irahul.shared.ComplexService" />
Creating the servlet: In Spring world we just create the handler and then wire it up using XML.
public class MyHandler implements Servlet {
 private HttpService httpService;
 private List<ComplexService> complexServices;
 public void setHttpService(HttpService httpService){
  this.httpService = httpService;  
 public void setComplexServices(List<ComplexService> complexServices) {
  this.complexServices = complexServices;
 //ideally this should be externalized. Have a manager listen for servlets but keeping it simple
 public void init() throws Exception{
  httpService.registerServlet("/", this, null, null); 
 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!");
   //there are 1...n services, pick one
   //using a random pick
     new Random().nextInt(complexServices.size())).doSomething());
Configuring it:
<?xml version="1.0" encoding="UTF-8"?>
<beans ..... >
  <!-- Reference list of services in OSGi -->
  <osgi:list id="complexServiceList" interface="com.irahul.shared.ComplexService" cardinality="0..N"/>
  <!-- Reference to Http Service -->
  <osgi:reference id="httpService" interface="org.osgi.service.http.HttpService"/>
  <!-- Create handler -->
  <bean id="myHandler" class="com.irahul.spring.http.handler.MyHandler" init-method="init">
   <property name="complexServices" ref="complexServiceList"/>
   <property name="httpService" ref="httpService"/>

No comments: