001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase;
019
020import org.junit.rules.TestRule;
021import org.junit.runner.Description;
022import org.junit.runners.model.Statement;
023
024/*
025* Test rules to prevent System.exit or Runtime.halt from exiting
026* the JVM - instead an exception is thrown.
027* */
028public class SystemExitRule implements TestRule {
029  final static SecurityManager securityManager = new TestSecurityManager();
030
031  @Override
032  public Statement apply(final Statement s, Description d) {
033    return new Statement() {
034      @Override public void evaluate() throws Throwable {
035
036        try {
037          forbidSystemExitCall();
038          s.evaluate();
039        } finally {
040          System.setSecurityManager(null);
041        }
042      }
043
044    };
045  };
046
047   // Exiting the JVM is not allowed in tests and this exception is thrown instead
048   // when it is done
049  public static class SystemExitInTestException extends SecurityException {
050  }
051
052  private static void forbidSystemExitCall() {
053    System.setSecurityManager(securityManager);
054  }
055}