01: package abbot.util;
02:
03: import java.security.Permission;
04: import java.util.*;
05:
06: import abbot.NoExitSecurityManager;
07:
08: /** Provides a method for terminating threads over which you otherwise have no
09: * control. Usually works.<p>
10: * NOTE: Still needs some work; if main script editor exits from the event
11: * dispatch thread, an exception is thrown and the exit aborted. Perhaps
12: * ignore event dispatch threads?
13: */
14:
15: public abstract class ThreadTerminatingSecurityManager extends
16: NoExitSecurityManager {
17:
18: public class ThreadTerminatedException extends SecurityException {
19: }
20:
21: private Map terminatedGroups = new WeakHashMap();
22:
23: private boolean isTerminated(Thread t) {
24: Iterator iter = terminatedGroups.keySet().iterator();
25: while (iter.hasNext()) {
26: ThreadGroup group = (ThreadGroup) iter.next();
27: ThreadGroup this Group = t.getThreadGroup();
28: if (this Group != null && group.parentOf(this Group)) {
29: return true;
30: }
31: }
32: return false;
33: }
34:
35: /** Ensure ThreadTermination exceptions are thrown for any thread in the
36: * given group when any such thread causes the security manager to be
37: * invoked.
38: */
39: public void terminateThreads(ThreadGroup group) {
40: if (group == null)
41: throw new NullPointerException(
42: "Thread group must not be null");
43: terminatedGroups.put(group, Boolean.TRUE);
44: // maybe do an interrupt/notify; but be careful b/c you might block
45: // trying to sycnhronize on the thread
46: if (group.activeCount() == 0) {
47: try {
48: group.destroy();
49: } catch (IllegalThreadStateException e) {
50: }
51: }
52: }
53:
54: /** Throw ThreadTerminated for any thread marked for termination. */
55: public void checkPermission(Permission perm, Object context) {
56: if (isTerminated(Thread.currentThread()))
57: throw new ThreadTerminatedException();
58: super .checkPermission(perm, context);
59: }
60:
61: /** Throw ThreadTerminated for any thread marked for termination. */
62: public void checkPermission(Permission perm) {
63: if (isTerminated(Thread.currentThread()))
64: throw new ThreadTerminatedException();
65: super.checkPermission(perm);
66: }
67: }
|