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:StackTraceHelper.java

/**
 * Removes the AspectWerkz specific elements from the stack trace.
 *
 * @param exception the Throwable to modify the stack trace on
 * @param className the name of the fake origin class of the exception
 *//* ww w  .  j a v a 2 s  .co  m*/
public static void hideFrameworkSpecificStackTrace(final Throwable exception, final String className) {
    if (exception == null) {
        throw new IllegalArgumentException("exception can not be null");
    }
    if (className == null) {
        throw new IllegalArgumentException("class name can not be null");
    }
    final List newStackTraceList = new ArrayList();
    final StackTraceElement[] stackTrace = exception.getStackTrace();
    int i;
    for (i = 1; i < stackTrace.length; i++) {
        if (stackTrace[i].getClassName().equals(className)) {
            break;
        }
    }
    for (int j = i; j < stackTrace.length; j++) {
        newStackTraceList.add(stackTrace[j]);
    }
    final StackTraceElement[] newStackTrace = new StackTraceElement[newStackTraceList.size()];
    int k = 0;
    for (Iterator it = newStackTraceList.iterator(); it.hasNext(); k++) {
        final StackTraceElement element = (StackTraceElement) it.next();
        newStackTrace[k] = element;
    }
    exception.setStackTrace(newStackTrace);
}

From source file:at.wada811.dayscounter.CrashExceptionHandler.java

/**
 * ?//from w  w  w.j  av a2  s  . co  m
 *
 * @param throwable
 *
 * @return
 *
 * @throws JSONException
 */
public static JSONObject getExceptionInfo(Throwable throwable) throws JSONException {
    JSONObject json = new JSONObject();
    json.put("name", throwable.getClass().getName());
    json.put("message", throwable.getMessage());
    if (throwable.getStackTrace() != null) {
        // ExceptionStacktrace
        JSONArray exceptionStacktrace = new JSONArray();
        for (StackTraceElement element : throwable.getStackTrace()) {
            exceptionStacktrace.put("at " + LogUtils.getMetaInfo(element));
        }
        json.put("ExceptionStacktrace", exceptionStacktrace);
    }
    if (throwable.getCause() != null) {
        json.put("cause", throwable.getCause());
        // CausedStacktrace
        if (throwable.getCause().getStackTrace() != null) {
            JSONArray causedStacktrace = new JSONArray();
            for (StackTraceElement element : throwable.getCause().getStackTrace()) {
                causedStacktrace.put("at " + LogUtils.getMetaInfo(element));
            }
            json.put("CausedStacktrace", causedStacktrace);
        }
    }
    return json;
}

From source file:com.netscape.cmscore.util.Debug.java

/**
 * Output a debug message at the output stream sepcified in the init()
 * method. This method is very lightweight if debugging is turned off, since
 * it will return immediately. However, the caller should be aware that
 * if the argument to Debug.trace() is an object whose toString() is
 * expensive, that this toString() will still be called in any case.
 * In such a case, it is wise to wrap the Debug.trace like this:
 *
 * <pre>// w  w  w.jav  a 2s.  com
 * if (Debug.on()) {
 *     Debug.trace(&quot;obj is: &quot; + obj);
 * }
 * </pre>
 *
 * @param level the message level. If this is >= than the currently set
 *            level (set with setLevel() ), the message is printed
 * @param t the message to print
 * @param ignoreStack when walking the stack to determine the
 *            location of the method that called the trace() method,
 *            ignore any classes with this string in. Can be null
 * @param printCaller if true, (and if static mShowCaller is true)
 *            dump caller information in this format:
 *            (source-file:line) methodname():
 */
public static void trace(int level, String t, String ignoreStack, boolean printCaller) {
    String callerinfo = "";
    if (!TRACE_ON)
        return;
    if (level >= mDebugLevel) {
        if (mShowCaller && printCaller) {
            String method = "";
            String fileAndLine = "";

            try {
                Throwable tr = new Throwable();
                StackTraceElement ste[] = tr.getStackTrace();
                int i = 0;
                while ((i < ste.length) && (ste[i].getMethodName().toLowerCase().indexOf("debug") > -1)
                        || (ste[i].getMethodName().toLowerCase().indexOf("hashkey") > -1)
                        || (ste[i].getClassName().toLowerCase().indexOf("propconfigstore") > -1)
                        || (ste[i].getClassName().toLowerCase().indexOf("argblock") > -1)
                        || (ste[i].getClassName().toLowerCase().indexOf("debug") > -1)
                        || (ste[i].getMethodName().toLowerCase().indexOf("trace") > -1))
                    i++;

                if (i < ste.length) {
                    fileAndLine = ste[i].getFileName() + ":" + ste[i].getLineNumber();
                    method = ste[i].getMethodName() + "()";
                }

                callerinfo = fileAndLine + ":" + method + " ";
            } catch (Exception f) {
            }
        }

        outputTraceMessage(callerinfo + t);
    }
}

From source file:com.google.gdt.eclipse.designer.util.GwtInvocationEvaluatorInterceptor.java

/**
 * @return <code>true</code> if given {@link Throwable} is caused by GWT Mail example.
 *///from  w  w  w. j av a 2 s  . co m
private static boolean isMailExampleException(Throwable e) {
    StackTraceElement[] stackTrace = e.getStackTrace();
    StackTraceElement element = stackTrace[0];
    return "com.google.gwt.sample.mail.client.MailList".equals(element.getClassName())
            && "selectRow".equals(element.getMethodName());
}

From source file:org.openstreetmap.josm.plugins.PluginHandlerTestIT.java

private static String findFaultyPlugin(Collection<PluginInformation> plugins, Throwable root) {
    for (PluginInformation p : plugins) {
        try {//  w  ww.  j  ava  2s .  com
            ClassLoader cl = PluginHandler.getPluginClassLoader(p.getName());
            String pluginPackage = cl.loadClass(p.className).getPackage().getName();
            for (StackTraceElement e : root.getStackTrace()) {
                try {
                    String stackPackage = cl.loadClass(e.getClassName()).getPackage().getName();
                    if (stackPackage.startsWith(pluginPackage)) {
                        return p.name;
                    }
                } catch (ClassNotFoundException ex) {
                    System.err.println(ex.getMessage());
                    continue;
                }
            }
        } catch (ClassNotFoundException ex) {
            System.err.println(ex.getMessage());
            continue;
        }
    }
    return "<unknown>";
}

From source file:de.domjos.schooltools.helper.Helper.java

public static void printException(Context context, Throwable ex) {
    StringBuilder message = new StringBuilder(ex.getMessage() + "\n" + ex.toString());
    for (StackTraceElement element : ex.getStackTrace()) {
        message.append(element.getFileName()).append(":").append(element.getClassName()).append(":")
                .append(element.getMethodName()).append(":").append(element.getLineNumber());
    }/* ww w  .j a v  a  2  s  .c  o m*/
    Log.e("Exception", message.toString(), ex);
    Log4JHelper.getLogger(context.getPackageName()).error("Exception", ex);
    Helper.createToast(context, ex.getLocalizedMessage(), false);
}

From source file:org.sherlok.FileBased.java

/** @return a list of the paths of all resources */
public static Collection<String> allResources() throws SherlokException {
    try {/*from  w w  w.j  a  v  a 2s.c o  m*/
        List<String> resources = list();
        File dir = new File(RUTA_RESOURCES_PATH);
        validateArgument(dir.exists(), "resources directory '" + RUTA_RESOURCES_PATH
                + "' does not exist (resolves to '" + dir.getAbsolutePath() + "')");
        Iterator<File> fit = FileUtils.iterateFiles(dir, null, true);
        while (fit.hasNext()) {
            File f = fit.next();
            if (!f.getName().startsWith(".")) { // filtering hidden files
                String relativePath = Paths.get(dir.getAbsolutePath())
                        .relativize(Paths.get(f.getAbsolutePath())).toString();
                if (!relativePath.startsWith(".")) {
                    resources.add(relativePath);
                }
            }
        }
        return resources;
    } catch (Throwable e) { // you never know...
        throw new SherlokException("could not list resources").setDetails(e.getStackTrace());
    }
}

From source file:hm.binkley.util.XPropsConverter.java

@SuppressWarnings("unchecked")
private static <T, E extends Exception> Conversion<T, E> invokeValueOf(final Class<T> token)
        throws NoSuchMethodError {
    try {/*www  . jav  a  2s  .  c  o  m*/
        final Method method = token.getMethod("valueOf", String.class);
        return value -> {
            try {
                return (T) method.invoke(null, value);
            } catch (final IllegalAccessException e) {
                final IllegalAccessError x = new IllegalAccessError(e.getMessage());
                x.setStackTrace(e.getStackTrace());
                throw x;
            } catch (final InvocationTargetException e) {
                final Throwable root = getRootCause(e);
                final RuntimeException x = new RuntimeException(root);
                x.setStackTrace(root.getStackTrace());
                throw x;
            }
        };
    } catch (final NoSuchMethodException ignored) {
        return null;
    }
}

From source file:hm.binkley.util.XPropsConverter.java

@SuppressWarnings("unchecked")
private static <T, E extends Exception> Conversion<T, E> invokeOf(final Class<T> token)
        throws NoSuchMethodError {
    try {//w w w  . j  av  a2 s . co m
        final Method method = token.getMethod("of", String.class);
        return value -> {
            try {
                return (T) method.invoke(null, value);
            } catch (final IllegalAccessException e) {
                final IllegalAccessError x = new IllegalAccessError(e.getMessage());
                x.setStackTrace(e.getStackTrace());
                throw x;
            } catch (final InvocationTargetException e) {
                final Throwable root = getRootCause(e);
                final RuntimeException x = new RuntimeException(root);
                x.setStackTrace(root.getStackTrace());
                throw x;
            }
        };
    } catch (final NoSuchMethodException ignored) {
        return null;
    }
}

From source file:org.evosuite.regression.RegressionExceptionHelper.java

/**
 * Get signature based on the root cause from the stack trace
 * (uses: location of the error triggering line from CUT)
 * @param CUT the class to expect the exception to be thrown from
 * @return signature string// w  ww.  j a  va 2s.  c o m
 */
public static String getExceptionSignature(Throwable throwable, String CUT) {
    String signature = throwable.getClass().getSimpleName();

    StackTraceElement[] stackTrace = throwable.getStackTrace();
    for (StackTraceElement el : stackTrace) {
        String elClass = el.getClassName();
        if (!Objects.equals(elClass, CUT)) {
            continue;
        }

        String method = el.getMethodName();
        int line = el.getLineNumber();
        signature += ":" + method + "-" + line;
        break;
    }
    return signature;
}