Java Reference
In-Depth Information
public void
printResult(
double
result) {
System.out.println("The result is: " + result);
}
}
This listing declares a class that implements the interface in listing 16.1. The details of
the implementation aren't relevant to
OSG
i, so we'll skip it.
There's no big difference between testing
OSG
i services and
POJO
s. You can reuse
the test from chapter 1 and include it in a build, as we show in part 3 of this topic. This
chapter doesn't cover unit testing alone; it covers integration testing of
OSG
i services.
Before we continue discussing the integration testing of the service that we just imple-
mented, we create a bundle to hold our service and install the service with Apache
Felix, an open source implementation of the
OSG
i R4 Service Platform.
To create the bundle we need an implementation of the
BundleActivator
inter-
face to register and unregister the service, as shown in listing 16.3.
Listing 16.3
CalculatorBundleActivator
[...]
import
org.osgi.framework.BundleActivator;
import
org.osgi.framework.BundleContext;
B
C
D
E
public class
CalculatorBundleActivator
implements
BundleActivator {
public void
start(BundleContext bundleContext)
throws
Exception {
System.out.println("Starting calculator service ...");
bundleContext.registerService(
CalculatorService.
class
.getName(),
new
CalculatorImpl(),
null
);
}
F
public void
stop(BundleContext bundleContext)
throws
Exception {
System.out.println(“Stopping calculator service ...”);
}
}
We start by importing the required classes
B
from felix.jar in the
FELIX_HOME
bin/
directory. Next, we declare our class to implement the
BundleActivator
interface
C
.
In
D
and
F
, we implement the required
start
and
stop
methods, which define how
the bundle will behave once it's started or stopped. In the
start
method, we register
the
CalculatorService
interface with the given
BundleContext
E
. By doing so we
notify the framework of our service, and our next step is to expose the interface to
other services.
Our
stop
method
F
doesn't need to do anything because Felix automatically
unregisters the service when it stops.
To expose our calculator service so that it can be used by other services, we need to
include it in a bundle: a
JAR
file containing all of our classes and the
MANIFEST
.
MF
file
shown in listing 16.4.