some util classes stolen from webfunds
[cacert-birdshack.git] / Business Logic / trunk / src / org / cacert / birdshack / util / Panic.java
1 /*
2 * Was webfunds.util.Panic, contributed.
3 */
4 package org.cacert.birdshack.util;
5
6 import org.apache.log4j.Logger;
7
8
9 /**
10 * Panic is thrown to force an unclean exit of the JVM when a fatal
11 * error occurs. This exception should not (and can not) be caught.
12 *
13 * Upon construction, Panic logs an message to Log4J at ERROR level. The
14 * message includes a stack trace (either obtained from the passed-in
15 * Throwable or generated by the Panic class itself). Panic then calls
16 * the Log4J Logger.shutdown() method and does a System.exit(1).
17 *
18 * Panic extends Error because it should not be caught. (I think it
19 * should extend Throwable but Jikes does not allow that. --JCvG)
20 *
21 * @author Jeroen C. van Gelderen (gelderen@webfunds.org)
22 * @version $Id: Panic.java,v 1.15 2005/02/02 19:45:57 iang Exp $
23 */
24 public final class Panic extends Error {
25
26 private static final Logger _logger =
27 Logger.getInstance(Panic.class.getName());
28
29 private static boolean handle = true;
30
31 /**
32 * Test classes can call this if they wish to catch
33 * Panic when they expect it to happen.
34 * This will disable the internal exit.
35 */
36 public static void disableHandling()
37 {
38 _logger.warn( "Panic.disableHandling() - this must be a test class.");
39 handle = false;
40 }
41
42
43 /** Panic with a default message. */
44 public Panic() {
45 this("unknown cause", null);
46 }
47
48
49 /** Panic with a message. A stack trace will be generated. */
50 public Panic(String msg) {
51 this(msg, null);
52 }
53
54
55 /** Panic with just a Throwable. */
56 public Panic(Throwable cause) {
57 this(cause.getMessage(), cause);
58 }
59
60
61 /** Panic with a message and the Throwable that caused the panic. */
62 public Panic(String msg, Throwable cause) {
63
64 super("PANIC: " + msg + "\nPanic from this cause:\n", cause);
65
66 if (handle)
67 {
68 if( cause != null ) {
69 _logger.error( this.getMessage(), cause );
70 } else {
71 // obtain a StackTrace and log it
72 Throwable t = new Throwable().fillInStackTrace();
73 _logger.error( this.getMessage() +
74 "\n(Stack trace generated by Panic)", t );
75 }
76
77 _logger.error("\nGoing to call System.exit(1)...");
78 Logger.shutdown();
79 System.exit(1);
80 }
81 }
82
83 /**
84 * A stopgap measure until Java 1.5.
85 * When assert becomes available, change all the lines to
86 * use the direct call.
87 */
88 public static void assert2(boolean asserted)
89 {
90 if (asserted)
91 return ;
92
93 throw new Panic("assert failed.");
94 }
95 }