Build OSGi applications with Aries

Introducing Apache Aries

Aries is an Apache Incubator project aimed at providing an OSGi-pluggable framework for building applications. This article introduces Aries and OSGi concepts and shows how to create OSGi-compliant modules that you can use to build an application.

Share:

Nathan A. Good, Senior Consultant and Freelance Developer, Enterprise Frameworks

Nathan GoodNathan A. Good lives in the Twin Cities area of Minnesota. Professionally, he does software development, software architecture, and systems administration. When he's not writing software, he enjoys building PCs and servers, reading about and working with new technologies, and trying to get his friends to make the move to open source software. He's written and co-written many books and articles, including Professional Red Hat Enterprise Linux 3, Regular Expression Recipes: A Problem-Solution Approach, and Foundations of PEAR: Rapid PHP Development.



10 August 2010

Also available in Chinese Japanese

The OSGi Alliance consists of a group of many different contributors that govern and maintain the OSGi specifications. OSGi technology enables a service- and module-based architecture using Java™ technology, and it is found in many leading products and frameworks.

Frequently used acronyms

  • API: Application programming interface
  • IDE: Integrated development environment
  • JAR: Java archive
  • XML: Extensible Markup Language

One example of a common product that uses OSGi technology is the Eclipse IDE. Eclipse plug-ins use OSGi technology for its benefits in building modular applications. Eclipse comes with a useful OSGi console that allows you to test OSGi modules by installing and running them. (The examples in this article use these OSGi tools to demonstrate some of the OSGi features.) Common frameworks, such as Spring, use OSGi technology to enable the creation and use of pluggable modules.

Many application servers, such as IBM WebSphere® Application Server, Apache Geronimo, JBoss, Glassfish, and Oracle®/BEA WebLogic use OSGi technology, as well.

You enable modular service-oriented components and features with OSGi technology in a couple of ways. First, the OSGi specification determines how classes are loaded for OSGi bundles, which is an important feature that allows modules to have different libraries yet function well together. Each bundle is sandboxed, which means that versions of logging libraries with one bundle won't conflict with different versions of the same product in different bundles.

Second, the OSGi specification requires that the implementations of the modules include well-defined interfaces and a manifest containing detailed information about the content. This use of interfaces and metadata in the manifest enforces loosely coupled yet tightly cohesive modules. One best practice for building Java interfaces and the Java classes that implement them includes putting the interfaces and implementations in separate bundles.

Required components

To get the most out of this article, you should already have the following tools installed:

There's a lot to learn about OSGi. You can find links to more information in the Resources section, but a quick summary of some of the goals of the OSGi framework is important for understanding the use and goals of Apache Aries:

  • Reduced complexity. OSGi is made up of bundles. Bundles are completely modular, communicating with one another only through service interfaces.
  • Reuse. Because the OSGi bundles are completely modular, they enable better reuse. Some open source projects package their Java classes in OSGi bundle-compliant JARs.
  • Easy deployment. The OSGi framework provides a standardized API that enables OSGi implementations to have tools for installing, starting, and stopping OSGi bundles.
  • Dynamic updates. Because OSGi bundles are modular and easy to deploy, you can make updates without having to restart an application.
  • Versioning. Dynamic updating and the sandboxing feature of bundles allow you to deploy and easily use different versions of bundles without running into conflicts between JARs. Class loading is sandboxed to each bundle, so dependencies such as logging frameworks can be different between bundles without causing problems.

Get to know Aries

The goal of Apache Aries is to enable the construction of enterprise applications using OSGi as an underlying technology to tie the various parts together. Using Aries, you can build the different application parts using technologies such as the Java Transaction API (JTA) and the Java Persistence API (JPA) and expose them as OSGi services and modules. The OSGi modules in Aries are scoped to the particular application, so they aren't visible outside the application you build using Aries. See Resources for links to more information about the Apache Aries Incubator project.

OutOfMemory

While running the Maven target on my computer, I ran into OutOfMemory errors. I resolved these errors by typing export MAVEN_OPTS=-Xmx265M, and then re-running the mvn command.

Downloading and installing Aries

You download Aries in source code form, and you build it locally. Instructions for doing so are provided on the Aries site for different ways to build the Aries source (see Resources). The examples here use Maven to build the Aries project and then import the code into Eclipse.

To download and install Aries, perform the following steps:

  1. Check the code out for Aries using Subversion on the command line:

    svn export https://svn.apache.org/repos/asf/incubator/aries/trunk
  2. Once you have the code checked out, prepare to download it with Maven using the following command:

    mvn clean
  3. Prepare the code so that you can import it into an Eclipse workspace using the following Maven command:

    mvn eclipse:eclipse
  4. Import the Aries projects into Eclipse by clicking File > Import and then clicking General > Existing projects into Eclipse.

Building a service

Now that you have downloaded and built the Aries code and imported it into Eclipse, you are ready to create your own service projects based on the HelloWorld examples. The sample service echoes the message that you give it, but backwards. This example demonstrates how you can send messages to services from a client.

First, write the interface for the service. Ideally, interfaces in OSGi applications should be in separate bundles (projects) from the implementation classes. This practice does make the project structure in Eclipse a bit more complex, but the benefit is that you can swap out the implementation bundles much more easily. Quickly changing the implementation of a service is one of the reasons for using a technology such as OSGi, which enforces a modular structure.

The EchoService interface is shown in Listing 1. It contains one method that accepts an argument to do something with the message in the implementation of the interface. It also contains an initialize method. The purpose of the method is to demonstrate how methods on the service can be called when the OSGi framework starts the service.

Listing 1. The EchoService Java interface
package com.example.echo.api;

public interface EchoService {

    void echoMessage(String message);
    
    void initialize();
    
}

With the interface written, you are ready to write the client class that calls the methods that the interface exposes. The client class is shown in Listing 2.

Listing 2. The EchoServiceClient class
package com.example.echo.client;

import com.example.echo.api.EchoService;

public class EchoServiceClient {

    private EchoService service;

    public void initialize()
    {
        String message = "My Message";
        service.echoMessage(message);
    }
    
    public EchoService getService() {
        return service;
    }

    public void setService(final EchoService service) {
        this.service = service;
    }
    
}

Now, add a class for implementation of the EchoService. Create yet another project for the service implementation bundle called com.example.echo.service, and add a project reference to the com.example.echo.api project.

Common naming conventions include naming the class something like EchoServiceImpl; I like using DefaultEchoService—naming the services after the type of implementation they are. This implementation class will be the default implementation for the EchoService interface, shown in Listing 3.

Listing 3. The DefaultEchoService implementation
package com.example.echo.service;

import com.example.echo.api.EchoService;

public class DefaultEchoService implements EchoService {

    public void echoMessage(final String message) {
        StringBuilder sb = new StringBuilder(message);
        sb.reverse();
        System.out.println(sb.toString());
    }

    public void initialize() {
        System.out.println(this.getClass().getName() + " is initialized.");
    }

}

Next, you must edit the files that tell Aries how to find and deploy the services.


Deploying the service

At this point, you should have a client class, an interface, and one class that implements the interface. These three classes should be in three separate projects—one file in each project. Now that you have the classes defined, you are ready to create the XML files that tell Aries what to do with the classes.

The client configuration file is shown in Listing 4.

Listing 4. The client configuration file
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
    <reference id="echoService" interface="com.example.echo.api.EchoService" />
    <bean id="echoClient" class="com.example.echo.client.EchoServiceClient"
        init-method="initialize">
        <property name="service" ref="echoService" />
    </bean>
</blueprint>

Note that the client configuration file has a reference to the echoService, which is also defined in the file along with the fully qualified name of the Java interface.

The server configuration file (shown in Listing 5) is similar to the client configuration file. It specifies the interface as a service, with a reference to the bean element, which contains the fully qualified name of the service implementation.

Listing 5. The services configuration file
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
    <bean id="echoServiceImpl" class="com.example.echo.service.DefaultEchoService"
        init-method="initialize">
        <property name="service" ref="echoService" />
    </bean>
    <service id="echoService" interface="com.example.echo.api.EchoService" />
</blueprint>

Here, you can see that you gain quite a bit of power by having the implementation class defined in the configuration file: The implementation can change without your having to change any code and without the client resources being affected.

Now that you have the XML configuration files added to the two projects—the client and the service projects—you're ready to compile the projects, assemble them into JAR files, and see how they look when started using an OSGi console.

For the OSGi console, this application uses the console that comes with the Eclipse IDE. Alternatively, you can use Apache Felix, which is another project from Apache that is an implementation of an OSGi container (see Resources).

A simple Apache Ant script (see Listing 6) compiles all of the projects, builds the JAR files, and puts the JARs into a single folder. From this folder, you will launch the OSGi console.

Listing 6. A simple Ant script for building and packaging the bundles
<project name="build.echo" default="build" basedir=".">
    
    <property name="src" value="src" />
    <property name="build" value="bin" />
    <property name="dist" value="dist" />
    <property name="workspacedir" 
        value="${basedir}/.." />
    <property name="api" 
        value="${workspacedir}/com.example.echo.api" />
    <property name="client" 
        value="${workspacedir}/com.example.echo.client" />
    <property name="services" 
        value="${workspacedir}/com.example.echo.services" />

    
    <target name="build">
        <javac srcdir="${api}/${src}" destdir="${api}/${build}"/>
        <javac srcdir="${client}/${src}" destdir="${client}/${build}"/>
        <javac srcdir="${services}/${src}" destdir="${services}/${build}"/>
    </target>
    
    <target name="package">
        <mkdir dir="${dist}" />
        <jar jarfile="${dist}/com.example.echo.api.jar" 
            basedir="${api}/build" />
        <jar jarfile="${dist}/com.example.echo.client.jar" 
            basedir="${client}/build" />
        <jar jarfile="${dist}/com.example.echo.services.jar" 
            basedir="${services}/build" />
    </target>
    
</project>

Run the Ant script from Eclipse, using the target build to build the JAR files. Once the build is complete, run the following command to launch the OSGi console:

java -jar org.eclipse.osgi_3.5.0.v20090520.jar -console

With the OSGi console running, you can see the status of the modules by typing ss at the console. See Listing 7 for an example of OSGi console output.

Listing 7. Listing the services
osgi> ss

Framework is launched.

id      State       Bundle
0       ACTIVE      org.eclipse.osgi_3.5.0.v20090520
1       ACTIVE      org.eclipse.equinox.cm_3.2.0.v20070116
2       ACTIVE      org.eclipse.osgi.services_3.1.200.v20070605
3       ACTIVE      org.ops4j.pax.logging.pax-logging-api_1.4.0
4       ACTIVE      org.ops4j.pax.logging.pax-logging-service_1.4.0
5       ACTIVE      org.apache.aries.util_0.2.0.incubating-SNAPSHOT
6       ACTIVE      org.apache.aries.blueprint_0.2.0.incubating-SNAPSHOT
7       RESOLVED    com.example.echo.api_1.0.0
8       RESOLVED    com.example.echo.client_1.0.0
9       RESOLVED    com.example.echo.server_1.0.0

To start any of the services, use the start command (for example, start 8).


Using OSGi services in a web container

Now that you have created a few OSGi bundles and have seen them in action, you are ready to learn how Aries can use the OSGi bundles in a web application package.

You can start Aries web applications by putting the project components (see Resources for links to download binary versions) that were compiled when you ran the mvn install task into a directory and starting the OSGi console. As the Aries components are all started, a load directory will be created.

Web applications are built from OSGi modules that are packaged in an archive file with an .eba file extension. These .eba files have a common format: If the EchoService interface you just built had an additional bundle that contained Java servlets, the contents of the .eba file would look something like Listing 8.

Listing 8. Sample .eba file
META-INF/APPLICATION.MF 
com.example.echo.api.jar 
com.example.echo.client.jar
com.example.echo.service.jar 
com.example.echo.web.jar

When dropped into the load directory while an instance of Aries is running, Aries unpacks the .eba file and loads and starts the bundles inside the .eba file. To uninstall the application from Aries, simply remove the file from the load directory.

After you drop an .eba file into the load directory, you can view the web application by navigating to the URL (for example, http://localhost:8080/com.example.echo.web/) in a browser.

The blog example that comes with Aries demonstrates how you can put the web bundle together. The mvn eclipse:eclipse command you ran earlier prepared the samples for the blog to be imported into Eclipse, too. The sample projects are shown in Listing 9.

Listing 9. Sample web bundle projects
org.apache.aries.samples.blog.api
org.apache.aries.samples.blog.biz
org.apache.aries.samples.blog.datasource
org.apache.aries.samples.blog.itests
org.apache.aries.samples.blog.jdbc.eba
org.apache.aries.samples.blog.jpa.eba
org.apache.aries.samples.blog.peristence.jdbc
org.apache.aries.samples.blog.peristence.jpa
org.apache.aries.samples.blog.web

Digging deeper

Similar and complementary projects and products to Aries provide many different ways of building applications that use OSGi technologies. Listed here are some related technologies that you can use to build, manage, and distribute OSGi components into applications.

Apache Felix and Apache Felix Karaf

Apache Felix is a core OSGi framework implementation. The Felix OSGi framework implementation has many sub projects—for example, Apache Felix Karaf, which provides an OSGi run time in which you can deploy Aries—that add components for creating a full-featured OSGi framework implementation. Learn more about Apache Felix and Felix Karaf in Resources.

Apache ServiceMix

Apache ServiceMix provides an Enterprise Service Bus (ESB) and was the original source of the Felix Karaf run time. ServiceMix is built using OSGi components and offers the ability to use OSGi technologies with Service-Oriented Architecture (SOA).

WebSphere Feature Pack

A Feature Pack for OSGi Applications and Java Persistence for IBM WebSphere Application Server version 7 implements the Blueprint Container specification, which Aries also uses (see Resources). The Blueprint Container is responsible for the following functions:

  • Using the XML configuration files for components
  • Instantiating and initializing the components
  • Enabling communication between the components
  • Registering services and looking them up

The Feature Pack enables you to deploy applications as collections of OSGi bundles, similar to Aries.


Conclusion

The Aries project is currently in the Apache Incubator but has the goal of enabling the development of applications that use OSGi technologies to build modular applications. OSGi is a technology that you can use to build Java services and modules that are truly modular, pluggable components.

You can download Aries and import it into Eclipse. From there, using the sample applications in this article as templates, you can build your own services that demonstrate some of the abilities of Aries.

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=505706
ArticleTitle=Build OSGi applications with Aries
publish-date=08102010