Java Reference
In-Depth Information
Click here to view code image
private FileInputStream openFile(AccessControlContext context) {
if (context == null) {
throw new SecurityException("Missing AccessControlContext");
}
final FileInputStream f[] = { null };
AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
try {
f[0] = new FileInputStream("file");
} catch (FileNotFoundException fnf) {
// Forward to handler
}
return null;
}
},
// Restrict the privileges by passing the context argument
context);
return f[0];
}
private static class FileAccessControlContext {
public static final AccessControlContext INSTANCE;
static {
Permission perm = new java.io.FilePermission("file",
"read");
PermissionCollection perms = perm.newPermissionCollection();
perms.add(perm);
INSTANCE = new AccessControlContext(new ProtectionDomain[] {
new ProtectionDomain(null, perms)});
}
}
// Wrapper method
public void performActionOnFile() {
try (final FileInputStream f =
// Grant only open-for-reading privileges
openFile(FileAccessControlContext.INSTANCE)){
// Perform action
} catch (Throwable t) {
// Handle exception
Search WWH ::




Custom Search