security
Get all permissions granted to classes loaded from a specific URL
In this example we shall show you how to get all permissions granted to classes loaded from a specific URL. To get the permissions from a specific URL one should perform the following steps:
- Create a new URL to be used as a code base.
- Initialize the URL with a String pathname, which can be either a pathname to a URL or a pathname to a directory.
- Create a CodeSource associated with the specified URL location and a set of Certificates.
- Create a PermissionCollection, by getting the permissions for the specific CodeSource, using the
getPermissions(CodeSource codesource)
API method of the installed Policy Object. - Create an enumeration of all the Permission objects, using the
elements()
API method of the PermissionCollection and return each one of the permissions to a new Permission Object, using thenextElement()
API method of the Enumeration,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Policy; import java.security.cert.Certificate; import java.util.Enumeration; public class GetGrantedPermissionsForURL { public static void main(String[] args) { URL codebase = null; try { // Get permissions for a URL (example) // codebase = new URL("http://www.javacodegeeks.com/"); // Get permissions for a directory codebase = new File(System.getProperty("user.home")).toURL(); } catch (MalformedURLException e) { } catch (IOException e) { } // Construct a code source from the code base CodeSource codeSource = new CodeSource(codebase, new Certificate[] {}); // Get all granted permissions PermissionCollection permissionCollection = Policy.getPolicy().getPermissions(codeSource); Enumeration permissions = permissionCollection.elements(); while (permissions.hasMoreElements()) { Permission permission = (Permission) permissions.nextElement(); System.out.println(permission.getName()); } } }
Example Output:
stopThread
localhost:1024-
<all permissions>
line.separator
java.vm.version
java.vm.specification.version
java.vm.specification.vendor
java.vendor.url
java.vm.name
os.name
java.vm.vendor
path.separator
java.specification.name
os.version
os.arch
java.class.version
java.version
file.separator
java.vendor
java.vm.specification.name
java.specification.version
java.specification.vendor
This was an example of how to get all permissions granted to classes loaded from a specific URL in Java.