/****************************************************************************** * Copyright (c) 2013 Timo Kinnunen. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which is available at http://www.eclipse.org/legal/epl-v10.html *****************************************************************************/ package utils.security; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.security.AccessControlException; public class SecurityManagerUtil { public static void preventSystemExit() { try { Path path = Files.createTempFile("all", ".policy"); Charset ascii = Charset.forName("ASCII"); byte[] bytes = ("grant {\n" + " permission java.security.AllPermission;\n" + "};") .getBytes(ascii); Files.write(path, bytes); System.setProperty("java.security.policy", path.toString()); SecurityManager manager = new SecurityManager() { @Override public void checkExit(int status) { super.checkExit(status); throw new AccessControlException("Calling System.exit() not allowed"); } }; System.setSecurityManager(manager); try { manager.checkExit(0); } catch(Exception expected) { return; } finally { Files.deleteIfExists(path); } } catch(IOException e) { throw new AssertionError("Cannot prevent System.exit()", e); } throw new AssertionError("Cannot prevent System.exit()"); } }