2 * Copyright (C) 2010 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package libcore.java.security;
19 import java.security.AccessControlContext;
20 import java.security.AccessControlException;
21 import java.security.AccessController;
22 import java.security.DomainCombiner;
23 import java.security.Permission;
24 import java.security.Permissions;
25 import java.security.PrivilegedAction;
26 import java.security.ProtectionDomain;
27 import junit.framework.TestCase;
29 public final class AccessControllerTest extends TestCase {
31 public void testDoPrivilegedWithCombiner() {
32 final Permission permission = new RuntimePermission("do stuff");
33 final DomainCombiner union = new DomainCombiner() {
34 public ProtectionDomain[] combine(ProtectionDomain[] a, ProtectionDomain[] b) {
35 a = (a == null) ? new ProtectionDomain[0] : a;
36 b = (b == null) ? new ProtectionDomain[0] : b;
37 ProtectionDomain[] union = new ProtectionDomain[a.length + b.length];
38 System.arraycopy(a, 0, union, 0, a.length);
39 System.arraycopy(b, 0, union, a.length, b.length);
44 ProtectionDomain protectionDomain = new ProtectionDomain(null, new Permissions());
45 AccessControlContext accessControlContext = new AccessControlContext(
46 new AccessControlContext(new ProtectionDomain[] { protectionDomain }), union);
48 AccessController.doPrivileged(new PrivilegedAction<Void>() {
50 // in this block we lack our requested permission
51 assertSame(union, AccessController.getContext().getDomainCombiner());
52 assertPermission(false, permission);
54 AccessController.doPrivileged(new PrivilegedAction<Void>() {
56 // nest doPrivileged to get it back.
57 assertNull(AccessController.getContext().getDomainCombiner());
58 assertPermission(true, permission);
63 AccessController.doPrivilegedWithCombiner(new PrivilegedAction<Void>() {
65 // nest doPrivilegedWithCombiner() to get it back and keep the combiner.
66 assertSame(union, AccessController.getContext().getDomainCombiner());
67 assertPermission(true, permission);
74 }, accessControlContext);
77 private void assertPermission(boolean granted, Permission permission) {
79 AccessController.getContext().checkPermission(permission);
82 AccessController.getContext().checkPermission(permission);
83 fail("Had unexpected permission: " + permission);
84 } catch (AccessControlException expected) {