下面列出了怎么用java.security.Permission的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns the permission collection for the given code source.
*/
@Override
protected PermissionCollection getPermissions(CodeSource codeSource)
{
PermissionCollection perms = super.getPermissions(codeSource);
ArrayList<Permission> permissions = _permissions;
int size = permissions != null ? permissions.size() : 0;
for (int i = 0; i < size; i++) {
Permission permission = permissions.get(i);
perms.add(permission);
}
return perms;
}
/**
* @serialData "permissions" field (a Vector containing the ServicePermissions).
*/
/*
* Writes the contents of the perms field out as a Vector for
* serialization compatibility with earlier releases.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
// Don't call out.defaultWriteObject()
// Write out Vector
Vector<Permission> permissions = new Vector<>(perms.size());
synchronized (this) {
permissions.addAll(perms);
}
ObjectOutputStream.PutField pfields = out.putFields();
pfields.put("permissions", permissions);
out.writeFields();
}
/**
* Prints warning message if installed Policy is the default Policy
* implementation and globally granted permissions do not include
* AllPermission or any ExecPermissions/ExecOptionPermissions.
*/
static void checkConfiguration() {
Policy policy =
AccessController.doPrivileged(new PrivilegedAction<Policy>() {
public Policy run() {
return Policy.getPolicy();
}
});
if (!(policy instanceof PolicyFile)) {
return;
}
PermissionCollection perms = getExecPermissions();
for (Enumeration<Permission> e = perms.elements();
e.hasMoreElements();)
{
Permission p = e.nextElement();
if (p instanceof AllPermission ||
p instanceof ExecPermission ||
p instanceof ExecOptionPermission)
{
return;
}
}
System.err.println(getTextResource("rmid.exec.perms.inadequate"));
}
@Test
public void testMajorVersionFromJavaSpecificationVersion() {
final SecurityManager current = System.getSecurityManager();
try {
System.setSecurityManager(new SecurityManager() {
@Override
public void checkPropertyAccess(String key) {
if (key.equals("java.specification.version")) {
// deny
throw new SecurityException(key);
}
}
// so we can restore the security manager
@Override
public void checkPermission(Permission perm) {
}
});
assertEquals(6, PlatformDependent0.majorVersionFromJavaSpecificationVersion());
} finally {
System.setSecurityManager(current);
}
}
/**
* Check if the connector server creator can assume the identity of each
* principal in the authenticated subject, i.e. check if the connector
* server creator codebase contains a subject delegation permission for
* each principal present in the authenticated subject.
*
* @return {@code true} if the connector server creator can delegate to all
* the authenticated principals in the subject. Otherwise, {@code false}.
*/
public static synchronized boolean
checkRemoveCallerContext(Subject subject) {
try {
for (Principal p : getSubjectPrincipals(subject)) {
final String pname =
p.getClass().getName() + "." + p.getName();
final Permission sdp =
new SubjectDelegationPermission(pname);
AccessController.checkPermission(sdp);
}
} catch (SecurityException e) {
return false;
}
return true;
}
public void runTest(AccessControlContext acc, Permission perm,
boolean expectACE, int id) {
AccessController.doPrivileged(
(PrivilegedAction) () -> {
try {
AccessController.getContext().checkPermission(P1);
} catch (AccessControlException ace) {
catchACE = true;
}
if (catchACE ^ expectACE) {
throw new RuntimeException("test" + id + " failed");
}
return null;
}, acc, perm);
}
@Override
public boolean implies(Permission permission) {
if (notInit) {
init();
}
return perms.implies(permission);
}
public String toString() {
StringBuilder sb = new StringBuilder("policy: ");
Enumeration<Permission> perms = permissions.elements();
while (perms.hasMoreElements()) {
sb.append("\n").append(perms.nextElement().toString());
}
return sb.toString();
}
public void checkPermission(Permission perm) {
if (!(perm instanceof ServicePermission)) {
return;
}
ServicePermission p = (ServicePermission)perm;
permChecks = permChecks + p.getActions().toUpperCase().charAt(0);
}
public java.util.Enumeration<Permission> elements() {
if (perms == null)
init();
synchronized (perms) {
return perms.elements();
}
}
private Permission getPermission(JarFile jarFile) {
try {
URLConnection uc = getConnection(jarFile);
if (uc != null)
return uc.getPermission();
} catch (IOException ioe) {
// gulp
}
return null;
}
public static void main(String[] args) throws Exception {
toolkit = (SunToolkit) Toolkit.getDefaultToolkit();
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGui();
}
});
toolkit.realSync();
// Get screen insets
screenInsets = toolkit.getScreenInsets(frame.getGraphicsConfiguration());
if (screenInsets.bottom == 0) {
// This test is only for configurations with taskbar on the bottom
return;
}
System.setSecurityManager(new SecurityManager(){
private String allowsAlwaysOnTopPermission = SecurityConstants.AWT.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION.getName();
@Override
public void checkPermission(Permission perm) {
if (allowsAlwaysOnTopPermission.equals(perm.getName())) {
throw new SecurityException();
}
}
});
// Show popup as if from an applet
// The popup shouldn't overlap the task bar. It should be shifted up.
checkPopup();
}
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
// Don't call defaultReadObject()
// Read in serialized fields
ObjectInputStream.GetField gfields = in.readFields();
// Get the one we want
Vector<Permission> permissions =
(Vector<Permission>)gfields.get("permissions", null);
perms = new ArrayList<Permission>(permissions.size());
perms.addAll(permissions);
}
@Override
public boolean implies(Permission permission) {
if (notInit) {
init();
}
return perms.implies(permission);
}
static void testOperation(MBeanServer mbs, CustomSecurityManager sm,
ObjectName on, MBeanOperationInfo opInfo) {
System.out.println("Testing " + opInfo.getName());
Descriptor desc = opInfo.getDescriptor();
if (desc.getFieldValue("dcmd.permissionClass") == null) {
// No special permission required, execution should not trigger
// any security exception
if (invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
} else {
// Building the required permission
Permission reqPerm = createPermission(
(String)desc.getFieldValue("dcmd.permissionClass"),
(String)desc.getFieldValue("dcmd.permissionName"),
(String)desc.getFieldValue("dcmd.permissionAction"));
// Paranoid mode: check that the SecurityManager has not already
// been granted the permission
sm.denyPermission(reqPerm);
// A special permission is required for this operation,
// invoking it without the permission granted must trigger
// a security exception
if(!invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// grant the permission and re-try invoking the operation
sm.grantPermission(reqPerm);
if(invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// Clean up
sm.denyPermission(reqPerm);
}
}
static void testOperation(MBeanServer mbs, CustomSecurityManager sm,
ObjectName on, MBeanOperationInfo opInfo) {
System.out.println("Testing " + opInfo.getName());
Descriptor desc = opInfo.getDescriptor();
if (desc.getFieldValue("dcmd.permissionClass") == null) {
// No special permission required, execution should not trigger
// any security exception
if (invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
} else {
// Building the required permission
Permission reqPerm = createPermission(
(String)desc.getFieldValue("dcmd.permissionClass"),
(String)desc.getFieldValue("dcmd.permissionName"),
(String)desc.getFieldValue("dcmd.permissionAction"));
// Paranoid mode: check that the SecurityManager has not already
// been granted the permission
sm.denyPermission(reqPerm);
// A special permission is required for this operation,
// invoking it without the permission granted must trigger
// a security exception
if(!invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// grant the permission and re-try invoking the operation
sm.grantPermission(reqPerm);
if(invokeOperation(mbs, on, opInfo)) {
throw new RuntimeException("TEST FAILED");
}
// Clean up
sm.denyPermission(reqPerm);
}
}
public boolean implies(ProtectionDomain domain, Permission permission) {
if (permission instanceof JodaTimePermission) {
return false;
}
return true;
// return super.implies(domain, permission);
}
private static void checkMBeanPermission(String classname,
String member,
ObjectName objectName,
String actions)
throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
Permission perm = new MBeanPermission(classname,
member,
objectName,
actions);
sm.checkPermission(perm);
}
}
/**
* Adds a permission to the SocketPermissions. The key for the hash is
* the name in the case of wildcards, or all the IP addresses.
*
* @param permission the Permission object to add.
*
* @exception IllegalArgumentException - if the permission is not a
* SocketPermission
*
* @exception SecurityException - if this SocketPermissionCollection object
* has been marked readonly
*/
public void add(Permission permission) {
if (! (permission instanceof SocketPermission))
throw new IllegalArgumentException("invalid permission: "+
permission);
if (isReadOnly())
throw new SecurityException(
"attempt to add a Permission to a readonly PermissionCollection");
// optimization to ensure perms most likely to be tested
// show up early (4301064)
synchronized (this) {
perms.add(0, (SocketPermission)permission);
}
}
/**
* Returns an enumeration of all the DelegationPermission objects
* in the container.
*
* @return an enumeration of all the DelegationPermission objects.
*/
public Enumeration<Permission> elements() {
// Convert Iterator into Enumeration
synchronized (this) {
return Collections.enumeration(perms);
}
}
public PermissionsBuilder addAll(PermissionCollection col) {
if (col != null) {
for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
perms.add(e.nextElement());
}
}
return this;
}
public PermissionsBuilder addAll(PermissionCollection col) {
if (col != null) {
for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
perms.add(e.nextElement());
}
}
return this;
}
public PermissionsBuilder addAll(PermissionCollection col) {
if (col != null) {
for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
perms.add(e.nextElement());
}
}
return this;
}
public PermissionsBuilder addAll(PermissionCollection col) {
if (col != null) {
for (Enumeration<Permission> e = col.elements(); e.hasMoreElements(); ) {
perms.add(e.nextElement());
}
}
return this;
}
public static void main(String[]args) throws Exception {
Permission p1 = new A("foo");
Permission p2 = new B("foo");
if (p1.implies(p2) || p2.implies(p1) || p1.equals(p2)) {
throw new Exception("Test failed");
}
// make sure permissions imply and equal themselves
if (! (p1.implies(p1) && p1.equals(p1))) {
throw new Exception("Test failed");
}
}
@Override
public String toString() {
StringJoiner sj = new StringJoiner("\n", "policy: ", "");
Enumeration<Permission> perms = permissions.elements();
while (perms.hasMoreElements()) {
sj.add(perms.nextElement().toString());
}
return sj.toString();
}
/**
* Returns an enumeration of all the DelegationPermission objects
* in the container.
*
* @return an enumeration of all the DelegationPermission objects.
*/
public Enumeration<Permission> elements() {
// Convert Iterator into Enumeration
synchronized (this) {
return Collections.enumeration(perms);
}
}
/**
* Adds a permission to the SocketPermissions. The key for the hash is
* the name in the case of wildcards, or all the IP addresses.
*
* @param permission the Permission object to add.
*
* @exception IllegalArgumentException - if the permission is not a
* SocketPermission
*
* @exception SecurityException - if this SocketPermissionCollection object
* has been marked readonly
*/
public void add(Permission permission) {
if (! (permission instanceof SocketPermission))
throw new IllegalArgumentException("invalid permission: "+
permission);
if (isReadOnly())
throw new SecurityException(
"attempt to add a Permission to a readonly PermissionCollection");
// optimization to ensure perms most likely to be tested
// show up early (4301064)
synchronized (this) {
perms.add(0, (SocketPermission)permission);
}
}
/**
* Check and see if this collection of permissions implies the permissions
* expressed in "permission".
*
* @param permission the Permission object to compare
*
* @return true if "permission" is a proper subset of a permission in
* the collection, false if not.
*/
public boolean implies(Permission permission) {
if (! (permission instanceof ServicePermission))
return false;
ServicePermission np = (ServicePermission) permission;
int desired = np.getMask();
int effective = 0;
int needed = desired;
synchronized (this) {
int len = perms.size();
// need to deal with the case where the needed permission has
// more than one action and the collection has individual permissions
// that sum up to the needed.
for (int i = 0; i < len; i++) {
ServicePermission x = (ServicePermission) perms.get(i);
//System.out.println(" trying "+x);
if (((needed & x.getMask()) != 0) && x.impliesIgnoreMask(np)) {
effective |= x.getMask();
if ((effective & desired) == desired)
return true;
needed = (desired ^ effective);
}
}
}
return false;
}
private static PermissionCollection copy(PermissionCollection pc) {
// TODO, provide a copy-on-write collection?!
final Permissions pc2 = new Permissions();
for (final Enumeration<Permission> e = pc.elements(); e.hasMoreElements();) {
pc2.add(e.nextElement());
}
return pc2;
}