Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.jruby.runtime.backtrace;
  
  import java.util.Arrays;
  
  import org.jruby.Ruby;
 
 public class TraceType {
 
     private static final Logger LOG = LoggerFactory.getLogger("TraceType");
 
     private final Gather gather;
     private final Format format;
 
     public TraceType(Gather gatherFormat format) {
         this. = gather;
         this. = format;
     }

    
Get a normal Ruby backtrace, using the current Gather type.

Parameters:
context
nativeException
Returns:
 
     public BacktraceData getBacktrace(ThreadContext contextboolean nativeException) {
         return .getBacktraceData(contextnativeException);
     }

    
Get an integrated Ruby/Java backtrace if the current Gather type is NORMAL

Parameters:
context
javaTrace
Returns:
 
     public BacktraceData getIntegratedBacktrace(ThreadContext contextStackTraceElement[] javaTrace) {
         return .getIntegratedBacktraceData(contextjavaTrace);
     }
 
     public String printBacktrace(RubyException exceptionboolean console) {
         return .printBacktrace(exceptionconsole);
     }
 
     public static void logBacktrace(RubyStackTraceElement[] trace) {
         .info("Backtrace generated:");
         for (RubyStackTraceElement element : trace) {
             .info("  " + element.getFileName() + ":" + element.getLineNumber() + " in " + element.getMethodName());
         }
     }
     
     public static void dumpException(RubyException exception) {
         .info("Exception raised: {} : {}"exception.getMetaClass(), exception);
     }
     
     public static void dumpBacktrace(RubyException exception) {
         Ruby runtime = exception.getRuntime();
         ..println("Backtrace generated:\n" + ..printBacktrace(exceptionruntime.getPosix().isatty(.)));
     }
     
     public static void dumpCaller(RubyArray trace) {
         .info("Caller backtrace generated:\n" + trace);
     }
     
     public static void dumpCaller(RubyStackTraceElement[] trace) {
         .info("Caller backtrace generated:\n" + Arrays.toString(trace));
     }
 
     public static void dumpWarning(RubyStackTraceElement[] trace) {
         .info("Warning backtrace generated:\n" + Arrays.toString(trace));
     }
 
     public static TraceType traceTypeFor(String style) {
         if (style.equalsIgnoreCase("raw")) return new TraceType(..);
         else if (style.equalsIgnoreCase("ruby_framed")) return new TraceType(..);
         else if (style.equalsIgnoreCase("normal")) return new TraceType(..);
         // deprecated, just uses jruby format now
         else if (style.equalsIgnoreCase("rubinius")) return new TraceType(..);
         else if (style.equalsIgnoreCase("full")) return new TraceType(..);
         else if (style.equalsIgnoreCase("mri")) return new TraceType(..);
         else return new TraceType(..);
     }
     
     public enum Gather {
        
Full raw backtraces with all Java frames included.
 
        RAW {
            public BacktraceData getBacktraceData(ThreadContext contextStackTraceElement[] javaTraceboolean nativeException) {
                return new BacktraceData(
                        javaTrace,
                        new BacktraceElement[0],
                        true,
                        false,
                        false);
            }
        },

        
A backtrace with interpreted frames intact, but don't remove Java frames.
        FULL {
            public BacktraceData getBacktraceData(ThreadContext contextStackTraceElement[] javaTraceboolean nativeException) {
        return new BacktraceData(
                        javaTrace,
                        context.createBacktrace2(0, nativeException),
                        true,
                        false,
                        false);
            }
        },

        
A normal Ruby-style backtrace, but which includes any non-org.jruby frames
        INTEGRATED {
            public BacktraceData getBacktraceData(ThreadContext contextStackTraceElement[] javaTraceboolean nativeException) {
                return new BacktraceData(
                        javaTrace,
                        context.createBacktrace2(0, nativeException),
                        false,
                        false,
                        true);
            }
        },

        
Normal Ruby-style backtrace, showing only Ruby and core class methods.
        NORMAL {
            public BacktraceData getBacktraceData(ThreadContext contextStackTraceElement[] javaTraceboolean nativeException) {
                return new BacktraceData(
                        javaTrace,
                        context.createBacktrace2(0, nativeException),
                        false,
                        context.runtime.getInstanceConfig().getBacktraceMask(),
                        false);
            }
        },

        
Normal Ruby-style backtrace, showing only Ruby and core class methods.
        CALLER {
            public BacktraceData getBacktraceData(ThreadContext contextStackTraceElement[] javaTraceboolean nativeException) {
                return new BacktraceData(
                        javaTrace,
                        context.createBacktrace2(0, nativeException),
                        false,
                        true,
                        false);
            }
        };

        
Gather backtrace data for a normal Ruby trace.

Parameters:
context
nativeException
Returns:
        public BacktraceData getBacktraceData(ThreadContext contextboolean nativeException) {
            BacktraceData data = getBacktraceData(context, Thread.currentThread().getStackTrace(), nativeException);
            context.runtime.incrementBacktraceCount();
            if (.logBacktrace(data.getBacktrace(context.runtime));
            return data;
        }

        
Gather backtrace data for an integrated trace if the current gather type is "NORMAL", otherwise use the current gather type.

Parameters:
context
javaTrace
Returns:
        public BacktraceData getIntegratedBacktraceData(ThreadContext contextStackTraceElement[] javaTrace) {
            Gather useGather = this;
            if (useGather == ) {
                useGather = ;
            }
            
            BacktraceData data = useGather.getBacktraceData(contextjavaTracefalse);
            context.runtime.incrementBacktraceCount();
            if (.logBacktrace(data.getBacktrace(context.runtime));
            return data;
        }
        public abstract BacktraceData getBacktraceData(ThreadContext contextStackTraceElement[] javaTraceboolean nativeException);
    }
    
    public enum Format {
        
Formatting like C Ruby
        MRI {
            public String printBacktrace(RubyException exceptionboolean console) {
                return printBacktraceMRI(exceptionconsole);
            }
        },

        
New JRuby formatting
        JRUBY {
            public String printBacktrace(RubyException exceptionboolean console) {
                return printBacktraceJRuby(exceptionconsole);
            }
        };
        public abstract String printBacktrace(RubyException exceptionboolean console);
    }
    protected static String printBacktraceMRI(RubyException exceptionboolean console) {
        Ruby runtime = exception.getRuntime();
        ThreadContext context = runtime.getCurrentContext();
        IRubyObject backtrace = exception.callMethod(context"backtrace");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream errorStream = new PrintStream(baos);
        boolean printedPosition = false;
        if (backtrace.isNil() || !(backtrace instanceof RubyArray)) {
            if (context.getFile() != null && context.getFile().length() > 0) {
                errorStream.print(context.getFile() + ":" + context.getLine());
                printedPosition = true;
            } else {
                errorStream.print(context.getLine());
                printedPosition = true;
            }
        } else if (((RubyArraybacktrace).getLength() == 0) {
            printErrorPos(contexterrorStream);
        } else {
            IRubyObject mesg = ((RubyArraybacktrace).first();
            if (mesg.isNil()) {
                printErrorPos(contexterrorStream);
            } else {
                errorStream.print(mesg);
                printedPosition = true;
            }
        }
        RubyClass type = exception.getMetaClass();
        String info = exception.toString();
        if (printedPositionerrorStream.print(": ");
        if (type == runtime.getRuntimeError() && (info == null || info.length() == 0)) {
            errorStream.print(": unhandled exception\n");
        } else {
            String path = type.getName();
            if (info.length() == 0) {
                errorStream.print(path + '\n');
            } else {
                if (path.startsWith("#")) {
                    path = null;
                }
                String tail = null;
                if (info.indexOf("\n") != -1) {
                    tail = info.substring(info.indexOf("\n") + 1);
                    info = info.substring(0, info.indexOf("\n"));
                }
                errorStream.print(info);
                if (path != null) {
                    errorStream.print(" (" + path + ")\n");
                }
                if (tail != null) {
                    errorStream.print(tail + '\n');
                }
            }
        }
        exception.printBacktrace(errorStream, 1);
        return new String(baos.toByteArray());
    }
    private static final String FIRST_COLOR = "\033[0;31m";
    private static final String KERNEL_COLOR = "\033[0;36m";
    private static final String EVAL_COLOR = "\033[0;33m";
    private static final String CLEAR_COLOR = "\033[0m";
    protected static String printBacktraceJRuby(RubyException exceptionboolean console) {
        Ruby runtime = exception.getRuntime();
        RubyStackTraceElement[] frames = exception.getBacktraceElements();
        if (frames == nullframes = new RubyStackTraceElement[0];
        // find longest method name
        int longestMethod = 0;
        for (RubyStackTraceElement frame : frames) {
            longestMethod = Math.max(longestMethodframe.getMethodName().length());
        }
        StringBuilder buffer = new StringBuilder();
        // exception line
        String message = exception.message(runtime.getCurrentContext()).toString();
        if (exception.getMetaClass() == runtime.getRuntimeError() && message.length() == 0) {
            message = "No current exception";
        }
        buffer
                .append(exception.getMetaClass().getName())
                .append(": ")
                .append(message)
                .append('\n');
        
        boolean color = console && runtime.getInstanceConfig().getBacktraceColor();
        // backtrace lines
        boolean first = true;
        for (RubyStackTraceElement frame : frames) {
            if (color) {
                if (first) {
                    buffer.append();
                } else if (frame.isBinding() || frame.getFileName().equals("(eval)")) {
                    buffer.append();
                } else if (frame.getFileName().indexOf(".java") != -1) {
                    buffer.append();
                }
                first = false;
            }
            
            buffer.append("  ");
            // method name
            String methodName = frame.getMethodName();
            for (int j = 0; j < longestMethod - methodName.length(); j++) {
                buffer.append(' ');
            }
            buffer
                    .append(methodName)
                    .append(" at ")
                    .append(frame.getFileName())
                    .append(':')
                    .append(frame.getLineNumber());
            
            if (color) {
                buffer.append();
            }
            
            buffer
                    .append('\n');
        }
        return buffer.toString();
    }
    public static IRubyObject generateMRIBacktrace(Ruby runtimeRubyStackTraceElement[] trace) {
        if (trace == null) {
            return runtime.getNil();
        }
        RubyArray traceArray = RubyArray.newArray(runtime);
        for (int i = 0; i < trace.lengthi++) {
            RubyStackTraceElement element = trace[i];
            RubyString str = RubyString.newString(runtimeelement.getFileName() + ":" + element.getLineNumber() + ":in `" + element.getMethodName() + "'");
            traceArray.append(str);
        }
        return traceArray;
    }
    private static void printErrorPos(ThreadContext contextPrintStream errorStream) {
        if (context.getFile() != null && context.getFile().length() > 0) {
            if (context.getFrameName() != null) {
                errorStream.print(context.getFile() + ":" + context.getLine());
                errorStream.print(":in '" + context.getFrameName() + '\'');
            } else if (context.getLine() != 0) {
                errorStream.print(context.getFile() + ":" + context.getLine());
            } else {
                errorStream.print(context.getFile());
            }
        }
    }
New to GrepCode? Check out our FAQ X