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:edu.harvard.iq.dataverse.harvest.client.HarvesterServiceBean.java

private void logException(Throwable e, Logger logger) {

    boolean cause = false;
    String fullMessage = "";
    do {/*from  w  ww  . j  a  v a2  s.  c o  m*/
        String message = e.getClass().getName() + " " + e.getMessage();
        if (cause) {
            message = "\nCaused By Exception.................... " + e.getClass().getName() + " "
                    + e.getMessage();
        }
        StackTraceElement[] ste = e.getStackTrace();
        message += "\nStackTrace: \n";
        for (int m = 0; m < ste.length; m++) {
            message += ste[m].toString() + "\n";
        }
        fullMessage += message;
        cause = true;
    } while ((e = e.getCause()) != null);
    logger.severe(fullMessage);
}

From source file:com.fluidops.iwb.api.ProviderServiceImpl.java

/**
 * Note: the history repository is only used in the fiwbcom version of the
 * method, i.e. when overriding the method in class ProviderServiceImplCom.
 * No historic data management is done at all in the fiwb version.
 * /*from  w  w w. j a v a  2  s  .  c o m*/
 * @param provider
 * @param data
 *            Externally passed data
 * @param repository
 * @param historyRepository
 */
private void load(AbstractFlexProvider provider, URI parameter, List<Statement> data, Repository repository,
        Repository historyRepository) throws Exception {
    logger.info("Starting provider with ID " + provider.providerID.stringValue());
    // fetch new data from provider
    List<Statement> newStmts = new LinkedList<Statement>();
    long start = System.currentTimeMillis();
    provider.running = true;
    try {
        if (data != null)
            newStmts = data; // data provided externally, there is no
        // need to run the provider
        else {
            if (parameter != null && provider instanceof LookupProvider) {
                ((LookupProvider) provider).gather(newStmts, parameter);
            } else
                provider.gather(newStmts);

        }

        provider.error = null;

        long now = System.currentTimeMillis();
        processProviderData(provider, newStmts, parameter, repository, historyRepository, now);
        provider.size = newStmts.size();
    } catch (Throwable t) {
        logger.error("Provider load error: ", t);
        StringBuilder error = new StringBuilder();
        error.append(t.getMessage());
        for (StackTraceElement tl : t.getStackTrace())
            error.append("\n").append(tl.toString());
        provider.error = error.toString();
    }

    // update statistics
    provider.lastUpdate = new Date();
    provider.lastDuration = System.currentTimeMillis() - start;
    provider.running = false;

    logger.info("Provider run of provider with ID " + provider.providerID + " finished");
}

From source file:com.master.metehan.filtereagle.Util.java

public static void sendCrashReport(Throwable ex, final Context context) {
    if (!isPlayStoreInstall(context))
        return;/*from ww  w  .j ava  2s.c  o  m*/
    if (!(Util.isDebuggable(context) || Util.getSelfVersionName(context).contains("beta")))
        return;

    try {
        ApplicationErrorReport report = new ApplicationErrorReport();
        report.packageName = report.processName = context.getPackageName();
        report.time = System.currentTimeMillis();
        report.type = ApplicationErrorReport.TYPE_CRASH;
        report.systemApp = false;

        ApplicationErrorReport.CrashInfo crash = new ApplicationErrorReport.CrashInfo();
        crash.exceptionClassName = ex.getClass().getSimpleName();
        crash.exceptionMessage = ex.getMessage();

        StringWriter writer = new StringWriter();
        PrintWriter printer = new PrintWriter(writer);
        ex.printStackTrace(printer);

        crash.stackTrace = writer.toString();

        StackTraceElement stack = ex.getStackTrace()[0];
        crash.throwClassName = stack.getClassName();
        crash.throwFileName = stack.getFileName();
        crash.throwLineNumber = stack.getLineNumber();
        crash.throwMethodName = stack.getMethodName();

        report.crashInfo = crash;

        final Intent bug = new Intent(Intent.ACTION_APP_ERROR);
        bug.putExtra(Intent.EXTRA_BUG_REPORT, report);
        bug.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (bug.resolveActivity(context.getPackageManager()) != null)
            context.startActivity(bug);
    } catch (Throwable exex) {
        Log.e(TAG, exex.toString() + "\n" + Log.getStackTraceString(exex));
    }
}

From source file:net.ymate.platform.log.jcl.JCLogger.java

protected void __doBuildEx(Object info, Throwable e, ILogger.LogLevel level) {
    StringBuilder _exSB = new StringBuilder(
            DateTimeUtils.formatTime(System.currentTimeMillis(), DateTimeUtils.YYYY_MM_DD_HH_MM_SS_SSS))
                    .append(level.getDispName()).append('[').append(Thread.currentThread().getId()).append(':')
                    .append(__doMakeCallerInfo()).append(']').append(' ')
                    .append(info == null ? StringUtils.EMPTY : StringUtils.trimToEmpty(info.toString()));
    if (e != null) {
        StringBuilder _stackSB = new StringBuilder(e.getClass().getName()).append(": ")
                .append(StringUtils.EMPTY).append(StringUtils.trimToEmpty(e.getMessage())).append("\n");
        StackTraceElement[] _stacks = e.getStackTrace();
        for (StackTraceElement _stack : _stacks) {
            _stackSB.append("\tat ").append(_stack).append("\n");
        }/*from  w w w.  jav  a 2s  .  co  m*/
        __ex(_stackSB, e.getCause());
        _exSB.append("- ").append(_stackSB);
    }
    __logger.log(Level.toLevel(level.getName(), Level.ALL), _exSB.toString());
    //
    if (__allowOutputConsole) {
        System.out.println(_exSB.toString());
    }
}

From source file:com.bstek.dorado.view.resolver.ViewServiceResolver.java

/**
 * @param jsonBuilder/*  w ww  .j a  v  a  2s. co  m*/
 * @param e
 */
protected void outputException(JsonBuilder jsonBuilder, Throwable throwable) {
    while (throwable.getCause() != null) {
        throwable = throwable.getCause();
    }

    String message = throwable.getMessage();
    if (message == null) {
        message = throwable.getClass().getSimpleName();
    }

    try {
        jsonBuilder.object(); // TODO: ?JSONBuilder?
        jsonBuilder.key("exceptionType").value("JavaException").key("message").value(message).key("stackTrace");
        jsonBuilder.array();
        StackTraceElement[] stackTrace = throwable.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            jsonBuilder.value(stackTraceElement.getClassName() + '.' + stackTraceElement.getMethodName() + '('
                    + stackTraceElement.getFileName() + ':' + stackTraceElement.getLineNumber() + ')');
        }
        jsonBuilder.endArray();
        jsonBuilder.endObject();
    } catch (Exception e) {
        // ignore e!!!
        throwable.printStackTrace();
    }
}

From source file:ome.services.util.ServiceHandler.java

private Throwable wrapUnknown(Throwable t, String msg) {

    // If this is an Error, then we want to log a message
    // since these are most likely: AssertionError (bad assumptions),
    // LinkageError (bad jar versions), ThreadDeath, or one of the
    // VirtualMachineErrors: OutOfMemory, InternalError, StackOverflowError,
    // UnknownError
    if (t instanceof Error) {
        log.error("java.lang.Error: " + msg, t);
    }// w  w  w.  j a v a2 s  .co  m

    // Wrap all other exceptions in InternalException
    InternalException re = new InternalException(msg);
    re.setStackTrace(t.getStackTrace());
    printException("Unknown exception thrown.", t);
    return re;
}

From source file:org.gflogger.log4j.Log4jEntry.java

@Override
public GFLogEntry append(Throwable e) {
    if (e != null) {
        try {// w  ww.j a v a  2s  .c  o m
            append(e.getClass().getName());
            String message = e.getLocalizedMessage();
            if (message != null) {
                append(": ").append(message);
            }
            append('\n');
            final StackTraceElement[] trace = e.getStackTrace();
            for (int i = 0; i < trace.length; i++) {
                append("\tat ").append(trace[i].getClassName()).append('.').append(trace[i].getMethodName());
                append('(');
                if (trace[i].isNativeMethod()) {
                    append("native");
                } else {
                    final String fileName = trace[i].getFileName();
                    final int lineNumber = trace[i].getLineNumber();
                    if (fileName != null) {
                        append(fileName);
                        if (lineNumber >= 0) {
                            append(':').append(lineNumber);
                        }

                        final Class clazz = loadClass(trace[i].getClassName());
                        if (clazz != null) {
                            append('[').append(getCodeLocation(clazz));
                            final String implVersion = getImplementationVersion(clazz);
                            if (implVersion != null) {
                                append(':').append(implVersion);
                            }
                            append(']');
                        }

                    } else {
                        append("unknown");
                    }
                }
                append(')').append('\n');
            }
        } catch (Throwable t) {
            //
            t.printStackTrace();
        }
    }
    return this;
}

From source file:com.emc.vipr.sync.ViPRSync.java

protected String summarize(Throwable t) {
    Throwable cause = getCause(t);
    StringBuilder summary = new StringBuilder();
    summary.append(MessageFormat.format("[{0}] {1}", t, cause));
    StackTraceElement[] elements = cause.getStackTrace();
    for (int i = 0; i < 15 && i < elements.length; i++) {
        summary.append("\n    at ").append(elements[i]);
    }//from ww w.jav a2s.  c o  m
    return summary.toString();
}

From source file:edu.harvard.iq.dataverse.api.imports.ImportServiceBean.java

@TransactionAttribute(REQUIRES_NEW)
public JsonObjectBuilder handleFile(DataverseRequest dataverseRequest, Dataverse owner, File file,
        ImportType importType, PrintWriter validationLog, PrintWriter cleanupLog)
        throws ImportException, IOException {

    System.out.println("handling file: " + file.getAbsolutePath());
    String ddiXMLToParse;/*from  w  w  w. j  a v a 2s .  c o m*/
    try {
        ddiXMLToParse = new String(Files.readAllBytes(file.toPath()));
        JsonObjectBuilder status = doImport(dataverseRequest, owner, ddiXMLToParse,
                file.getParentFile().getName() + "/" + file.getName(), importType, cleanupLog);
        status.add("file", file.getName());
        logger.log(Level.INFO, "completed doImport {0}/{1}",
                new Object[] { file.getParentFile().getName(), file.getName() });
        return status;
    } catch (ImportException ex) {
        String msg = "Import Exception processing file " + file.getParentFile().getName() + "/" + file.getName()
                + ", msg:" + ex.getMessage();
        logger.info(msg);
        if (validationLog != null) {
            validationLog.println(msg);
        }
        return Json.createObjectBuilder().add("message", "Import Exception processing file "
                + file.getParentFile().getName() + "/" + file.getName() + ", msg:" + ex.getMessage());
    } catch (IOException e) {
        Throwable causedBy = e.getCause();
        while (causedBy != null && causedBy.getCause() != null) {
            causedBy = causedBy.getCause();
        }
        String stackLine = "";
        if (causedBy != null && causedBy.getStackTrace() != null && causedBy.getStackTrace().length > 0) {
            stackLine = causedBy.getStackTrace()[0].toString();
        }
        String msg = "Unexpected Error in handleFile(), file:" + file.getParentFile().getName() + "/"
                + file.getName();
        if (e.getMessage() != null) {
            msg += "message: " + e.getMessage();
        }
        msg += ", caused by: " + causedBy;
        if (causedBy != null && causedBy.getMessage() != null) {
            msg += ", caused by message: " + causedBy.getMessage();
        }
        msg += " at line: " + stackLine;

        validationLog.println(msg);
        e.printStackTrace();

        return Json.createObjectBuilder().add("message", "Unexpected Exception processing file "
                + file.getParentFile().getName() + "/" + file.getName() + ", msg:" + e.getMessage());

    }
}

From source file:org.thoughtland.xlocation.Util.java

public static void bug(XHook hook, Throwable ex) {
    int priority;
    if (ex instanceof ActivityShare.AbortException)
        priority = Log.WARN;//from   ww w  .j a v a 2  s. co m
    else if (ex instanceof ActivityShare.ServerException)
        priority = Log.WARN;
    else if (ex instanceof ConnectTimeoutException)
        priority = Log.WARN;
    else if (ex instanceof FileNotFoundException)
        priority = Log.WARN;
    else if (ex instanceof HttpHostConnectException)
        priority = Log.WARN;
    else if (ex instanceof NoClassDefFoundError)
        priority = Log.WARN;
    else if (ex instanceof OutOfMemoryError)
        priority = Log.WARN;
    else if (ex instanceof RuntimeException)
        priority = Log.WARN;
    else if (ex instanceof SecurityException)
        priority = Log.WARN;
    else if (ex instanceof SocketTimeoutException)
        priority = Log.WARN;
    else if (ex instanceof SSLPeerUnverifiedException)
        priority = Log.WARN;
    else if (ex instanceof TransactionTooLargeException)
        priority = Log.WARN;
    else if (ex instanceof UnknownHostException)
        priority = Log.WARN;
    else
        priority = Log.ERROR;

    boolean xlocation = false;
    for (StackTraceElement frame : ex.getStackTrace())
        if (frame.getClassName() != null && frame.getClassName().startsWith("org.thoughtland.xlocation")) {
            xlocation = true;
            break;
        }
    if (!xlocation)
        priority = Log.WARN;

    log(hook, priority, ex.toString() + " uid=" + Process.myUid() + "\n" + Log.getStackTraceString(ex));
}