![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e215. Creating a Custom PermissionThis example creates a permission that controls access to pages of a book. The permission name consists of a book id, a colon, and a set of allowable pages. The set of allowable pages is specified as a comma-separated list of page ranges. For example,88:1,3-4 specifies
that pages 1, 3, and 4 are accessible in the book whose id is 88.
import java.io.*; import java.security.*; import java.util.*; public class BookPermission extends BasicPermission implements Serializable { String bookid = null; BitSet pages = new BitSet(); public BookPermission(String perm) { super(perm); String[] fields = perm.split(":"); // Get book id bookid = fields[0]; // Get page ranges and set pages String[] ranges = fields[1].split(","); for (int i=0; i<ranges.length; i++) { // Get the start and end of the range String[] range = ranges[i].split("-"); int start = Integer.parseInt(range[0]); int end = start; if (range.length > 1) { end = Integer.parseInt(range[1]); } // Set the pages in the bitset pages.set(start, end+1); } } public boolean implies(Permission permission) { BookPermission bp = (BookPermission)permission; // Check book id if (!bookid.equals(bp.bookid)) { return false; } // Clone other pages bitset BitSet pgs = (BitSet)bp.pages.clone(); // OR both bitsets pgs.or(pages); // Return true if this bitset contains all the bits in the other bitset return pages.equals(pgs); } public String getActions() { return ""; } public int hashCode() { return bookid.hashCode() ^ pages.hashCode(); } public boolean equals(Object obj) { if (!(obj instanceof BookPermission)) { return false; } BookPermission bp = (BookPermission)obj; return pages.equals(bp.pages) && bookid.equals(bp.bookid); } }Here's some examples that use BookPermission :
Permission p1 = new BookPermission("123:1-3,5,7-10"); Permission p2 = new BookPermission("123:2"); boolean b = p1.implies(p2); // false p2 = new BookPermission("123:3"); b = p1.implies(p2); // true p2 = new BookPermission("1234:3"); b = p1.implies(p2); // false p2 = new BookPermission("123:3,8-9"); b = p1.implies(p2); // true p2 = new BookPermission("123:3-5"); b = p1.implies(p2); // false
e213. Checking Read/Write Permission for a Directory e214. Determining If One Permission Implies Another e216. Controlling Access to an Object e217. Listing All Permissions Granted to a Loaded Class e218. Listing All Permissions Granted to Classes Loaded from a URL or Directory
© 2002 Addison-Wesley. |