📄 e215. creating a custom permission.txt
字号:
This 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
Related Examples
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -