Previous | Home | Next


Working with OSGi applications

A detailed explanation of the OSGi framework is out of the scope of this publication. Refer to the following sources for more information about that topic:


OSGi overview

Open Services Gateway initiative (OSGi) is a framework based on Java technology. OSGi enables you to write modular, dynamic, and versioning applications. WAS V8.5 uses the Eclipse Equinox as the framework for OSGi applications and OSGi V4.2.

We can design and build applications from coherent, versioned, reusable OSGi modules that are accessed only through well-defined interfaces. The new features of WAS V8.5 support for OSGi applications includes the following list:

The OSGi framework in WAS provides support for each of the layers of the OSGi Architecture:


OSGi application model


OSGi bundles and bundle archives

The unit of deployment in OSGi is a bundle. A bundle is a standard JAR or WAR file with additional metadata in the manifest file. Because the standard Java environment ignores these additional properties, we can also use an OSGi bundle with classic Java applications.

There are several bundles and bundle archives within an OGSi application:


OSGi Bundle Manifest file

The metadata for an OSGi application is defined in manifest files. An OSGi bundle contains a bundle manifest. A composite bundle archive contains a composite bundle manifest. An enterprise bundle archive contains an application manifest. An enterprise bundle archive asset contains a deployment manifest which is generated automatically when the enterprise bundle archive file is imported as an asset.

In this section we focus on the OSGi bundle manifest located under META-INF/MANIFEST.MF.

For other manifest information, refer to the following website: http://www14.software.ibm.com/webapp/wsbroker/redirect?version=phil&product=was-nd -dist&topic=ca_manifest We now check each element of the example manifest shown as Example 27-1.

Example of bundle manifest file, META-INF/MANIFEST.MF

Manifest-Version: 1.0 Bundle-ManifestVersion: 2
Bundle-Name: MyLibrary bundle
Bundle-SymbolicName: com.sample.mylibrary
Bundle-Version: 42.0.0
Bundle-Activator: com.sample.mylibrary.Activator
Import-Package: org.osgi.framework;version=”[1.0.0,2.0.0)”
Export-Package:

com.sample.mylibrary.stringops;version=23.2.1,com.sample.mylibrary.integerops;ver
sion=5.0.0
Meta-Persistence: entities/persistence.xml,

 lib/thirdPartyEntities.jar!/META-INF/persistence.xml
Web-ContextPath: /contextRoot
Export-EJB:
Bundle-Blueprint: /blueprint/*.xml

The following list explains the elements of the bundle manifest file

OSGi Service

OSGi also introduces a service registry layer used for collaboration between bundles. An OSGi service is published to the service registry under one or more Java interface names with any optional metadata stored as custom properties.

Bundles publish services to the service registry, and other bundles can discover them by looking up a service in the service registry. Bundles can filter service registry searches using the interface name and custom properties.

OSGi Applications in WAS usually interact with the OSGi service registry through a Blueprint module definition. POJO bean components, that are described in the Blueprint module definition, can be registered as services through a <service> element or can have service references injected into them through a <reference> element.

Services are fully dynamic, and typically have the same lifecycle as the bundle that provides them. Provider bundles can be stopped and started causing POJO services registered and de-registered, independently of the lifecycle of the consuming bundles. However, bundles can choose to publish and retract services dynamically due to changes in the environment, for example, due to one required service going away or coming back.


Enterprise OSGi

OSGi was originally targeted to support Java Platform, Standard Edition, but Version 4.2 of the OSGi specification introduces additional support for Java Platform, Enterprise Edition.

These extensions allow developers to write an OSGi enterprise application using methods that are similar to writing Java EE applications. The following Java EE technologies are integrated with the OSGi framework:

The specifications allow developers to write an OSGi enterprise application using methods that are similar to writing Java EE applications. Because the OSGi model is non-invasive to the classic Java EE model, both applications can be used in the same run time.


Using the sample application

In this section, we use an ITSOBank sample application to explain the OSGi packaging model. To work with the OSGi application, we use IBM Assembly and Deploy Tools for WebSphere Administration v8.5. However, we can use any other tool that supports the OSGi framework.


Downloading the application

To access and use the sample application:

  1. To download the sample application, go to the following website: http://www.redbooks.ibm.com/abstracts/sg247835.html?Open

  2. Click the Additional Material link.

  3. Click the sg247835.zip file, and select Save to save the compressed file to your computer.

  4. Extract the compressed file, and find the OSGi_ITSO_example.zip file. This file is located in the 7835codesolution/osgi directory.


Importing the application to the development tool

To use the sample OSGi_ITSO_example application for our exercise, import the projects files into IBM Assembly and Deploy Tools for WebSphere Administration by completing the following steps:

  1. Start IBM Assembly and Deploy Tools for WebSphere Administration.

  2. Click...

      File | Import | Existing projects into workspace | Next

  3. Click Browse next to the Select root directory, and point to the root folder where you extracted the OSGi_ITSO_example.zip file. Click OK.

  4. The process discovers the five projects. Click Select All to select all of the projects. Select Copy projects into workspace.

  5. Click Finish.

  6. The IBM Assembly and Deploy Tools for WebSphere Administration promotes a Workspace Migration window. Click Select All, and make sure the check boxes of all five projects are selected, and click Next. In the Migration Project Resource window, click Next. In the Undefined Server Runtime window select the WAS V8.5 as New Server Runtime and accept all default settings. In the Complete Migration Startup window, click Finish. After the migration process complete, a dialog confirms the migration completed successfully.

  7. After the projects are loaded to your workspace, copy all the JAR files used by itso.bank.web bundle from the OSGi_ITSO_example\jar files directory. Then, in the Enterprise Explorer view of the workspace, expand the itso.bank.web application, and paste the files into the WEB-INF/lib directory. Note that this method is only one way to supply libraries to the web project.

    After importing the projects, we can use the Enterprise Explorer perspective to preview the ITSOBank application projects...

    To have a fully operational OSGi ITSOBank application, additional configuration is required, such as configuring the data source on the server.


    Packaging OSGi applications


Common OSGi patterns

Consider using the following common OSGi patterns that have special support in the packaging of OSGi applications:


Sample application packaging

The ITSOBank is a simple application, but it presents a good approach about how to design OSGi modules. This application is built from four bundles that follow a three-tier architecture of front end, business logic, and back end.

If an OSGi application provides or requires any external services and references, these are explicitly made available by declaring them in an application manifest. The application manifest describes modularity at the application level in a similar way to OSGi headers in a bundle manifest file that define modularity at the bundle level.

A single main application project, itso.bank.app, holds a descriptor META-INF/APPLICATION.MF file, which configures bundles used by the application.

APPLICATION.MF of itso.bank.app application

Application-Name: itso.bank.app
Application-SymbolicName: itso.bank.app
Application-ManifestVersion: 1.0 Application-Version: 1.0.0.qualifier
Manifest-Version: 1.0 Application-Content: itso.bank.api;version="1.0.0",

itso.bank.biz;version="1.0.0",
itso.bank.persistence;version="1.0.0",
itso.bank.web;version="1.0.0"

The other projects define each bundle as follows:

itso.bank.api An API bundle containing the interfaces that connect the web logic to the business logic and the business logic to persistence.
itso.bank.biz A business bundle containing the business logic and acts as an intermediary between the presentation logic and the database.
itso.bank.persistance A persistence bundle that encapsulates the JPA-based database access pattern.
itso.bank.web A web bundle for servlets, JSPs, and static content that delegates the actual business functionality to the business bundle.

The three-tier application split is a standard pattern, but in an OSGi model, it contains a number of OSGi specific twists.

All of the implementation layers are connected through interfaces only. OSGi helps to verify concrete classes are not visible. Thus, individual module developers can only choose to use the provided interfaces. It is a best practice to minimize class dependencies and to ensure unit testability. To obtain concrete implementation of the service interfaces, module developers can use the OSGi service registry.

As a second step, we use a Blueprint to provide the fine-grained dependency injection that separates the wiring of business beans to and from services from their implementation.

Finally, there is the API bundle, which warrants a closer look. In a traditional Java EE style development, we might have included the interfaces in the bundles that also provide the implementation. Alternatively, in OSGi development, we focus more on deciding on packaging and module boundaries. The key criterias define responsibilities and frequency of change across the entire module lifecycle.

Providing the service or entity interfaces and implementing the interfaces are two separate concerns. For example, with the persistence interface (besides a JPA-based persistence implementation mechanism), we can investigate other mechanisms that accesses a no-SQL persistence store or a flat file. Separating the concerns earlier in the process pays off, rather than packaging the interfaces in each separate implementation.

The frequency of change also distinguishes interfaces and implementation. Interfaces change less often because the cost for change is high and because client code can be broken are. Alternatively, the hidden implementation classes change more frequently without requiring interface changes, in particular, as result of defects. Thus, separate packaging conceptually means we can update the implementation without changing the interface bundles. Replacing interface classes can never be done seamlessly, but replacing a service implementation can.


Exporting OSGi applications

To export an OSGi application from the IBM Assembly and Deploy Tools for WebSphere Administration from the Enterprise application view:

  1. Select the main OSGi application (itso.bank.app in this case), right-click itso.bank.app and then click Export | Export.

  2. From the context window, click OSGi Application (EBA) application type.

  3. Enter the location of the exported file in the To EBA file field. The .eba extension is added automatically to this file. Click Finish. Figure 27-7 shows the OSGi application export window.

An OSGI package for deployment is built and validated. In this case, a file called c:\IBM\itsobank.eba is created. We can inspect this file for its content and generated descriptor files. Notice that if you select the Replace qualifier with time stamp option, the generated versions and bundles name qualifier part is a time stamp.

When generating an application without using this option, the files are saved with the following names:

We can also use other tools to build your OSGi applications, such as Ant or Maven, and automate them with wsadmin scripts.

Refer to the following web sites:


Additional considerations when exporting OSGi applications

Because of the complexities of the OSGi class loader, give special consideration to importing an exported package. When a package is exported, the package can be used by a separate bundle before the exported bundle is even started. This situation can be a problem when singletons and static fields are used because an imported class is loaded by a separate class loader than the class loader used by the bundle. This creates separate instances of the service object.

For example, suppose bundleA exports a service object responsible for generating sequential order numbers. Also, suppose that three other bundles import and use that service object for generating order numbers. Those three other bundles use the framework class loader and share the same instance of the service object. If bundleA also imports the package, it also uses the same instance. However, if bundleA does not import the package, the bundle class loader instantiates a new instance of the service object and possibly produces a duplicate list of order numbers.

So the practices noted indicate that you typically must import any packages that you export to reduce the number of copies of that package in memory and to ensure the object instances come from the same class loader.


Deploying OSGi applications

We can deploy an OSGi application by adding an enterprise bundle archive asset to a business-level application. The deployment can be done using the dmgr console or wsadmin. Installing through the dmgr console is useful when dealing with complex application structures involving multiple versions and sharing. Using the dmgr console for the first installation is also useful for capturing script commands for future use with wsadmin.

OSGi applications are packaged in enterprise bundle archive files. Deploying applications packaged this way involves completing the following steps:

  1. Import the enterprise bundle archive file as an asset.

  2. Add that asset to the business-level application as a composition unit.


Importing the enterprise bundle archive file as an asset

To import the enterprise bundle archive file as an asset:

  1. In the dmgr console, click...

      Applications | Application Types | Assets | Import

    Select the itsobank.eba file exported earlier.

  2. In the wizard, accept all the defaults.

  3. In the summary step, click Finish to import the asset. Enterprise bundle archive asset conversion and resolution warnings or other information might display in the upper-left corner.

  4. After processing is complete and without error, save your changes. For OSGi applications, provisioning happens when importing the asset. As a result of provisioning, bundles might need to be retrieved from a bundle repository (internal or external). This process needs to be complete before the asset can be added to a business-level application. However, downloads are triggered only after the asset import is saved. Thus, saving the changes after importing the asset is required.


Add the enterprise bundle archive asset to the business-level application

To add the enterprise bundle archive asset to the business-level applications:

  1. To create a new empty business-level application...

      Applications | Application Types | Business-level applications | New

    Enter a name for the application. ITSOBank Systems is used in this example. Click Apply.

    In the business-level application detail panel, click Add | Add Asset in the Deployed Assets section.

  2. Choose the asset that was created.

  3. A wizard starts the new composition unit that will be created. In the wizard, the first step is to set the options for the composition unit

    In the asset wizard, the following fields are displayed. The following list describes the fields:

    • Backing ID: Displays the unique identifier for the composition unit registered in the application domain. We cannot change this setting.

    • Name: Name for the composition unit.

    • Starting weight: Specifies the order in which composition units are started when the server starts. The composition unit with the lowest number is started first.

    • Start composition unit upon distribution: Whether to start the composition unit when it is distributed to other locations. Applies only to assets and shared library composition units.

    • Restart behavior on update (of the composition unit):
      • ALL: Restarts the composition unit after the entire composition unit is updated.
      • DEFAULT: Restarts the composition unit after the part of the composition unit is updated.
      • NONE: Does not restart the composition unit after the composition unit is updated.

    • Click Next.

    • While still in the asset wizard, its second step is to map the composition unit to a target. Select the server on which the itso.bank.app application will run.

    • The third step within the asset wizard is to map the context root for the web modules. Select the Context Root to which the itso.bank.app is to be mapped (default is /itsobank).

    • The fourth step within the asset wizard is to map the virtual hosts for the web modules. Select the desired virtual host.

    • In the Summary page of the wizard, click Finish.

    • Save the changes.

Now we can start the business-level application. There are other wizard steps depending on the bundles and archives contained in your OSGi application.

There are some restrictions for OSGi application deployment:

We can also use wsadmin to deploy the OSGi application, it is the common method used in a production environment.


Administrating OSGi applications

In this section, we focus on the OSGi application update, adding a new bundle to the bundle repository, and OSGi application security. More information: the OSGi application administration, refer to the following website: http://www14.software.ibm.com/webapp/wsbroker/redirect?version=phil&product=was-ex press-dist&topic=ta_admin


Updating OSGi applications

After you import your OSGi application as an asset, newer versions of the bundles or composite bundles the asset uses might become available. We can configure the deployed asset to use an updated version, specific bundle version, or to pull in the latest compatible version. WAS does not update the asset to a newer version automatically.

Before you update an OSGi application, ensure the new update bundles have a valid and updated version value. If the new bundle version is the same as the old bundle version, the OSGi run time treats the original version and the new version interchangeably (despite potentially different build numbers).

In this example, we update the ITSO Bank OSGi application


Add the updated bundle or composite bundle to a bundle repository

To update the ITSO Bank application, the new bundle is added to the internal OSGi bundler repository:

  1. In the dmgr console click Environment | OSGi bundle repositories | Internal bundle repository.

  2. Click New, and in the Specify path field, enter the path to the new bundle. Choose to specify a path on your local computer or on the remote network manager environment.

    In this case, we use the itso.bank.biz bundle v1.0.1 that was exported from IBM Assembly and Deploy Tools for WebSphere Administration. This bundle is a single JAR file.

  3. Click OK, and save the configuration.


Updating bundle versions in a deployed OSGi application

After the new bundle is added to the repository, configure the ITSO Bank application to use it explicitly, using the following steps:

  1. Click Applications | Application Types | Assets, and choose the ITSO Bank application.

  2. Under the Additional Properties section, click the Update bundle versions in this application link.

  3. From the new form, choose the new version of the itso.bank.biz bundle, as shown on

    Select the version: The drop-down menus list all the available versions plus the No preference option. Selecting a specific version instructs the provisioning system to use exactly that version for the update. Selecting No preference instructs the provisioning system to find the highest version that works with the other selections.

    With both selections, the new version must fall into the range specified in the application manifest. For example, the following application content specifies that only bundle versions from 1.0.0 but less than 2.0.0 are admissible during provisioning and during updates:

      Application-Content: itso.bank.biz;version="[1.0.0,2.0.0)"

  4. If no errors occur during processing, a message displays that selected bundle versions can be resolved. Click Create.

    At this time, the configured bundles are downloaded from repositories, in this case from an internal OSGi repository on WAS. The OSGi run time must cache the bundles locally so that applications are not affected by changes to the bundle repositories. This process of downloading the new versions to create local copies can take a small amount of time with external repositories or large bundles, but is mostly instantaneous when working with the internal bundle repository. We can check the status of downloads from the asset detail window or the composition unit detail window.

  5. Save your changes to the master configuration. Checking the status of the OSGi composition unit and update

We can check the update status of the OSGi composition unit in the dmgr console:

  1. Click Applications | Application Types | Business-level applications | application_name | composition_unit_name.

  2. Check the deployment status. It is displayed under General Properties and then OSGi application deployment status.

    The OSGi composition unit status: There are four distinct deployment statuses for an OSGi composition unit:

  3. Using the latest OSGi application deployment.

  4. New OSGi application deployment not yet available because it requires bundles that are still downloading.

  5. New OSGi application deployment available.

  6. New OSGi application deployment cannot be applied because bundle downloads have failed.

  7. If you plan to update the composition unit at this time, we can update the OSGi composition unit so the business-level application uses the newer configuration. Click Update to latest deployment under...

      Business-level applications | ITSOBank application | ITSOBank eba asset

More information: Updating OSGi applications


Secure OSGi applications

Securing OSGi applications in WAS is similar to securing enterprise applications. The following options are available for use:

  • Using application security with OSGi applications: – Modify the security role to user or group mapping.

    In the dmgr console, Click Applications | Application Types | Business-level applications | application_name | [Deployed assets] Add | Add Asset | asset_name | Wizard step: Map security roles to users or groups – Use application security with web application bundles. Define security constraints in web.xml for a web application bundle. – Configure bean security in the Blueprint XML file.

    This is new feature introduced in WAS V8.5. You configure security by defining one or more <access-constraint> elements, inside the <bean> element of Blueprint XML file of your OSGi application.

    An example of bean security of an OSGi application

    <bean class="com.sample.secureBeanImpl">
    <sec:access-constraint role="ROLE1" />
    <sec:access-constraint method="getID" role="ROLE2" />
    
    </bean>
    

    The two levels of security configuration are: • Configuring bean-level security: In Example 27-3, the methods of the secureBean1 bean are accessible only by users assigned the role called ROLE1. • Configuring method-level security: In Example 27-3, the getID method of the secureBean1 bean is accessible only by users assigned ROLE2. – Use application security with EJB bundles. Enforce any bean method security settings in the ejb-jar.xml file for an EJB bundle.

  • Use Java 2 security with OSGi applications. Similar as Java 2 security in enterprise applications, WAS allows you to have a permissions.perm file in the META-INF directory of the OSGi application. This permissions.perm file applies fine-grained control of the permissions for each bundle.

    More information: securing OSGi application, refer to the following website: http://www14.software.ibm.com/webapp/wsbroker/redirect?version=phil&product=was-ba se-iseries&topic=ta_sec