01: /*
02: * Copyright (C) 2006, 2007 XStream Committers.
03: * All rights reserved.
04: *
05: * The software in this package is published under the terms of the BSD
06: * style license a copy of which has been included with this distribution in
07: * the LICENSE.txt file.
08: *
09: * Created on 14. March 2006 by Joerg Schaible
10: */
11: package com.thoughtworks.xstream.testutil;
12:
13: import java.security.AccessControlContext;
14: import java.security.CodeSource;
15: import java.security.Permission;
16: import java.security.PermissionCollection;
17: import java.security.Permissions;
18: import java.security.ProtectionDomain;
19: import java.util.ArrayList;
20: import java.util.Collections;
21: import java.util.HashMap;
22: import java.util.Iterator;
23: import java.util.List;
24: import java.util.Map;
25:
26: /**
27: * @author Jörg Schaible
28: */
29: public class DynamicSecurityManager extends SecurityManager {
30:
31: private Map permissions = new HashMap();
32: private AccessControlContext acc = null;
33: private List failedPermissions = new ArrayList();
34:
35: public void addPermission(final CodeSource codeSource,
36: final Permission permission) {
37: PermissionCollection permissionCollection = (PermissionCollection) permissions
38: .get(codeSource);
39: if (permissionCollection == null) {
40: permissionCollection = new Permissions();
41: permissions.put(codeSource, permissionCollection);
42: }
43: permissionCollection.add(permission);
44: // updateACC();
45: }
46:
47: public void setPermissions(final CodeSource codeSource,
48: final PermissionCollection permissionCollection) {
49: if (permissionCollection == null) {
50: if (permissions.remove(codeSource) != null) {
51: // updateACC();
52: }
53: } else {
54: if (permissions.put(codeSource, permissionCollection) != null) {
55: // updateACC();
56: }
57: }
58: }
59:
60: private void updateACC() {
61: if (permissions.size() == 0) {
62: acc = null;
63: } else {
64: final ProtectionDomain[] domains = new ProtectionDomain[permissions
65: .size()];
66: int i = 0;
67: for (final Iterator iter = permissions.keySet().iterator(); iter
68: .hasNext();) {
69: final CodeSource codeSource = (CodeSource) iter.next();
70: final PermissionCollection permissionCollection = (PermissionCollection) permissions
71: .get(codeSource);
72: domains[i++] = new ProtectionDomain(codeSource,
73: permissionCollection);
74: }
75: acc = new AccessControlContext(domains);
76: }
77: }
78:
79: public void setReadOnly() {
80: updateACC();
81: }
82:
83: public void checkPermission(Permission perm) {
84: if (acc != null) {
85: try {
86: checkPermission(perm, acc);
87: } catch (final SecurityException e) {
88: failedPermissions.add(perm);
89: throw e;
90: }
91: }
92: }
93:
94: public List getFailedPermissions() {
95: return Collections.unmodifiableList(failedPermissions);
96: }
97: }
|