Java security policy set from code

1.5k Views Asked by At

Using this bit of code to try and set a policy file:

ClassLoader cl= getClass().getClassLoader();
URL policyURL =cl.getResource("res/policy/new_policy.policy");
System.setProperty("java.security.policy", policyURL.toString());

And I get a java.lang.NullPointerException on the last line. The file is in my project directory in the correct path.

Question: What could cause this exception?

Answer: Running from eclipse, the path was constructed relative to the main project folder, not the project's bin folder. Considering that, moving the res folder in the bin folder solved the issue without changing any of the code above.

2

There are 2 best solutions below

4
On BEST ANSWER

If the path is in you project, add a /

cl.getResource("/res/policy/new_policy.policy")

But I would suggest you print the value of policyURL to check that you retrieve the file ok.

If you are executing in Eclipse, remember that the resources must be in a resources folder so they go to classes folder when build.

Eclipse only execute classes, and the classes live in output folder (bin).

0
On

This would happen if:

policyURL.toString()

is null, as the property values are stored in a Hashtable and the the Hashtable class checks whether the value is null in it's put method and throws a NullPointerException if it is. I would make sure that your policyUrl Object is being constructed correctly.