KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > Print


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.enterprise.util;
24
25 import java.util.StringTokenizer JavaDoc;
26 import java.io.ByteArrayOutputStream JavaDoc;
27 import java.io.File JavaDoc;
28 import java.io.PrintStream JavaDoc;
29 import java.io.FileOutputStream JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.StringWriter JavaDoc;
32 import java.io.Writer JavaDoc;
33 import java.io.PrintWriter JavaDoc;
34
35 /*
36 ** Printing/Debug Utilities
37 **
38 ** This Module contains replacements for various types of print statements used for
39 ** debugging purposes.
40 ** Example:
41 ** Replace this
42 ** System.out.println("test message");
43 ** With this
44 ** Print.println("test message");
45 ** or
46 ** Print.dprintln("test message");
47 ** The advantage of using Print.println is that the message ("test message") can be
48 ** pre-pended with the actual location of the print statement itself. For instance,
49 ** Issuing a call to 'Print.dprintln("hello world")' may print a console message
50 ** similar to the following:
51 ** [MyCustomClass.doSomething:291] hello world
52 ** This indicates that the 'Print.dprintln' is located in the method 'doSomething'
53 ** in the class 'MyCustomClass' at source file line number 291. This will help
54 ** show the precise location of various debug message print statements that should
55 ** be removed prior to FCS. (Note: the package is remove from the class before
56 ** printing the stack frame to avoid creating a print line which is excessively long)
57 **
58 ** Difference between 'println' and 'dprintln':
59 ** Each 'printXXX' method in this module has a corresponding 'dprintXXX' method.
60 ** The 'dprintXXX' methods will only print their specified message if the System
61 ** property "ri.debugMode" is true. Additionally, 'dprintXXX' methods will always
62 ** prepend the location (stackframe) of the 'Print.dprintXXX' call.
63 ** The 'printXXX' methods always print their specified message to the console.
64 ** However, the default is to _not_ include the location (stackframe) of the print
65 ** statement unless the System property "ri.print.showStackFrame" is true. The
66 ** location of all print statements can then be exposed by setting this system
67 ** property to true.
68 **
69 ** Replacements:
70 ** Old method New Method
71 ** System.out.println("hello") => Print.println("hello")
72 ** <Throwable>.printStackTrace() => Print.printStackTrace("Error", <Throwable>)
73 ** Thread.dumpStack() => Print.printStackTrace("Stack Trace");
74 ** if (debug) System.out.println("x") => Print.dprintln("x"); // not optimized
75 ** if (debug) System.out.println("x") => if (debug) Print.println("x");
76 **
77 ** To turn on debug mode (to allow 'dprintXXX' to print), include system property:
78 ** -Dri.debugMode=true
79 **
80 ** To turn have 'printXXX' methods print the stack frame location, include system property:
81 ** -Dri.print.showStackFrame=true
82 **
83 ** -----------------------------------------------------------------------------
84 ** @author Martin D. Flynn
85 */

86
87 public class Print
88 {
89
90     /* -------------------------------------------------------------------------
91     */

92
93     /* System property keys */
94     public static final String JavaDoc SYSTEM_DEBUG_MODE = "ri.debugMode";
95     public static final String JavaDoc SYSTEM_STACK_FRAME = "ri.print.showStackFrame";
96
97     /* Throwable instance used to obtain stack information */
98     private static Throwable JavaDoc stackTrace = null;
99
100     /* by default the source file name is not printed in the location */
101     private static boolean showStackFrameSource = false;
102
103     /* -------------------------------------------------------------------------
104     */

105
106     /* Set the debug mode
107     ** @param specified debug state
108     */

109     public static void setDebugMode(boolean state)
110     {
111     System.setProperty(SYSTEM_DEBUG_MODE, String.valueOf(state));
112     }
113
114     /* Return the current debug mode state
115     ** @return debug state
116     */

117     public static boolean isDebugMode()
118     {
119     return Boolean.getBoolean(SYSTEM_DEBUG_MODE);
120     }
121
122     /* -------------------------------------------------------------------------
123     */

124
125     /* Set the state to force prepending the stack frame to 'print' statements
126     ** @param specified printStackFrame state
127     */

128     public static void setPrintStackFrame(boolean state)
129     {
130     System.setProperty(SYSTEM_STACK_FRAME, String.valueOf(state));
131     }
132
133     /* return the current state of including the stack frame in 'print' statements
134     ** @return printStackFrame state
135     */

136     public static boolean printStackFrame()
137     {
138     return Boolean.getBoolean(SYSTEM_STACK_FRAME);
139     }
140
141     /* -------------------------------------------------------------------------
142     */

143
144     /* Set the state to include the module source file rather than the normal stack frame
145     ** @param specified showStackFrameSource state
146     */

147     public static void setShowStackFrameSource(boolean flag)
148     {
149     showStackFrameSource = flag;
150     }
151
152     /* -------------------------------------------------------------------------
153     */

154
155     /* Return the specified StackTraceElement
156     ** @return the @see java.lang.StackTraceElement for the specified stack frame
157     ** @param the specified stack frame to retrieve.
158     */

159     public static StackTraceElement JavaDoc getStackFrame(int frameNum)
160     {
161     if (stackTrace == null) { stackTrace = new Throwable JavaDoc(); }
162     stackTrace.fillInStackTrace();
163     return stackTrace.getStackTrace()[frameNum + 1];
164     }
165
166     /* Return the String form of the current StackTraceElement
167     ** @return the @see java.lang.String version of the specified stack frame
168     ** @param the specified stack frame to retrieve.
169     */

170     public static String JavaDoc getStackFrameString(int frameNum)
171     {
172     return getStackFrameString(frameNum + 1, showStackFrameSource);
173     }
174
175     /* Return the String form of the current StackTraceElement
176     ** @return the @see java.lang.String version of the specified stack frame
177     ** @param the StackTraceElement to convert to a string.
178     */

179     public static String JavaDoc getStackFrameString(StackTraceElement JavaDoc stackFrame)
180     {
181     return getStackFrameString(stackFrame, showStackFrameSource);
182     }
183
184     /* Return the String form of the current StackTraceElement
185     ** @return the @see java.lang.String version of the specified stack frame
186     ** @param the specified stack frame to retrieve.
187     ** @param indicator whether the String should include the module source file name
188     */

189     public static String JavaDoc getStackFrameString(int frameNum, boolean showSrc)
190     {
191     return getStackFrameString(getStackFrame(frameNum + 1), showSrc);
192     }
193
194     /* Return the String form of the current StackTraceElement
195     ** @return the @see java.lang.String version of the specified stack frame
196     ** @param the StackTraceElement to convert to a string.
197     ** @param indicator whether the String should include the module source file name
198     */

199     public static String JavaDoc getStackFrameString(StackTraceElement JavaDoc stackFrame, boolean showSrc)
200     {
201     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
202     if (showSrc) {
203         String JavaDoc s = stackFrame.getFileName();
204         if (s != null) {
205         int p = s.lastIndexOf(File.separator);
206             sb.append((p >= 0)? s.substring(p + 1) : s);
207         } else {
208             String JavaDoc c = stackFrame.getClassName();
209             int p = c.lastIndexOf(".");
210             sb.append("<").append((p >= 0)? c.substring(p + 1) : c).append(">");
211         }
212     } else {
213         String JavaDoc c = stackFrame.getClassName();
214         int p = c.lastIndexOf(".");
215         sb.append((p >= 0)? c.substring(p + 1) : c);
216     }
217     sb.append(".").append(stackFrame.getMethodName());
218     if (stackFrame.getLineNumber() >= 0) {
219         sb.append(":").append(stackFrame.getLineNumber());
220     }
221     return sb.toString();
222     }
223
224     /* -------------------------------------------------------------------------
225     */

226
227     /* Internal print statement
228     ** @param output @see java.io.PrintStream
229     ** @param the stack frame location of the real 'print' statement.
230     ** @param the message to print.
231     */

232     protected static void _println(PrintStream JavaDoc out, int frameNum, String JavaDoc msg)
233     {
234     String JavaDoc m = (frameNum >= 0)? "[" + getStackFrameString(frameNum + 1) + "] " + msg : msg;
235     print(out, m + "\n");
236     }
237
238     /* -------------------------------------------------------------------------
239     */

240
241     /* Print message to specified PrintStream (default to System.out)
242     ** Does not include a linefeed at the end of the message.
243     ** @param output @see java.io.PrintStream
244     ** @param the message to print.
245     */

246     public static void print(PrintStream JavaDoc out, String JavaDoc msg)
247     {
248     ((out != null)? out : System.out).print(msg);
249     }
250
251     /* Print message to specified PrintStream (default to System.out)
252     ** Prints message only if debugMode system property is true.
253     ** Does not include a linefeed at the end of the message.
254     ** @param output @see java.io.PrintStream
255     ** @param the message to print.
256     */

257     public static void dprint(PrintStream JavaDoc out, String JavaDoc msg)
258     {
259     if (isDebugMode()) {
260         print(out, msg);
261     }
262     }
263
264     /* Print message to specified System.out
265     ** Does not include a linefeed at the end of the message.
266     ** @param the message to print.
267     */

268     public static void print(String JavaDoc msg)
269     {
270     print(null, msg);
271     }
272
273     /* Print message to specified System.out
274     ** Prints message only if debugMode system property is true.
275     ** Does not include a linefeed at the end of the message.
276     ** @param the message to print.
277     */

278     public static void dprint(String JavaDoc msg)
279     {
280     if (isDebugMode()) {
281         print(null, msg);
282     }
283     }
284
285     /* Print message to specified PrintStream (default to System.out)
286     ** StackFrame information is included if the specified frame is >= 0, or if
287     ** the showStackFrame system property is true. To force the stack frame info to
288     ** print, set the frameNum to '0' [eg.' Print.println(null, 0, "This location");']
289     ** Message is terminated with a linefeed
290     ** @param output @see java.io.PrintStream
291     ** @param the stack frame location of the real 'print' statement.
292     ** @param the message to print.
293     */

294     public static void println(PrintStream JavaDoc out, int frameNum, String JavaDoc msg)
295     {
296     int f = (frameNum >= 0)? (frameNum + 1) : (printStackFrame()? Math.abs(frameNum) : -1);
297     _println(out, f, msg);
298     }
299
300     /* Print message to specified PrintStream (default to System.out)
301     ** Prints message only if debugMode system property is true.
302     ** StackFrame information is included.
303     ** Message is terminated with a linefeed
304     ** @param output @see java.io.PrintStream
305     ** @param the stack frame location of the real 'print' statement.
306     ** @param the message to print.
307     */

308     public static void dprintln(PrintStream JavaDoc out, int frameNum, String JavaDoc msg)
309     {
310     if (isDebugMode()) {
311         int f = (frameNum >= 0)? (frameNum + 1) : Math.abs(frameNum);
312         _println(out, f, msg);
313     }
314     }
315
316     /* Print message to System.out
317     ** StackFrame information is included if the specified frame is >= 0, or if
318     ** the showStackFrame system property is true. To force the stack frame info to
319     ** print, set the frameNum to '0' [eg.' Print.println(0, "This location");']
320     ** Message is terminated with a linefeed
321     ** @param the stack frame location of the real 'print' statement.
322     ** @param the message to print.
323     */

324     public static void println(int frameNum, String JavaDoc msg)
325     {
326     int f = (frameNum >= 0)? (frameNum + 1) : (printStackFrame()? Math.abs(frameNum) : -1);
327     _println(null, f, msg);
328     }
329
330     /* Print message to System.out
331     ** Prints message only if debugMode system property is true.
332     ** StackFrame information is included.
333     ** Message is terminated with a linefeed
334     ** @param the stack frame location of the real 'print' statement.
335     ** @param the message to print.
336     */

337     public static void dprintln(int frameNum, String JavaDoc msg)
338     {
339     if (isDebugMode()) {
340         int f = (frameNum >= 0)? (frameNum + 1) : Math.abs(frameNum);
341         _println(null, f, msg);
342     }
343     }
344
345     /* Print message to specified PrintStream (default to System.out)
346     ** StackFrame information is included if the showStackFrame system property is true.
347     ** Message is terminated with a linefeed
348     ** @param output @see java.io.PrintStream
349     ** @param the message to print.
350     */

351     public static void println(PrintStream JavaDoc out, String JavaDoc msg)
352     {
353     _println(out, (printStackFrame()? 1 : -1), msg);
354     }
355
356     /* Print message to specified PrintStream (default to System.out)
357     ** Prints message only if debugMode system property is true.
358     ** StackFrame information is included.
359     ** Message is terminated with a linefeed
360     ** @param output @see java.io.PrintStream
361     ** @param the message to print.
362     */

363     public static void dprintln(PrintStream JavaDoc out, String JavaDoc msg)
364     {
365     if (isDebugMode()) {
366         _println(out, 1, msg);
367     }
368     }
369
370     /* Print message to System.out
371     ** StackFrame information is included if the showStackFrame system property is true.
372     ** Message is terminated with a linefeed
373     ** @param the message to print.
374     */

375     public static void println(String JavaDoc msg)
376     {
377     _println(null, (printStackFrame()? 1 : -1), msg);
378     }
379
380     /* Print message to System.out
381     ** Prints message only if debugMode system property is true.
382     ** StackFrame information is included.
383     ** Message is terminated with a linefeed
384     ** @param the message to print.
385     */

386     public static void dprintln(String JavaDoc msg)
387     {
388     if (isDebugMode()) {
389         _println(null, 1, msg);
390     }
391     }
392
393     /* -------------------------------------------------------------------------
394     */

395
396     private static PrintStream JavaDoc printStackTrace_Stream = null;
397     private static File JavaDoc printStackTrace_LogFile = null;
398
399     /* Set default output file for logging stack traces (logging defaults to System.out)
400     ** @param the output file to log stack traces
401     */

402     public static void setStackTraceLogFile(File JavaDoc logFile)
403     {
404
405     /* close old log file */
406     if (printStackTrace_Stream != null) {
407         printStackTrace_Stream.close();
408         printStackTrace_Stream = null;
409         printStackTrace_LogFile = null;
410     }
411
412     /* open new log file */
413     if ((logFile != null) && logFile.isAbsolute()) {
414         try {
415             printStackTrace_Stream = new PrintStream JavaDoc(new FileOutputStream JavaDoc(logFile), true);
416         printStackTrace_LogFile = logFile;
417         } catch (IOException JavaDoc ioe) {
418         Print.println(0, "Unable to open StackTrace log file: " + logFile);
419         }
420     }
421
422     }
423
424     /* Format and print stack trace information
425     ** @param output @see java.io.PrintStream
426     ** @param the stack frame location of the real 'print' statement.
427     ** @param the title of the stack trace.
428     ** @param the message to print.
429     ** @param the Throwable containing the stack trace to print.
430     */

431     private static void _printStackTrace(PrintStream JavaDoc out, int frame, String JavaDoc title, String JavaDoc msg, Throwable JavaDoc excp)
432     {
433
434     /* header vars */
435     final String JavaDoc _dash = "----------------------------------------"; // 40
436
final String JavaDoc dashLine = _dash + _dash + "\n"; // 80
437
final String JavaDoc _ttl = " " + title + " ";
438     final String JavaDoc errTitle = dashLine.substring(0, 16) + _ttl + dashLine.substring(16 + _ttl.length());
439
440     /* default PrintStream */
441     if (out == null) {
442         out = System.out;
443     }
444
445     /* header */
446     Print.print(out, "\n");
447     Print.print(out, dashLine + errTitle);
448     Print.print(out, "[" + Print.getStackFrameString(frame + 1) + "]\n");
449     if ((msg != null) && !msg.equals("")) { Print.print(out, msg + "\n"); }
450
451     /* stack trace */
452     if (excp != null) {
453         Print.print(out, excp.toString() + "\n");
454         Print.print(out, dashLine);
455         excp.printStackTrace(out);
456     } else {
457         Print.print(out, dashLine);
458         Print.print(out, "Stack Trace:\n");
459         Throwable JavaDoc t = new Throwable JavaDoc();
460         t.fillInStackTrace();
461         ByteArrayOutputStream JavaDoc bos = new ByteArrayOutputStream JavaDoc();
462         PrintStream JavaDoc ps = new PrintStream JavaDoc(bos);
463         t.printStackTrace(ps);
464         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(bos.toString(), "\n");
465         st.nextToken(); // "java.lang.Throwable"
466
for (int i = 0; i < frame + 1; i++) { st.nextToken(); } // discard superfluous stack frames
467
for (;st.hasMoreTokens();) { Print.println(out, st.nextToken()); }
468     }
469
470     /* final dashed line */
471     Print.print(out, dashLine);
472     Print.print(out, "\n");
473
474     }
475
476     /* Print stack trace information to specified PrintStream.
477     ** @param output @see java.io.PrintStream
478     ** @param the stack frame location of the real 'print' statement.
479     ** @param the title of the stack trace.
480     ** @param the message to print.
481     ** @param the Throwable containing the stack trace to print.
482     */

483     public static void printStackTrace(PrintStream JavaDoc out, int frame, String JavaDoc title, String JavaDoc msg, Throwable JavaDoc excp)
484     {
485     if (out == null) { out = printStackTrace_Stream; }
486     if ((out != null) && (out != System.out) && (out != System.err)) {
487         Print.print("\n");
488         if (excp != null) {
489             String JavaDoc m = ((msg != null) && !msg.equals(""))? (msg + " - ") : "";
490         Print.println(null, frame + 1, "Error: " + m + excp + "");
491         StackTraceElement JavaDoc ste[] = excp.getStackTrace();
492         if (ste.length > 0) {
493                 Print.print(" ==> at " + getStackFrameString(ste[0]) + "\n");
494         }
495         } else {
496             Print.println(null, frame + 1, msg);
497         }
498         if (printStackTrace_LogFile != null) {
499             Print.print("(Stack trace logged to '" + printStackTrace_LogFile + "')\n");
500         }
501         Print.print("\n");
502     }
503     _printStackTrace(out, frame + 1, title, msg, excp);
504     }
505
506     /* Print stack trace information to specified PrintStream.
507     ** Prints stack trace only if debugMode system property is true.
508     ** @param output @see java.io.PrintStream
509     ** @param the stack frame location of the real 'print' statement.
510     ** @param the title of the stack trace.
511     ** @param the message to print.
512     ** @param the Throwable containing the stack trace to print.
513     */

514     public static void dprintStackTrace(PrintStream JavaDoc out, int frame, String JavaDoc title, String JavaDoc msg, Throwable JavaDoc excp)
515     {
516     if (isDebugMode()) {
517         if (out == null) { out = printStackTrace_Stream; }
518         if ((out != null) && (out != System.out) && (out != System.err)) {
519             String JavaDoc m = (excp != null)? (msg + " (" + excp + ")") : msg;
520             Print.println(null, frame + 1, "{log} " + m);
521         }
522         _printStackTrace(out, frame + 1, title, msg, excp);
523     }
524     }
525
526     /* Print stack trace information to default PrintStream.
527     ** @param the title of the stack trace.
528     ** @param the message to print.
529     ** @param the Throwable containing the stack trace to print.
530     */

531     public static void printStackTrace(String JavaDoc title, String JavaDoc msg, Throwable JavaDoc excp)
532     {
533     printStackTrace(null, 1, title, msg, excp);
534     }
535
536     /* Print stack trace information to default PrintStream.
537     ** Prints stack trace only if debugMode system property is true.
538     ** @param the title of the stack trace.
539     ** @param the message to print.
540     ** @param the Throwable containing the stack trace to print.
541     */

542     public static void dprintStackTrace(String JavaDoc title, String JavaDoc msg, Throwable JavaDoc excp)
543     {
544     if (isDebugMode()) {
545         dprintStackTrace(null, 1, title, msg, excp);
546     }
547     }
548
549     /* Print stack trace information to default PrintStream.
550     ** Use this method instead of '<Throwable>.printStackTrace'
551     ** @param the message to print.
552     ** @param the Throwable containing the stack trace to print.
553     */

554     public static void printStackTrace(String JavaDoc msg, Throwable JavaDoc excp)
555     {
556     String JavaDoc title = (excp != null)? "Exception" : "StackTrace";
557     printStackTrace(null, 1, title, msg, excp);
558     }
559
560     /* Print stack trace information to default PrintStream.
561     ** Prints stack trace only if debugMode system property is true.
562     ** Use this method instead of '<Throwable>.printStackTrace'
563     ** @param the message to print.
564     ** @param the Throwable containing the stack trace to print.
565     */

566     public static void dprintStackTrace(String JavaDoc msg, Throwable JavaDoc excp)
567     {
568     if (isDebugMode()) {
569         String JavaDoc title = (excp != null)? "(DEBUG) Exception" : "(DEBUG) StackTrace";
570         dprintStackTrace(null, 1, title, msg, excp);
571     }
572     }
573
574     /* Print stack trace information to default PrintStream.
575     ** Use this method instead of 'Thread.dumpStack'
576     ** @param the message to print.
577     */

578     public static void printStackTrace(String JavaDoc msg)
579     {
580     printStackTrace(null, 1, "StackTrace", msg, null);
581     }
582
583     /* Print stack trace information to default PrintStream.
584     ** Prints stack trace only if debugMode system property is true.
585     ** Use this method instead of 'Thread.dumpStack'
586     ** @param the message to print.
587     */

588     public static void dprintStackTrace(String JavaDoc msg)
589     {
590     if (isDebugMode()) {
591         dprintStackTrace(null, 1, "(DEBUG) StackTrace", msg, null);
592     }
593     }
594
595     /* Print stack trace information to default PrintStream.
596     ** Allows specifying frame
597     ** @param the stack frame to print.
598     ** @param the message to print.
599     */

600     public static void printStackTrace(int frame, String JavaDoc msg)
601     {
602     printStackTrace(null, frame + 1, "StackTrace", msg, null);
603     }
604
605     /* Print stack trace information to default PrintStream.
606     ** Prints stack trace only if debugMode system property is true.
607     ** Allows specifying frame
608     ** @param the stack frame to print.
609     ** @param the message to print.
610     */

611     public static void dprintStackTrace(int frame, String JavaDoc msg)
612     {
613     if (isDebugMode()) {
614         dprintStackTrace(null, frame + 1, "(DEBUG) StackTrace", msg, null);
615     }
616     }
617
618     public static String JavaDoc printStackTraceToString()
619     {
620         Throwable JavaDoc t = new Throwable JavaDoc("printStackTraceToString");
621         t.fillInStackTrace();
622
623         StringWriter JavaDoc stringWriter = new StringWriter JavaDoc();
624         PrintWriter JavaDoc printWriter = new PrintWriter JavaDoc(stringWriter);
625         t.printStackTrace(printWriter);
626         String JavaDoc stackTrace = stringWriter.toString();
627
628         printWriter.close();
629
630         return stackTrace;
631     }
632 }
633
Popular Tags