OSGi service usage sample details
After you run the sample, you can import and study the source files to learn more about how the OSGi service and the solution interact.
Running the sample
- Open the Samples Console perspective.
- In the Samples and Tutorials view, click View sample commands for the OSGi sample.
- Double-click run.application, and wait for the Console view to display BUILD SUCCESSFUL. This command runs the application by submitting an event. It might take a while for this command to finish.
- In a text editor, open the
<WLP_USER_DIR>/servers/cisDev/logs/console.log.
You can see the following
messages:
cis.sample@fr.ibm.com No loan service available or request is null.The API of the OSGi service is deployed but the implementation of the OSGi service is not deployed.
- Double-click install.service.impl, and wait for the Console view to display BUILD SUCCESSFUL. This command deploys the bundle that contains the service implementation.
- In Windows Explorer or
at a command line, open the <WLP_USER_DIR>/extension/lib folder,
and verify that it contains the following folder and file:
- features/LoanServiceFeature_1.0.0.0.mf
- com.ibm.cis.sample.LoanServices_1.0.0.0.jar
- View the contents of the <WLP_USER_DIR>/servers/cisDev/server.xml file. At the bottom of this file, you can see that the LoanServiceFeature_1.0.0.0 feature is now on the server.
- In a text editor, open the <WLP_USER_DIR>/servers/cisDev/logs/console.log.
You can see the following messages:
loan.service.impl.LoanImpl service created XXX loan service added - Double-click run.application, and wait for the Console view to display BUILD SUCCESSFUL. This command runs the application by submitting an event. It might take a while for this command to finish.
- In a text editor, open the
<WLP_USER_DIR>/servers/cisDev/logs/messages.log.
Near the end of the log, you can see the following
message:
Monthly repayment : 386.6560305885655 for Customer cis sampleAn event was sent by the client application. The solution processed the event, which involved the following steps:- The Java™ agent called the service.
- A response event was fired by the Java agent.
- A rule agent was triggered, and the display rule was fired and printed the message about the monthly repayment.
To check that the rule was fired, do the following steps:
- In the Sample Server view, click .
- Accept any security exception that is displayed. Insight Inspector opens and shows that two events were processed.
- Click the name of the solution. The information shows that a MortgageRequest event was emitted and processed by the Java agent that emitted the MortgageResponse event.
- Click the MortgageResponse event on the OSGISampleRuleAgent timeline.
Then, click Rules at the bottom of the page
and you can see that the display rule was fired.

Source files
The sample source files are in <InstallDir>/samples/osgi.
- LoanServiceFeatureApi, the OSGi service API packaging project
- LoanServicesApi, the OSGi service API project
- LoanServicesBOM, the business object model for the project
- LoanServiceFeature, the OSGi service implementation packaging project
- LoanServices, the OSGi service implementation project
- OSGISampleClient, the client application project
- OSGISampleJavaAgent, the Java agent project
- OSGISampleRuleAgent, the rule agent project
- OSGISampleSolution, the solution project
- OSGISampleSolution - Java Model, the generated XOM project
- OSGISampleSolutionBOM, the business object model project
How this sample works
- The OSGi service API that is used by the solution and the service implementation
- The OSGi service implementation that is used by the solution
- The OSGi service implementation that is used by the agents
- The LoanServicesBOM that makes the link between the Rule agent and the OSGi service
- The rule agent and the Java agent that handles events and calls the OSGi service
- The client application that sends events to Insight Server
The OSGi service API is implemented as an OSGi bundle that is packaged and deployed as a Liberty feature. It defines the Loan interface public double calculateMonthlyPayments(MortgageRequest request);.
The service API is composed of the projects LoanServicesApi, which defines the service interface, and LoanServiceFeatureApi, which defines the Liberty features that package the service definition.
Import-Package: loan.model;version="0.20.0.0";resolution:=optional, org.osgi.framework
The service is deployed as a Liberty feature. A Liberty feature consists of a feature manifest file and one or more OSGi bundles. The OSGi bundles contain classes and services that provide a particular capability when the feature is installed onto a Liberty profile server. It makes a library available to applications so that the external packages are visible on the default application class path. By copying the feature manifest into the ${wlp.user.dir}/extension/lib/features directory and the OSGi bundle into the ${wlp.user.dir}/extension/lib directory, the feature can be installed to the Liberty profile. The feature can then be used in the server.xml file.
- LoanServices, which defines the service implementation
- LoanServiceFeature, which defines the Liberty features that are packaging this service
The MortgageRequest class is defined in the BOM solution. The interface the service is implementing is defined in the bundle that contains the service API.
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<bean id="LoanImplBean" class="loan.service.impl.LoanImpl" />
<service id="LoanImpleBeanService" ref="LoanImplBean" interface="loan.service.Loan"></service>
</blueprint>
The preceding XML section defines a service that exposes an interface loan.service.Loan. The implementation is the loan.service.impl.LoanImpl class. When the OSGi service bundle is deployed, the blueprint container reads the content of the bundle, registers the service into the OSGi service registry, and creates an initial component instance. A bundle is considered to be a Blueprint bundle when it contains Blueprint XML files as specified in the Bundle-Blueprint manifest header or under the OSGI-INF/blueprint/ directory.
The solution has a rule agent and a Java agent.
when a MortgageResponse occurs
then
displayResult ( the monthly repayment of this MortgageResponse ,
the last name of the customer of this MortgageResponse ,
the first name of the customer of this MortgageResponse ) ;
public static void displayResult(double repayment, string lastName, string
firstName);
property "OSGi.service" "loan.service.Loan"
property "OSGi.service.version" "0.20.0.0"
public void displayResult(double repayment, String lastName, String
firstName)
{ System.out.println("Monthly Repayment: " + repayment + " for Customer " + firstName + " " + lastName); }
The Java agent reacts to MortgageRequest events and is defined in the <InstallDir>/samples/osgi/OSGISampleJavaAgent/agent.adsc file:
'osgisamplesolution.osgisamplejavaagent.MyJavaAgent' is an agent related to a Customer ,
processing events :
- MortgageRequest , where this Customer comes from the customer of this MortgageRequest
Various techniques can be used to get a service reference. For example, you could access a service by using the BundleContext and FrameworkUtil classes, as in the following code snippet:
BundleContext ctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
ServiceReference<loan.service.Loan> serviceref = null;
Object service = null;
if( ctx != null ) {
serviceref = context.getServiceReference(loan.service.Loan.class.getName());
if( serviceref != null ) {
service = ctx.getService(serviceref);
double repayment = service.calculateMonthlyPayments(...);
} else {
System.out.println("No loan service available."); // service not available
}
}
The OSGi service model makes services dynamic by allowing bundles that provide services to be uninstalled or stopped for any reason, such as administration, maintenance, or network failure. Therefore, services can be registered and unregistered asynchronously at any time. The sample could be extended into a scenario in which a version of the Java agent accepts bundles of services from multiple loan providers, such as banks, and where the computation of the monthly repayment takes into account a customer profile. The computation of the monthly repayment would be different from bank to bank and the Java agent would determine which provider is the most appropriate. These loan services could be added or removed at any time, without restarting the solution. For simplicity, the sample does not show this scenario.
The Java agent shows how to use a ServiceTracker object to track the loan service. The ServiceTracker object is used by an Activator object to track service availability concurrently. Navigate to OSGISampleJavaAgent/src/osgisamplesolution/osgisamplejavaagent/ to open Activator.java and tracker/LoanServiceTracker.java.
The OSGi service is called when an event is processed by the Java agent. Navigate to OSGISampleJavaAgent/src/osgisamplesolution/osgisamplejavaagent to open MyJavaAgent.java. A MortgageResponse event is triggered by the Java agent after the computation is finished. The event is built by the MyJavaAgent.buildResponse method and is submitted by using the com.ibm.ia.agent.EntityAgent.emit method.
The rule agent reacts to MortgageResponse events and is defined in the <InstallDir>/samples/osgi/OSGISampleRuleAgent/agent.adsc file:
'OSGISampleRuleAgent' is an agent related to a Customer ,
processing events :
- MortgageResponse , where this Customer comes from the customer of this MortgageResponse
A MortgageRequest event is triggered by the client application. Navigate to OSGISampleClient/src/test and open LoanServiceTest.java to check the emitMortgageRequest, which builds and emits the event.
The client application uses the TestDriver API. The test driver captures information for debugging and problem determination. When a test driver instance is created, it connects to a server and sends the server a solution identifier. The server sends data to the test driver instance, which collects the debug information in memory and sends it to System.out.println. You can also write the data to a file.
The test driver class provides access to EventFactory to create events and ConceptFactory to create entities. Navigate to OSGISampleClient/src/test/LoanServiceTest.java to see the implementation details.
Rebuilding the sample
After you use or modify the sample, you can rebuild it to its original state.
- In the Samples Commands view, open .
- Double-click install.service to reinstall the service.
- Double-click redeploy to undeploy and redeploy the solution.
- Double-click run.application to run the application by submitting an event.