name.didier.david.test4j.utils.ExitCaptor Maven / Gradle / Ivy
package name.didier.david.test4j.utils;
/**
* Capture all exit calls. Usage:
*
*
* ExitCaptor captor = new ExitCaptor();
* try {
* captor.startCapturing();
* doSomeExiting();
* } catch (NoExitException e) {
* doSomethingWithStatus(e.getStatus());
* } catch (Exception e) {
* propagate(e);
* } finally {
* captor.stopCapturing();
* }
*
*
* @author ddidier
*/
public class ExitCaptor {
/** The backup {@link SecurityManager}. */
private SecurityManager oldSecurityManager;
/** The capturing {@link SecurityManager}. */
private SecurityManager newSecurityManager;
/** Default constructor. */
public ExitCaptor() {
super();
}
/**
* Start to capture exit calls. The security manager is reassigned so do not forget to restore the previous state
* with {@link #stopCapturing()}. Use a {@code finally} block!
*
* @throws IllegalStateException if already capturing exit calls.
*/
public void startCapturing() {
if (isCapturing()) {
throw new IllegalStateException("Already capturing exit calls");
}
oldSecurityManager = System.getSecurityManager();
newSecurityManager = new NoExitSecurityManager();
System.setSecurityManager(newSecurityManager);
}
/**
* Stop to capture exit calls. The previous security manager is restored. Should be used in a {@code finally} block!
*
* @throws IllegalStateException if not capturing exit calls.
*/
public void stopCapturing() {
if (!isCapturing()) {
throw new IllegalStateException("Not capturing exit calls");
}
System.setSecurityManager(oldSecurityManager);
reset();
}
/**
* @return true
if capturing exit calls, false
otherwise.
*/
public boolean isCapturing() {
return newSecurityManager != null;
}
/**
* Reset the capturing state of exit calls.
*/
private void reset() {
oldSecurityManager = null;
newSecurityManager = null;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy