Agostino
Agostino

Reputation: 2811

Set java.security.policy property to a cross-platform file path

I'm trying to set the system property "java.security.policy" programmatically.

It works, as long as the path to the security policy file has no spaces.

File myFileReference = new File("C:\folder_name\security.policy")
System.setProperty("java.security.policy", myFileReference.getAbsolutePath());
System.setSecurityManager(new RMISecurityManager());

If there are spaces int the file path, they get escaped with a %20, like this "C:\folder%20name\security.policy".

The code above executes fine, but then all security checks fail. I assume setProperty doesn't really find the file.

On Windows, writing the file name without that escaping for spaces works.

System.setProperty("java.security.policy", "C:\\some folder\\wideopen.policy");

So, the problem seems to be that %20 space escaping. I could replace it using a regex, but maybe that would make it work just on Windows, and fails somewhere else. Also, I don't want to hard-code the file path like that.

I looked at the Java doc for a File function that returns a "System.setProperty" compatible path name that works on any platform. I also tried things like toURI().toString(), to no avail.

Is there an elegant way to get a working file path String from a File reference in 1 line of code?

EDIT: This was simplified code, I construct the file like this

URL policyURL = Class.class.getResource("/sub local folder/wideopen.policy");
new File(policyURL.getFile())

I needed a relative path, so I used that little getResource trick, which happens to return an URL, with the nasty %20 escapings. I can use an URLDecoder to strip them away now that I know what the problem is. But is there a less error prone way?

Upvotes: 0

Views: 1385

Answers (1)

Agostino
Agostino

Reputation: 2811

I solved using the URLDecoder class. Here is a complete example of what I was trying to do, and the solution that made it work.

//here is the trick
URL policyFileURL = Class.class.getResource("/server/model/easy.policy");
String policyFilePath = "";
try {
    policyFilePath = URLDecoder.decode(policyFileURL.getFile(), "UTF-8");
}
catch (UnsupportedEncodingException e) {}

//here what I wanted to do (now it works)
server.activate(port, new File(policyFilePath));

Upvotes: 1

Related Questions