Alex Rivera | Logout

How to reference an included file in OSGi bundle when performing java.io.File or FileInputStream

Asked 2010-09-28T06:45:10.493
11

I am using the aQute Bnd toolset to create an OSGi bundle and have packaged with some dependant 'resource' files. This includes *.css files and *.xsd files in a resources directory I have created.

I have included the following in the bundle.bnd file:

Include-Resource: resources/=resources/ 

and when I do a build, the generated *.jar file has the *.css and *.xsd files in the resources directory in the top directory of the jar bundle file.

However, in the actual code I am having difficulty in trying to refer to this as part of my class path:

I have tried the following:

new File("resources/example.css");

I have also tried:

URL cssFile = this.getClass().getResource("resources/example.css");
try
{
   file = new File(cssFile.toURI()));
}
catch(Exception e)
{
   e.printStackTrace();  
}

I either get a NullPointException error or a File cannot be found IOException error (depending which one I use). I get this error when running in both Eclipse Equinox in Debug Configuration mode as well as Apache Felix (which we are using for our deployment). Note I am trying to do this in Java classes outside of the BundleActivator.

Do I need to always refer to the context of the BundleActivator e.g.?

 /*
 * (non-Javadoc)
 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
 */
 @Override
 public void start(BundleContext context) throws Exception 
 {   
     /* Service to host the Bundle interface. */
     ServletContainerService service = new ServletContainerService();
     service.addServlet(new ServletContainer(new AxisServlet(), true));
     this.serverReg = context.registerService(ServletContainerService.class.getName(), service, null);

     cssFile = new File(context.getClass.getResource("resource/example.css")); 
 }

I think the above will work, but will mean I will

Edit
Report

1 Answer

9

The Bundle interface has a getEntry(java.lang.String path) method which return an Url and is documented as:

Returns a URL to the entry at the specified path in this bundle. This bundle's class loader is not used to search for the entry. Only the contents of this bundle are searched for the entry. The specified path is always relative to the root of this bundle and may begin with "/". A path value of "/" indicates the root of this bundle.

answered 2010-09-28T07:20:28.470

Your Answer