I'm trying to run a maven OSGi bundle project, but I get:
Exception in thread "main" java.lang.NullPointerException: Specified service reference cannot be null.
at System.out.println(framework.getBundleContext().getService(reference));
below in initialize()
.
I can't seem to get it right. I'm new to OSGi. Please help me get the project to run. Thank you all in advance.
This is the way I embed my OSGi Framework, then try to start the service:
private void initialize() throws BundleException, URISyntaxException {
Map<String, String> map = new HashMap<String, String>();
// make sure the cache is cleaned
map.put(Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
map.put("ds.showtrace", "true");
map.put("ds.showerrors", "true");
FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
Framework framework = frameworkFactory.newFramework(map);
System.out.println("Starting OSGi Framework");
framework.init();
framework.start();
loadScrBundle(framework);
framework.getBundleContext().installBundle("file:" + "D:/core-1.0.jar").start();
ServiceReference<?> reference = framework.getBundleContext()
.getServiceReference(HelloWorldService.class.getName());
System.out.println(framework.getBundleContext().getService(reference));
for (Bundle bundle : framework.getBundleContext().getBundles()) {
System.out.println("Bundle: " + bundle.getSymbolicName());
if (bundle.getRegisteredServices() != null) {
for (ServiceReference<?> serviceReference : bundle.getRegisteredServices())
System.out.println("\tRegistered service: " + serviceReference);
}
}
}
This is how I export the rev.core.api
service package:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.name}</Bundle-SymbolicName>
<Export-Package>rev.core.api</Export-Package>
<Bundle-Activator>rev.core.impl.Activator</Bundle-Activator>
<Bundle-Vendor>Rev CAIT</Bundle-Vendor>
</instructions>
</configuration>
</plugin>
</plugins>
</build>