Sergio
Sergio

Reputation: 8670

Querying jar entries in an Eclipse plugin

In my OSGi bundle (an eclipse plugin) I can query class entries at certain paths using something like:

bundle.findEntries("<class_directory>/<package_name_as_url>/", "*.class", true)

For example, if my classes are in the bin directory in my bundle, and I want to find all classes in the package mypackage, then I could write the path as the string "/bin/mypackage/", producing this:

bundle.findEntries("/bin/mypackage/", "*.class", true)

However, I have not managed to do the same when the classes are packaged in a jar inside my bundle. For example, if the jar is myJar.jar inside the folder 'lib', how I could query all the classes in it? I tried with these alternatives without any success:

bundle.findEntries("/lib/myJar.jar!/", "*.class", true)
bundle.findEntries("/lib/myJar.jar/", "*.class", true)

If using strings for writing the paths will not work for resources inside JARs, then how I could query the entries in my bundle that are children of a given resource URL, instead of using a plain string like "/bin/mypackage/" or "/lib/myJar.jar!/" as shown in the examples above? (such URL points to the JAR I need to query).

I know I can use:

JarFile jarFile = (JarFile) resolvedURL.getContent();

and then

jarFile.entries()

to get the entries in a Jar, but I am not happy with this solution since: 1) I would like to find a generic way to ask for bundle resources independently if they are in a JAR or not (not funny polluting the code with if conditions). 2) With that solution I cannot automatically filter the resources using a pattern, like "*.class".

Thanks in advance for any help or feedback!

UPDATE:

Apparently there is not a simple/efficient way to do this (!) - though I would love to be wrong about that -. I found here a discussion about how to convert a URL in an IPath:

http://www.eclipse.org/forums/index.php/mv/tree/88506/#page_top

(in the discussion they suggest to use Platform.asLocalURL().getPath(), that happens to be deprecated by now, I tried with the equivalent FileLocator.toFileURL().getPath instead)

Once you have the IPath you could use FileLocator.findEntries(bundle, path) to get the children entries from the URL. The problem of this approach is that apparently if the resource you need to query is inside a jar (as in my case), Eclipse will copy it somewhere in your operative system. In addition of this being a potential bottleneck for your application, FileLocator.findEntries(bundle, path) will fail given that the path is not anymore a real path of the bundle, but the path of a cached directory somewhere in the OS.

I am surprised there is not a direct way to accomplish this.

Upvotes: 1

Views: 833

Answers (1)

BJ Hargrave
BJ Hargrave

Reputation: 9384

A better solution is to use the new BundleWiring.listResources method. This method will search the bundle classpath including jar files for resources such as .class files.

Upvotes: 2

Related Questions