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.ajax4jsf.application.DebugOutputMaker.java

/**
 * @param e/* www . j a  va 2 s  . c om*/
 * @param out
 */
public void writeExceptionStack(Throwable e, PrintWriter out) {
    out.println("<h2 class=\"a4j_debug\">Exceptions: </h2>");
    Throwable error = e;
    int errorId = 0;
    String caused = "exception ";
    while (null != error) {
        out.print("<h3 onclick=\"toggle('exception" + errorId + "')\"  class='exception a4j_debug'>");
        writeToggleMark(out, "exception" + errorId);
        out.print(caused + error.getClass().getName() + " : " + error.getMessage() + "</h3>");
        out.println("<div id='exception" + errorId
                + "' style='display: none;' class='exception'><p>Exception stack :</p><pre>");
        StackTraceElement[] stackTrace = error.getStackTrace();
        for (int i = 0; i < stackTrace.length; i++) {
            out.print("  at " + stackTrace[i].getClassName());
            out.print("." + stackTrace[i].getMethodName());
            out.println(" in " + stackTrace[i].getFileName() + " line " + stackTrace[i].getLineNumber());
        }
        // error.printStackTrace(out);
        out.println("</pre></div>");
        error = error.getCause();
        caused = "caused by ";
        errorId++;
    }
}

From source file:opensource.zeocompanion.ZeoCompanionApplication.java

public static void postToErrorLog(String method, Throwable theException, String extra, String threadName,
        boolean noAlert) {
    String eMsg = "Exception";
    if (method != null) {
        if (!method.isEmpty()) {
            eMsg = eMsg + " in " + method;
        }//from   ww  w  .j  ava2  s .  c  o m
    }
    if (threadName != null) {
        if (!threadName.isEmpty()) {
            eMsg = eMsg + " in Thread " + threadName;
        }
    }
    if (extra != null) {
        if (!extra.isEmpty()) {
            eMsg = eMsg + " (" + extra + ")";
        }
    }
    eMsg = eMsg + ": " + theException.toString();
    Log.e(_CTAG + ".postToErrorLog", eMsg);
    theException.printStackTrace();

    int r = checkExternalStorage();
    if (r != 0) {
        Log.e(_CTAG + ".postToErrorLog", "Cannot write to external storage code " + r);
        return;
    }

    FileWriter wrt = null;
    try {
        // pull the stack trace
        StackTraceElement[] traces = theException.getStackTrace();

        // ensure the directory structure is present and compose the file name
        File internalsDir = new File(mBaseExtStorageDir + File.separator + "internals");
        internalsDir.mkdirs();
        File errLogFile = new File(internalsDir + File.separator + "error.log");

        // create and append to the file
        wrt = new FileWriter(errLogFile, true); // append if file already exists
        wrt.write(new Date().toString() + "\n");
        if (threadName != null) {
            if (!threadName.isEmpty()) {
                wrt.write(" in Thread " + threadName + " ");
            }
        }
        wrt.write("AppVerName " + BuildConfig.VERSION_NAME + " AppVerCode " + BuildConfig.VERSION_CODE);
        if (mDatabaseHandler != null) {
            wrt.write(" with DBver " + mDatabaseHandler.mVersion);
        }
        wrt.write("\n");
        if (mZeoAppHandler != null) {
            if (mZeoAppHandler.mZeoApp_versionName == null) {
                wrt.write("Zeo App not installed\n");
            } else {
                wrt.write("Zeo App version " + mZeoAppHandler.mZeoApp_versionName + " build "
                        + mZeoAppHandler.mZeoApp_versionCode + "\n");
            }
        }
        wrt.write("Android Version " + android.os.Build.VERSION.RELEASE + " API "
                + android.os.Build.VERSION.SDK_INT + "\n");
        wrt.write("Platform Manf " + Build.MANUFACTURER + " Model " + Build.MODEL + "\n");
        WindowManager windowManager = (WindowManager) mApp.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        Point screenSize = new Point();
        display.getSize(screenSize);
        wrt.write("Platform Screen Orientation X,Y " + screenSize.x + "," + screenSize.y + ", Density="
                + mScreenDensity + "\n");
        if (method != null) {
            if (!method.isEmpty()) {
                wrt.write(method + "\n");
            }
        }
        if (extra != null) {
            if (!extra.isEmpty()) {
                wrt.write(extra + "\n");
            }
        }
        wrt.write(theException.toString() + "\n");
        for (StackTraceElement st : traces) {
            wrt.write(st.toString() + "\n");
        }
        wrt.write("=====\n");
        wrt.write("=====\n");
        wrt.flush();
        wrt.close();

        // force it to be shown and post an alert
        forceShowOnPC(errLogFile);
        if (!noAlert) {
            postAlert("An abort occured; details are in \'internals/error.log\'; contact the Developer");
        } // noAlert is only needed when an Alert itself was being posted to the database and it failed to post

        // must send the toast indirectly in case this is being called from a utility thread
        Message msg = new Message();
        msg.what = ZeoCompanionApplication.MESSAGE_APP_SEND_TOAST;
        msg.obj = "Abort successfully logged to \'internals/error.log\'";
        mAppHandler.sendMessage(msg);
    } catch (Exception e) {
        if (wrt != null) {
            try {
                wrt.close();
            } catch (Exception ignored) {
            }
        }
        Log.e(_CTAG + ".postToErrLog", "Cannot write to error.log: " + e.toString());
        e.printStackTrace();
    }
}

From source file:com.flexive.tests.browser.AbstractBackendBrowserTest.java

/**
 * a method every test should call if it decides to skip it self
 *//*from  w ww. ja  va 2 s .co m*/
protected void skipMe() {
    Throwable t = new Throwable();
    String s = t.getStackTrace()[1].toString();
    skipList.add(s);
}

From source file:org.schimpf.util.Logger.java

/**
 * @author <FONT style='color:#55A; font-size:12px; font-weight:bold;'>Hermann D. Schimpf</FONT>
 * @author <B>SCHIMPF</B> - <FONT style="font-style:italic;">Sistemas de Informaci&oacute;n y Gesti&oacute;n</FONT>
 * @author <B>Schimpf.NET</B>
 * @version Aug 1, 2012 6:13:53 PM// w  w w  .j ava 2  s  .c o  m
 * @param name Nombre para el logger
 * @param logFile Ruta al fichero log
 */
public Logger(final String name, final String logFile) {
    // generamos una ruta
    final Throwable caller = new Throwable();
    // clase temporal
    Class<?> tempClass = null;
    // recorremos la ruta
    for (final StackTraceElement trace : caller.getStackTrace())
        try {
            // obtenemos el nombre de la clase
            final Class<?> callerClass = Class.forName(trace.getClassName());
            // verificamos si no es la clase Logger
            if (!callerClass.equals(this.getClass()))
                // almacenamos la clase
                tempClass = callerClass;
        } catch (final ClassNotFoundException ignored) {
        }
    // almacenamos la clase
    this.clazz = tempClass;
    // almacenamos la clase
    this.name = name;
    // verificamos si es una carpeta
    if (logFile != null && new File(logFile).exists() && new File(logFile).isDirectory())
        // el fichero log lo tomamos desde el nombre
        this.logFile = new File(logFile + FileSystems.getDefault().getSeparator() + this.name + ".log");
    else
        // almacenamos el fichero log
        this.logFile = new File(logFile != null ? logFile : this.name + ".log");
    // verificamos si se especifico el fichero log
    this.enableLogFile(logFile != null);
}

From source file:es.bsc.servicess.ide.PackagingUtils.java

/** Generate the WS stubs
 * @param classpath project classpath//ww  w . ja v a2s .c  om
 * @param classes Classes which implement a JAXWS service
 * @param classFolder Folder to store package classes
 * @param myProgressMonitor Eclipse progress monitor
 * @throws CoreException
 */
private static void generateServiceStubs(String classpath, String[] classes, IFolder classFolder,
        IProgressMonitor myProgressMonitor) throws CoreException {
    String clpth = new String(classFolder.getLocation().toOSString() + ":" + classpath);
    log.debug("Classpath: " + clpth);
    if (classes != null) {
        for (String cl : classes) {
            int i = -1;
            try {

                i = WsGen.doMain(new String[] { "-verbose", "-cp", clpth, cl, "-d",
                        classFolder.getLocation().toOSString(), "-wsdl" });

            } catch (Throwable e) {
                CoreException ce = new CoreException(
                        new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
                e.printStackTrace();
                ce.setStackTrace(e.getStackTrace());
                throw (ce);
            }
            if (i != 0) {
                throw (new CoreException(
                        new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error generating service stubs")));
            }

        }
    } else {
        throw (new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Classes not found exists")));
    }

}

From source file:org.commonjava.indy.core.change.StoreEnablementManager.java

@Measure(timers = @MetricNamed(DEFAULT))
public void onStoreError(@Observes IndyStoreErrorEvent evt) {
    Logger logger = LoggerFactory.getLogger(getClass());
    StoreKey key = evt.getStoreKey();//from  w w  w  .ja va 2 s  .co  m
    Throwable error = evt.getError();
    try {
        ArtifactStore store = storeDataManager.getArtifactStore(key);
        if (store == null) {
            logger.warn("Attempt to disable missing repo! Skipping.");
            return;
        }

        store = store.copyOf();

        int disableTimeout = store.getDisableTimeout();
        if (disableTimeout <= TIMEOUT_NEVER_DISABLE) {
            logger.debug("Disable-timeout set to {}, will never disable the repo", disableTimeout);
            store.setDisabled(false);
        } else {
            store.setDisabled(true);
            final ChangeSummary changeSummary = new ChangeSummary(ChangeSummary.SYSTEM_USER,
                    String.format("Disabling %s due to error: %s\n\nStack Trace:\n  %s", key, error,
                            StringUtils.join(error.getStackTrace(), "\n  ")));

            storeDataManager.storeArtifactStore(store, changeSummary, false, true, new EventMetadata());

            logger.warn("{} has been disabled due to store-level error: {}\n Will re-enable in {} seconds.",
                    key, error, disableTimeout == TIMEOUT_USE_DEFAULT ? config.getStoreDisableTimeoutSeconds()
                            : disableTimeout);

            // TODO: How is it this doesn't duplicate the event handler method onStoreUpdate()...we're updating the store just above here.
            setReEnablementTimeout(key);
        }
    } catch (IndyDataException e) {
        logger.error(String.format("Failed to disable %s on error: %s", key, error), e);
    } catch (IndySchedulerException e) {
        logger.error(String.format("Failed to schedule re-enablement of %s for retry.", key), e);
    }
}

From source file:com.konakart.server.KKGWTServiceImpl.java

/**
 * Returns a string containing the stack trace of the exception and its cause
 * //  w w w  . j a  v a2s .  c  o  m
 * @param e
 * @return Returns a string containing the stack trace
 */
private String getExceptionMessage(Throwable e) {
    StringBuffer sb = new StringBuffer();

    if (e.getMessage() == null) {
        sb.append("null");
    } else {
        sb.append(e.getMessage());
    }
    sb.append("<br>");

    // Get the stack trace of the exception
    sb.append("Exception Stack Trace = ");
    StackTraceElement[] ste = e.getStackTrace();
    for (int i = 0; i < ste.length; i++) {
        sb.append("<br>   at ");
        sb.append(ste[i].toString());
    }

    // Get the stack trace of the exception cause
    Throwable eCause = e.getCause();
    if (eCause != null) {
        sb.append("<br><br>Exception Cause = ");
        StackTraceElement[] ste1 = eCause.getStackTrace();
        for (int i = 0; i < ste1.length; i++) {
            sb.append("<br>   at ");
            sb.append(ste1[i].toString());
        }
    }

    return sb.toString();
}

From source file:org.wisdom.error.DefaultPageErrorHandler.java

/**
 * Generates the error page./* w  ww  . ja v a2  s  .co  m*/
 *
 * @param context the context.
 * @param route   the route
 * @param e       the thrown error
 * @return the HTTP result serving the error page
 */
private Result renderInternalError(Context context, Route route, Throwable e) {
    Throwable localException;

    // If the template is not there, just wrap the exception within a JSON Object.
    if (internalerror == null) {
        return internalServerError(e);
    }

    // Manage ITE
    if (e instanceof InvocationTargetException) {
        localException = ((InvocationTargetException) e).getTargetException();
    } else {
        localException = e;
    }

    // Retrieve the cause if any.
    String cause;
    StackTraceElement[] stack;
    if (localException.getCause() != null) {
        cause = localException.getCause().getMessage();
        stack = localException.getCause().getStackTrace();
    } else {
        cause = localException.getMessage();
        stack = localException.getStackTrace();
    }

    // Retrieve the file name.
    String fileName = null;
    int line = -1;
    if (stack != null && stack.length != 0) {
        fileName = stack[0].getFileName();
        line = stack[0].getLineNumber();
    }

    // Remove iPOJO trace from the stack trace.
    List<StackTraceElement> cleaned = StackTraceUtils.cleanup(stack);

    // We are good to go !
    return internalServerError(render(internalerror, "route", route, "context", context, "exception",
            localException, "message", localException.getMessage(), "cause", cause, "file", fileName, "line",
            line, "stack", cleaned));
}

From source file:org.carewebframework.shell.plugins.PluginContainer.java

/**
 * Creates a chained exception.//from w w  w  .j av  a 2s. c o  m
 * 
 * @param action Action being performed at the time of the exception.
 * @param newException Exception just thrown.
 * @param previousException Previous exception (may be null).
 * @return Top level exception in chain.
 */
private PluginLifecycleEventException createChainedException(final String action, final Throwable newException,
        final PluginLifecycleEventException previousException) {
    String msg = action + " event generated an error.";
    log.error(msg, newException);
    PluginLifecycleEventException wrapper = new PluginLifecycleEventException(Executions.getCurrent(), msg,
            previousException == null ? newException : previousException);
    wrapper.setStackTrace(newException.getStackTrace());
    return wrapper;
}

From source file:com.mmj.app.common.component.ComponentController.java

@ExceptionHandler(Throwable.class)
public ModelAndView handleIOException(Throwable e) throws Throwable {

    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
        throw e;/*from   w  w w  . j  a v  a  2 s .  com*/
    }

    if (request == null && response == null) {
        throw e;
    }

    if (request == null && response != null) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
        pw.println("{\"code\":-1,\"message\":\",?!\",\"data\":\"\"}");
        pw.flush();
        pw.close();
    }

    ModelAndView mav = new ModelAndView();
    if (InvokeTypeTools.isAjax(request)) {
        return createJsonMav(",?!", ResultCode.ERROR, e.getMessage());
    }

    mav.addObject("exception", e.getCause() == null ? StringUtils.EMPTY : e.getCause().toString());
    mav.addObject("msg", e.getMessage());
    mav.addObject("stackTrace", e.getStackTrace().toString());
    if (request.getRequestURI() != null) {
        mav.addObject("url", request.getRequestURI().toString());
    }
    mav.getModel().put(CustomVelocityLayoutView.USE_LAYOUT, "false");
    mav.setViewName("error");
    return mav;
}