Listing All Permissions Granted to Classes Loaded from a URL or Directory

A code base is a location of class or jar files specified using a URL. The URL may refer to a location on the Internet or a directory in the local file system. This example retrieves all the permissions granted to a particular class that's been loaded from a code base.

These permissions are effective only if the security manager is installed (see Enabling the Security Manager). However, with a security manager installed, a class will require permission to execute Class.getProtectionDomain() and Policy.getPermissions().

URL codebase = null; try { // Get permissions for a URL codebase = new URL("http://java.sun.com/"); // Get permissions for a directory codebase = new File("c:\\users\\almanac\\").toURL(); codebase = new File(System.getProperty("user.home")).toURL(); } catch (MalformedURLException e) { } catch (IOException e) { } // Construct a code source with the code base CodeSource cs = new CodeSource(codebase, null); // Get all granted permissions PermissionCollection pcoll = Policy.getPolicy().getPermissions(cs); // View each permission in the permission collection Enumeration enum = pcoll.elements(); for (; enum.hasMoreElements(); ) { Permission p = (Permission)enum.nextElement(); }
When the above example is run with the following policy file:
grant codeBase "http://java.sun.com/-" { // Give permission to read all system properties permission java.util.PropertyPermission "*", "read"; }; grant codeBase "file:${user.home}/*" { // Give permission to execute all runtime-protected methods permission java.lang.RuntimePermission "*"; };
using the following command:
java -Djava.security.policy==my.policy MyApp
the permissions for the URL http://java.sun.com/ are:
(java.util.PropertyPermission * read)
and the permissions for the directory System.getProperty("user.home") are:
(java.lang.RuntimePermission *)

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.