SecurityManagerPolicyEnforcer implements PolicyEnforcer { @Override public void applyPolicy(ServletContext cx) { synchronized(MUTEX) { if (startupCount > 0) { startupCount += 1; return; } SecurityManagerPolicy fakePolicy = new SecurityManagerPolicy(); try { fakePolicy.parsePolicy(new StringReader("{\"<null>\":{\"java.io.FilePermission\":{\"/tmp/foo/bar\":{\"read\":{}}}}}")); } catch (IOException e) { throw new RuntimeException(e); } ProtectionDomain fakeProtectionDomain = java.lang.String.class.getProtectionDomain(); FilePermission fakePermission = new FilePermission("/tmp/foo/bar", "read"); boolean t = new DynamicJavaPolicy(null, fakePolicy, policyConfig).implies(fakeProtectionDomain, fakePermission); if (!t) { throw new IllegalStateException("Dummy implies request should have returned true."); } java.security.Policy parentPolicy = java.security.Policy.getPolicy(); if (parentPolicy != null && parentPolicy.getClass().getName().equals(DynamicJavaPolicy.class.getName())) { throw new IllegalStateException("Having multiple PIE jars in a single container is unsupported. Move PIE from your application WARs to your container's common lib directory."); } startupCount += 1; dynamicJavaPolicy = new DynamicJavaPolicy(parentPolicy, policy, policyConfig); dynamicJavaPolicy.refresh(); java.security.Policy.setPolicy(dynamicJavaPolicy); if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } } }  @Override void init(PieConfig pieConfig); @Override PolicyConfig getPolicyConfig(); @Override Policy getPolicy(); @Override void applyPolicy(ServletContext cx); @Override void shutdown();  }
@Test public void testApplyPolicy() { assertNull(System.getSecurityManager()); System.setSecurityManager(new StubSecurityManager()); try { SecurityManagerPolicyEnforcer policyEnforcer = new SecurityManagerPolicyEnforcer(); policyEnforcer.init(new PieConfig()); ServletContext servletContext = createStrictMock(ServletContext.class); replay(servletContext); policyEnforcer.applyPolicy(servletContext); verify(servletContext); assertNotNull(java.security.Policy.getPolicy()); assertEquals(java.security.Policy.getPolicy().getClass(), DynamicJavaPolicy.class); policyEnforcer.shutdown(); } finally { java.security.Policy.setPolicy(null); System.setSecurityManager(null); } }