001    /*
002     * Created on Dec 21, 2009
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005     * in compliance with the License. You may obtain a copy of the License at
006     *
007     * http://www.apache.org/licenses/LICENSE-2.0
008     *
009     * Unless required by applicable law or agreed to in writing, software distributed under the License
010     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011     * or implied. See the License for the specific language governing permissions and limitations under
012     * the License.
013     *
014     * Copyright @2009-2010 the original author or authors.
015     */
016    package org.fest.swing.security;
017    
018    /**
019     * Understands installing/uninstalling a <code>{@link NoExitSecurityManager}</code>.
020     *
021     * @author Alex Ruiz
022     */
023    public class NoExitSecurityManagerInstaller {
024    
025      /**
026       * Installs a new <code>{@link NoExitSecurityManager}</code> in <code>System</code>.
027       * @return this installer.
028       */
029      public static NoExitSecurityManagerInstaller installNoExitSecurityManager() {
030        return new NoExitSecurityManagerInstaller();
031      }
032    
033      /**
034       * Installs a new <code>{@link NoExitSecurityManager}</code> in <code>System</code>.
035       * @param hook gets notified when an application tries to terminate the current JVM.
036       * @return this installer.
037       * @throws NullPointerException if the given hook is <code>null</code>.
038       */
039      public static NoExitSecurityManagerInstaller installNoExitSecurityManager(ExitCallHook hook) {
040        return new NoExitSecurityManagerInstaller(hook);
041      }
042    
043      private final SecurityManager oldManager;
044    
045      private NoExitSecurityManagerInstaller() {
046        this(new NoExitSecurityManager());
047      }
048    
049      private NoExitSecurityManagerInstaller(ExitCallHook hook) {
050        this(new NoExitSecurityManager(hook));
051      }
052    
053      private NoExitSecurityManagerInstaller(NoExitSecurityManager newManager) {
054        oldManager = System.getSecurityManager();
055        System.setSecurityManager(newManager);
056      }
057    
058      /**
059       * Uninstalls the <code>{@link NoExitSecurityManager}</code> installed by
060       * <code>{@link #installNoExitSecurityManager()}</code>, restoring the original <code>{@link SecurityManager}</code>.
061       */
062      public void uninstall() {
063        System.setSecurityManager(oldManager);
064      }
065    }