Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape result of FileLocator.resolve(url)

The method FileLocator.resolve(url) can be used to translate an address bundleentry://something/somewhere/x.txt to a proper file URL for /mnt/foo/somewhere/x.txt.

However, which is also documented at https://bugs.eclipse.org/bugs/show_bug.cgi?id=145096, the URL is not escaped. As an example, if the Eclipse installation containing the referenced bundle is in a directory containing a space, the URL returned by FileLocator.resolve still contains the space and calling url.toURI() fails because of that.

  • How can I manually escape all necessary characters in the URL?
  • How can I get a File object based on a path relative to the current bundle?

As reference, here is the code that fails when trying to find the directory dir inside my plugin's .jar file if that file is in a directory containing a space:

    final IPath pathOfExampleProject = new Path("dir");
    final Bundle bundle = Platform.getBundle(AproveIDs.PLUGIN_ID);
    final URL url = FileLocator.find(bundle, pathOfExampleProject, null);
    final URL url2 = FileLocator.toFileURL(url);
    url2.toURI(); // Illegal character in path at index [...]
like image 872
C-Otto Avatar asked Feb 03 '13 20:02

C-Otto


2 Answers

I just found this code:

http://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/editor/tools/plugins/com.google.dart.tools.core/src/com/google/dart/tools/core/internal/model/BundledSystemLibrary.java?r=2057

The relevant lines indeed help:

// We need to use the 3-arg constructor of URI in order to properly escape file system chars.
URI resolvedUri = new URI(resolvedUrl.getProtocol(), resolvedUrl.getPath(), null);
like image 150
C-Otto Avatar answered Nov 13 '22 14:11

C-Otto


Two additional notes:

  • FileLocator.resolve indeed resolves an URL, but it does not necessarily return a file:/ URL. In the default case where your bundle is packed (in a .jar), you should use FileLocator.toFileURL, which automatically extracts the resource to a cache if needed.
  • since Eclipse 4.x now includes EMF Common API by default, you can escape the URL more simply with EMF's URI API as follows:

URI resolvedUri = URI.createFileURI(resolved.getPath());

To get the file name, call resolvedUri.toFileString();

like image 34
Matthieu Wipliez Avatar answered Nov 13 '22 12:11

Matthieu Wipliez