Example usage for java.lang Throwable getStackTrace

List of usage examples for java.lang Throwable getStackTrace

Introduction

In this page you can find the example usage for java.lang Throwable getStackTrace.

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Provides programmatic access to the stack trace information printed by #printStackTrace() .

Usage

From source file:org.mrgeo.gce.MrGeoFormatFactorySpi.java

private static void logstack(Throwable t) {
    StackTraceElement[] st = t.getStackTrace();
    boolean first = true;
    for (StackTraceElement tr : st) {
        if (first) {
            first = false;/*from ww  w.  ja  v  a2s  . c o m*/
            log.severe(tr.toString());
        } else {
            log.severe("  " + tr.toString());
        }
    }
}

From source file:Main.java

public static String getExceptionStackTrace(Throwable throwable) {
    if (null == throwable) {
        return "null";
    }//from   ww w  . ja v a2  s .com
    StringBuilder sb = new StringBuilder(throwable.getMessage()).append("\n");
    StackTraceElement[] elements = throwable.getStackTrace();
    for (StackTraceElement element : elements) {
        sb.append(element.toString()).append("\r\n");
    }
    return sb.toString();
}

From source file:org.b3log.latke.util.Callstacks.java

/**
 * Prints call stack with the specified logging level.
 * /* w w  w. java  2s  .c om*/
 * @param logLevel the specified logging level
 * @param carePackages the specified packages to print, for example, ["org.b3log.latke", "org.b3log.solo"], {@code null} to care 
 * nothing
 * @param exceptablePackages the specified packages to skip, for example, ["com.sun", "java.io", "org.b3log.solo.filter"], 
 * {@code null} to skip nothing
 */
public static void printCallstack(final Level logLevel, final String[] carePackages,
        final String[] exceptablePackages) {
    if (null == logLevel) {
        LOGGER.log(Level.WARNING, "Requires parameter[logLevel]");

        return;
    }

    final Throwable throwable = new Throwable();
    final StackTraceElement[] stackElements = throwable.getStackTrace();

    if (null == stackElements) {
        LOGGER.log(Level.WARNING, "Empty call stack");

        return;
    }

    final StringBuilder stackBuilder = new StringBuilder("CallStack [").append(Strings.LINE_SEPARATOR);

    for (int i = 1; i < stackElements.length; i++) {
        final String stackElemClassName = stackElements[i].getClassName();

        if (!StringUtils.startsWithAny(stackElemClassName, carePackages)
                || StringUtils.startsWithAny(stackElemClassName, exceptablePackages)) {
            continue;
        }

        stackBuilder.append("    [className=").append(stackElements[i].getClassName()).append(", fileName=")
                .append(stackElements[i].getFileName()).append(", lineNumber=")
                .append(stackElements[i].getLineNumber()).append(", methodName=")
                .append(stackElements[i].getMethodName()).append(']').append(Strings.LINE_SEPARATOR);
    }
    stackBuilder.append("], fullDepth=[").append(stackElements.length).append("]");

    LOGGER.log(logLevel, stackBuilder.toString());
}

From source file:org.apache.tajo.exception.ErrorUtil.java

public static Stacktrace.StackTrace convertStacktrace(Throwable t) {
    Stacktrace.StackTrace.Builder builder = Stacktrace.StackTrace.newBuilder();
    if (t != null) {
        for (StackTraceElement element : t.getStackTrace()) {
            builder.addElement(Stacktrace.StackTrace.Element.newBuilder()
                    .setFilename(element.getFileName() == null ? "(Unknown Source)" : element.getFileName())
                    .setFunction(element.getClassName() + "::" + element.getMethodName())
                    .setLine(element.getLineNumber()));
        }/*from  w w  w .  ja  v  a  2s  .  c o  m*/
    }
    return builder.build();
}

From source file:com.norbl.util.StringUtil.java

private static String throwableToString(Throwable x, String prefix) {

    String mess = x.toString() + "\n\n" + stackTraceToString(x.getStackTrace());
    Throwable cause = x.getCause();
    if (cause != null) {
        mess += "\nCAUSE:\n" + throwableToString(cause, prefix + "    ");
    }//from  w ww. j av a 2  s.  c  o  m
    return (mess);
}

From source file:com.ms.commons.utilities.CoreUtilities.java

/**
 * //from  w  w w. j a  v  a  2s . co  m
 * 
 * @param e
 * @return
 */
public static String getExceptionText(Throwable e) {
    if (e != null) {
        StringBuilder sb = new StringBuilder();
        StackTraceElement[] st = e.getStackTrace();
        for (StackTraceElement s : st) {
            sb.append(s.toString()).append("\r\n");
        }
        return sb.toString();
    }
    return null;
}

From source file:Main.java

public static String getCompressedStackTrace(Throwable t, int startAt, int limit) {
    try {/*from w  w  w.ja  v  a  2  s.c  om*/
        StackTraceElement[] stackTrace = t.getStackTrace();
        if (stackTrace.length < startAt) {
            return "";
        }
        StringBuilder sb = new StringBuilder("");
        for (int i = startAt; i < stackTrace.length && i < startAt + limit; i++) {
            StackTraceElement element = stackTrace[i];
            String classname = element.getClassName();
            String cnShort;
            boolean showLineNumber = true;
            boolean breakAfter = false;
            if (classname.startsWith("com.vuze.android.remote.")) {
                cnShort = classname.substring(24, classname.length());
            } else if (classname.equals("android.os.Handler")) {
                showLineNumber = false;
                cnShort = "Handler";
            } else if (classname.equals("android.os.Looper")) {
                showLineNumber = false;
                cnShort = "Looper";
                breakAfter = true;
            } else if (classname.length() < 9) { // include full if something like aa.ab.ac
                cnShort = classname;
            } else {
                int len = classname.length();
                int start = len > 14 ? len - 14 : 0;

                int pos = classname.indexOf('.', start);
                if (pos >= 0) {
                    start = pos + 1;
                }
                cnShort = classname.substring(start, len);
            }
            if (i != startAt) {
                sb.append(", ");
            }
            sb.append(cnShort);
            sb.append('.');
            sb.append(element.getMethodName());
            if (showLineNumber) {
                sb.append(':');
                sb.append(element.getLineNumber());
            }
            if (breakAfter) {
                break;
            }
        }
        Throwable cause = t.getCause();
        if (cause != null) {
            sb.append("\n|Cause ");
            sb.append(cause.getClass().getSimpleName());
            if (cause instanceof Resources.NotFoundException || cause instanceof RuntimeException) {
                sb.append(' ');
                sb.append(cause.getMessage());
            }
            sb.append(' ');
            sb.append(getCompressedStackTrace(cause, 0, 9));
        }
        return sb.toString();
    } catch (Throwable derp) {
        return "derp " + derp.getClass().getSimpleName();
    }
}

From source file:com.mobage.air.extension.Dispatcher.java

public static void dispatch(FREContext context, String eventType, Throwable exception) {
    try {/*from   w w  w.ja  v  a 2 s  . c om*/
        JSONArray args = new JSONArray();

        args.put(exception.toString());
        for (StackTraceElement item : exception.getStackTrace()) {
            args.put(item.toString());
        }

        context.dispatchStatusEventAsync(eventType, args.toString());
    } catch (Exception e) {
        Log.wtf(TAG, e);
    }
}

From source file:com.basho.riak.presto.cli.CLI.java

public static void dummy_main(String args[]) throws UnknownHostException, InterruptedException {
    System.out.println("foobar");

    RiakNode node = new RiakNode.Builder().withRemoteAddress("127.0.0.1").withRemotePort(8087)
            .withMaxConnections(10).withConnectionTimeout(CONNECTION_TIMEOUT_MIL).build();
    List<RiakNode> nodes = Arrays.asList(node);
    RiakCluster cluster = RiakCluster.builder(nodes).build();

    long startTime = System.currentTimeMillis();

    //Bucket bucket = client.createBucket("demo_bucket").execute();
    for (int i = 0; i < DATA_COUNT; i++) {
        try {//from   w  w  w  . j av  a  2  s.  c om
            if (i % 1000 == 0) {
                log("storing key #" + i);
            }
            ;
            BinaryValue key = BinaryValue.create("demo_key_" + i);
            RiakObject obj = new RiakObject();
            obj.setContentType("application/json");
            obj.setValue(BinaryValue.create("{'name':'bob','age':18}"));
            StoreOperation op = new StoreOperation.Builder(new Location(NAMESPACE, key)).withContent(obj)
                    .withReturnBody(false).build();
            cluster.execute(op);

            op.await();
            if (!op.isSuccess()) {
                throw op.cause();
            }

        } catch (Throwable t) {
            log(t.getMessage());
            log(t.getStackTrace().toString());
        }

    }

    long duration = System.currentTimeMillis() - startTime;

    log("ops per sec: " + DATA_COUNT / (duration / 1000.0));
}

From source file:org.kuali.kfs.module.tem.web.JstlFunctions.java

/**
 * Get the stack trace from a <code>{@link Throwable}</code> and create a log message from it for tracing purposes
 *
 * @param thrownObj/*w w w  .  j av a  2s .  co m*/
 * @return String log message
 */
private static String buildTraceMessage(Throwable thrownObj) {
    StackTraceElement stackTraceElement = thrownObj.getStackTrace()[0];
    return new StringBuilder(stackTraceElement.getClassName()).append("#")
            .append(stackTraceElement.getMethodName()).append(":").append(stackTraceElement.getLineNumber())
            .append(" ").append(thrownObj.getClass().getSimpleName()).append("\n")
            .append(thrownObj.getMessage()).toString();
}