We introduced the current general state of OSGi in the former preface. The following is about the commonly used OSGi framework and its application instances.
1.1 Equinox
1.1.1 Introduction
First let’s have a look at Equinox. It is one of projects in Eclipse and is well known for OSGi R4 RI, the project’s advantages as the OSGi framework are reflected by the successful Eclipse IDE. In the current, Equinox is released along with Eclipse, at the same time, it can be downloaded independently, and the independent download page has all implementations of Equinox on OSGi R4 and the Bundle for Equinox extending OSGi R4.
The developing group of Equinox is led by Jeff who is a staff from IBM; it is an active and productive group viewing from the point of developer maillist, everyone interested in it can apply for joining the maillist:
http://dev.eclipse.org/mailman/listinfo/equinox-dev.
To get further information about Equinox please login the following web sites:
Official site: http://www.eclipse.org/equinox
Chinese site: http://china.osgiusers.org
The next is to introduce how to set up your developing environment.
1.1.2 Developing Environment Configuration
Now that it is based on Equinox to develop application, we should first download Equinox. Equinox is an Eclipse project and through it Eclipse3.1 or later versions only could start up. Eclipses after version3.1 have included Equinox and you can see a file like org.eclipse.osgi_3.4.3_R34x_v20081215-1030.jar in the directory named plugins (Different Eclipse version has different version number and date). This file in fact is the Equinox implementation on OSGi R4 Core. If there is an Eclipse earlier than version 3.1, it is advised to download a more advanced version.
Now is to start up Eclipse and check the developing environment;
Ø First step, open Run Configurations dialog (figure 1-1)
Figure 1-1 Run Configuration Menu
Ø Second step, create a new running configuration of OSGi Framework type. (Figure 1-2)
Figure 1-2 Create a New Running Configuration
Ø Third step, display all Bundles (Figure 1-3)
Figure 1-3 Display All Bundles
Ø Forth step, deselect all Bundles (Figure 1-4 )
Figure 1-4 Deselect All Bundles
Ø Fifth step, select the Bundle named org.eclipse.osgi (Figure 1-5)
Figure 1-5 Result after Selecting Bundle org.eclipse.osgi
Ø Sixth step, run and see the results.
Click the Run button, if “osgi>” displays in the Console and there are no errors, the developing environment is alright. Now input ss following the “osgi>” then type enter key, the figure 1-6 will display.
Figure 1-6 Executive Results
Well, the settings are ready. Next let us begin the first OSGi application.
1.1.3 Hello World
In the section, I will create an classical example Hello World. You must have seen the Hello World example programmed in Java, C or C++ language where a string “Hello World” is output and then the program ended. Instead of outputting “Hello World”, this Hello World has to do something when starting and stopping a Bundle. Now let’s create this example step by step.
Ø Step 1, create a Bundle project.
n Create a Plug-in project in Eclipse IDE. (Figure 1-7)
Figure 1-7 Create a Plug-in Project
n Input necessary info related to the project, the only different point from ordinary Java project is to select “this plug-in is targeted to run with”, here check “an OSGi framework” and select standard item in the dropdown box, that is to create a standard OSGi Bundle project. (figure 1-8)
n Enter the data required to generate the plug-in. (figure 1-9)
l Plug-in ID is the unique identifier; you can assure its uniqueness by adopting the style of Java package naming policy in practical projects.
l Plug-in Version is the version of the Bundle you created.
l Plug-in Name denotes the expressive name of your Bundle.
l Plug-in Provider denotes the Bundle provider.
l Execution Environment denotes the settings Bundles need to execute.
l The rest is the key Activator textbox in which you can input a Class name and the Class would be constructed by Eclipse when the project is created.
Figure 1-8 Set the Plug-in Project
Figure 1-9 Set the Plug-in Meta Info
n After Bundle project finished, you can get the view like the following figure in the package view, now it is indicated the project is successfully created.
Figure 1-10 Plug-in Project Content in Package View
Ø Step 2, finish Activator code segment.
n Open the default file HelloWorldActivator.java. (figure 1-11)
Figure 1-11 Default Activator Code Segments
We can see the Class HelloWorldActivator implements the Interface BundleActivator and has two empty methods – stop and start. The start method is called when starting up Bundle and the stop method called when stopping Bundle. Next we need to add codes in these two methods. (Figure 1-12 )
Figure 1-12 Modified Activator Codes
At this point, the Hello World demo is finished and let’s run it to see the results.
Ø Step 3, run the program.
n First create a configuration used for Hello World execution. (Figure 1-13)
Figure 1-13 Bundles Settings for HelloWorld Demo
n Next set the value of the Auto-Start property to false by the dropdown box and uncheck the unused Bundles included by Target Platform.
Then click the Auto-Start in the line of the HelloWorld to select false in the dropdown box and uncheck the Target Platform making all items it includes deselect. Next, click “Add Required Bundles” button in the right and the pane before the Target Platform becomes partially selected at this moment, last check “Only show selected bundles”. In this way, the settings for the HelloWorld execution are completed. (Figure 1-14)
Figure 1-14 Bundles Settings for Execution
n Now click the “Run” button, if the “osgi>” prompt appears, that is to say the first OSGi application is done.
Input “ss” behind the “osgi>” prompt and type Enter, the output info will be like this. (Figure 1-15)
Figure 1-15 Running Results
As the output info shows, the Bundle HelloWorld has been installed and resolved but not started. Now input “start 1” and type Enter to see what will happen. Yes, we see “HelloWorldBundle started!” Go on to input “ss”, the results will look like the following. (Figure 1-16)
Figure 1-16 Results When Starting Bundle
Here, we can see the HelloWorldBundle state has become “ACTIVE” from “RESOLVED” state, it is showed the “HelloWorldBundle” has been started successfully. At the same time, the messages added in the start method are output correctly.
Then input “stop 1” and “ss” respectively, the console messages would be like what figure 1-17 displays.
Figure 1-17 Results When Stopping Bundle
Now the HelloWorldBundle is stopped. The added messages in the stop method are displayed in the console and the HelloWorldBundle state changes into “RESOLVED” from “ACTIVE”.
By this point, we complete creating the first OSGi Bundle - HelloWorldBundle and execute it successfully. The following chapters will describe some more complicated demo programs.
1.1.4 Develop the Conventional Applications
1.1.4.1 B/S Applications
At first, let’s discuss how to develop the B/S application based on OSGi. Generally, there are two ways to develop an OSGi based B/S application, one way is installing a built-in Http application server in OSGi framework; Another one is integrating OSGi framework in Servlet container. Next, let me introduce how to realize the two developing styles. In addition, this section also offers an example using “Declarative Service”.
Now image such a B/S application which can function as a small dictionary. When a user input a word through the browser and type “Submit”, the application gives the word’s explanation. Of course, the application would not realize the requirement in detail and only support consulting a few words. If you are interested, you can complete it.
For this example, there are four Bundles including dictionary consulting response Bundle, dictionary consulting interface Bundle, local dictionary service Bundle and remote dictionary service Bundle. The general design can be illustrated by figure 1-18.
Figure 1-18 Design of the Bundles
These Bundles are described as below.
1. Consult Response Bundle
The Bundle offers a page for inputting word to be queried, retrieves the dictionary service from BundleContext, gets the consult results by calling the consult interface of the dictionary service and returns the results to the query page.
2. Dictionary Consulting Interface Bundle
The Bundle offers an interface for dictionary consulting.
3. Local Dictionary Service Bundle
The Bundle offers a dictionary consulting service for looking up the local dictionary.
4. Remote Dictionary Service Bundle
The Bundle offers a dictionary consulting service for looking up the remote dictionary.
Well, I think you cannot wait to construct the first B/S application.
Build Http application server into OSGi framework
In this section, we will build the Http Server into OSGi framework to develop this dictionary consulting system. First step is to get the developing environment ready according to the above mentioned HelloWorld demo that needs only one Bundle. But for this slightly more complicated example, there needs more Bundles to set up the developing environment.
We create a new running configuration of OSGi framework in the “Run Configuration” dialog where the following Bundles like javax.servlet, org.apache.commons.logging, org.eclipse.equinox.http.jetty, org.eclipse.equinox.http.servlet, org.eclipse.osgi, org.eclipse.osgi.services and org.mortbay.jetty will be selected, it is showed in figure 1-19.
Figure 1-19 The checked Bundles in the Run Configuration dialog
There are some startup logs output after clicking Run button. If “osgi>” is output then the running settings are alright; if there is something like “Address already in use:JVM_Bind” output, it is showed that the port 80 is in used because the Http Service of Equinox has the default port value 80, then we can reset its default port value by opening the Arguments tab and add “_Dorg.osgi.service.http.port=8080” in VM arguments in the Run Configuration dialog. In this example, we use the default value 80, on starting up input “ss” and type enter, the following info in figure 1-20 will be displayed.
Now, the environment is ok and you will see frame like figure1-21 when you input http://localhost/ in the browser.
Figure 1-20 Running information
Figure1-21 Output info in the browser
At this moment, the Http Server is start up successfully and you can begin the Bundle creation.
Ø Fisrt, create the dictionary consulting interface bundle project.
Construct a Plug-in project named DictQuery like figure 1-22 showed.
Figure 1-22 Setting the plug-in info
Then, create an interface class “QueryService” in package named ogr.osgichina.demo.dictquery.query, see figure 1-23.
Figure 1-23 Interface QueryService
This Bundle is used for interface export, so not to modify BundleActivator of the Bundle.
Open the file “MANIFEST.MF” in this project and the info will be displayed like figure 1-24.
Figure 1-24 MANIFEST.MF info
We will see a few tabs included “Overview”, “Dependencies”, “Runtime”, “Build”, “MANIFEST.MF” and “build. properties” in this window. Any modifications in “Overview”, “Dependencies”, “Runtime”, “Build” will be mapped into the two files “MANIFEST.MF” and “build. properties”.
Next step is to export the interface package in order that other Bundle can use the package.
Select the “Runtime” tab and click “Add” button, then select the package including “QueryServie” and click “save” to finish this operation. See figure 1-25 in the following.
Figure 1-25 Exported package
This line showed below will be appended in the MANIFEST.MF file.
Now we finish developing the dictionary consulting interface Bundle, the next task is to develop the local dictionary consulting Bundle.
Ø Second, develop the dictionary consulting Bundle.
n Create a plug-in project named LocalDictQuery.
n Import the dictionary consulting interface and realize a real class for dictionary consulting.
Open the MANIFEST.MF file of the project and select the “Dependencies” tab. Click the “Add” button on the right side, select the above exported package: org.osgichina.demo.dictquery.query in the popup dialog and click “save” button to finish import operation. Now, have a look at the MANIFEST.MF file, you will see the line “org.osgichina.demo.dictquery.query” is listed like figure1-26.
Figure 1-26 The imported packages
n Then, it’s time to code the implementation class LocalDictQueryServiceImpl which implements the interface QueryService. The method “queryWord” in the class can retrieve query result from the local dictionary, if there is no query result, “N/A” is returned. The code segment is showed in figure 1-27.
Figure1-27 code segment of LocalDictQueryServiceImpl
n The last task is to write code for “Activator”, see figure 1-28 below, to register the dictionary consulting service “LocalDictQueryServiceImp” provided above when starting up Bundle. How to let the other Bundles use the dictionary consulting service LocalDictQueryServiceImp? In OSGi framework, this is realized by the way of service registering with BundleContext. In the following section, there will be an example to use the service instance.
Figure 1-28 code segment of Activator
From the code constructs, we can see there are two modifications on the system-generated code. One is the variable of ServiceRegistration type “sr”, the other one is adding a line of code in the start method and the stop method, respectively. Now let’s have a look at the two lines of code.
The code shows that full class name of QueryService is used for the registered service name, the newly created LocalDictQueryServiceImpl object is registered as a service whose usage will be introduced in the below content.
This line of code is used to cancel the registered services. At this point, the Bundle for query request handling is done.
Ø Third, develop the Bundle for remote dictionary consulting service.
This Bundle is very similar to the LocalDictQuery except for this project name is RemoteDictQuery. In addition, the service provided in this Bundle is different from what the LocalDictQuery provides in order that the two services can be distinguished.
The following figure 1-29 shows code section implementing the interface QueryService.
Figure 1-29 the code section of RemoteDictQueryServiceImpl
The last task is to finish the dictionary consulting response Bundle.
Ø Forth, construct the dictionary consulting response Bundel.
Not like the conventional Web application development, it is needed to register the Servlet and the resource files (such as css, html, pictures and so on) through HttpService to access services instead of deploying the Web applications into the web servers, because OSGi framework has no such a Bundle like the application server. For this simple demo, there provides a dictionary consulting page and servlet corresponding to the page. Create a directory named “page” in “src” and create a file dictquery.htm and the dictionary consulting response servlet in the “page” folder, in addition, the Servlet API including javax.servlet and javax.servlet.http should be imported because the servlet extends HttpServlet. Next, you have to import another two packages org.osgichina.demo.dictquery.query and org.osgi.service.http. It is showed in figure 1-30.
Figure 1-30 the imported packages
Then, we can write the servlet code which is no difference from the common servlet besides the doGet method like the below.
ServiceReference serviceRef =
context.getServiceReference(QueryService.class.getName());
if (null ! = serviceRef ) {
queryService = (QueryService) context.getService(serviceRef);
}
Here, the “context”, is the passed BundleContext as creating the Servlet, by which the dictionary consulting service is acquired. First, an object of ServiceReference type is returned when using the “context” to get the reference to the Service; then, to get an instance of the Service based on the ServiceReference; next, methods in the Service can be called to conduct the dictionary consulting.
Moreover, the Servlet has to be registered in the Http server on starting up the dictionary consulting response Bundle. Realted codes are writed in BundleActivator, you can see them in source codes package.
Now, a casual dictionary consulting system is done, let’s have a run and see how it looks.
Launch the application and type “ss” behind the “osgi>”, you will note the effect like figure 1-31 below.
Figure 1-31 the effect after starting up the Bundles
Start up the browser and type http://localhost/demo/page/dictquery.htm in URL bar, you will see the running result like figure 1-32.
Figure 1-32 the running result of the dictionary consulting system in the browser
Stop the number 11 Bundle of RemoteDicQuery, type test and click “查询”button, the result will look like the below.
, and the following messages will be output in the console.
Now, the dictionary consulting system development is completed.