Example usage for java.lang StackTraceElement getFileName

List of usage examples for java.lang StackTraceElement getFileName

Introduction

In this page you can find the example usage for java.lang StackTraceElement getFileName.

Prototype

public String getFileName() 

Source Link

Document

Returns the name of the source file containing the execution point represented by this stack trace element.

Usage

From source file:com.qspin.qtaste.ui.reporter.TestCaseReportTable.java

protected void updateTestCaseRow(TestResult tr) {

    int rowNum = ((Integer) testCases.get(tr)).intValue();
    if (rowNum == -1) {
        // means that testcases has not been emptied ..

        // TO DO/*  w w  w. ja v  a 2 s. co m*/
        return;
    }
    tcModel.setValueAt(convertToUniqueTc(tr), rowNum, TEST_CASE);
    tcModel.setValueAt(tr.getFormattedElapsedTime(false), rowNum, EXEC_TIME);
    tcModel.setValueAt(tr.getExtraResultDetails(), rowNum, DETAILS);
    if (tr.getReturnValue() != null) {
        tcModel.setValueAt(tr.getReturnValue(), rowNum, RESULT);
    }

    TestResult.Status testCaseStatus = tr.getStatus();
    ImageIcon statusImg = getImage(testCaseStatus);
    tcModel.setValueAt(statusImg, rowNum, STATUS);

    TestBedConfiguration testbed = TestBedConfiguration.getInstance();
    tcModel.setValueAt(
            testbed.getFile().getName().replace("." + StaticConfiguration.CAMPAIGN_FILE_EXTENSION, ""), rowNum,
            TESTBED);

    if ((testCaseStatus == TestResult.Status.FAIL) || ((testCaseStatus == TestResult.Status.NOT_AVAILABLE))) {
        int selectedRow = tcTable.getSelectedRow();
        // update the failedReason if the current selected testcase is
        //   the one to be updated
        if (selectedRow == rowNum) {
            if (tcReasonModel != null) {
                // clear
                while (tcReasonModel.getRowCount() > 0) {
                    tcReasonModel.removeRow(0);
                }
                ArrayList<StackTraceElement> stack = tr.getStack();
                Iterator<StackTraceElement> it = stack.iterator();
                while (it.hasNext()) {
                    StackTraceElement stackElement = it.next();
                    if (stackElement.getFileName().equals("embedded_jython")) {
                        continue;
                    }
                    Object[] row = new Object[6];
                    row[TCResultsSelectionListeners.LINE] = stackElement.getLineNumber();
                    row[TCResultsSelectionListeners.FILE_NAME] = stackElement.getFileName();
                    String methodName = stackElement.getMethodName();
                    if (methodName.equals("f$0")) {
                        methodName = "main";
                    } else {
                        // remove $i suffix from method name
                        int dollarIndex = methodName.indexOf("$");
                        if (dollarIndex > 0) {
                            methodName = methodName.substring(0, dollarIndex);
                        }
                    }
                    row[TCResultsSelectionListeners.FUNCTION_ID] = methodName;
                    //row[TCResultsSelectionListeners.ERR_MSG] = tr.getExtraResultDetails();
                    row[TCResultsSelectionListeners.OBJECT] = stackElement;
                    //row[TCResultsSelectionListeners.ROW] = tr.getTestData() != null ? tr.getTestData().getRowId() : null;;
                    tcReasonModel.addRow(row);
                }
            }
            if (stackTrace != null) {
                stackTrace.setText(tr.getStackTrace());
            }
        }
    }
}

From source file:org.codelibs.fess.web.base.FessBaseAction.java

protected void buildApplicationExceptionStackTrace(RuntimeException cause, StringBuilder sb) {
    final StackTraceElement[] stackTrace = cause.getStackTrace();
    if (stackTrace == null) { // just in case
        return;/*from   w  w w.ja v  a 2  s  .c  om*/
    }
    int index = 0;
    for (StackTraceElement element : stackTrace) {
        if (index > 10) { // not all because it's not error
            break;
        }
        final String className = element.getClassName();
        final String fileName = element.getFileName(); // might be null
        final int lineNumber = element.getLineNumber();
        final String methodName = element.getMethodName();
        sb.append("\n at ").append(className).append(".").append(methodName);
        sb.append("(").append(fileName);
        if (lineNumber >= 0) {
            sb.append(":").append(lineNumber);
        }
        sb.append(")");
        ++index;
    }
}

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

/**
 * Almacena el mensaje de una excepcion en el log
 * //www .j  a v a 2s.com
 * @author <FONT style='color:#55A; font-size:12px; font-weight:bold;'>Hermann D. Schimpf</FONT>
 * @author <B>HDS Solutions</B> - <FONT style="font-style:italic;">Soluci&oacute;nes Inform&aacute;ticas</FONT>
 * @version Oct 1, 2012 12:55:33 PM
 * @param level Nivel del mensaje
 * @param exception Excepcion a mostrar
 */
public synchronized void log(final Level level, final Throwable exception) {
    // verificamos si alguno esta habilitado
    if (!level.isEnabled(this.consoleLevel) && !level.isEnabled(this.fileLevel))
        // salimos
        return;
    // generamos el inicio del mensaje
    final String logStart = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
            .format(new Date(System.currentTimeMillis())) + " "
            + StringUtils.rightPad("[" + level.name() + "]", 9) + this.name + " ";
    // iniciamos el mensaje
    final StringBuffer log = new StringBuffer(logStart);
    // agregamos el mensaje de la excepcion
    log.append(exception.getClass().getName()
            + (exception.getMessage() != null ? ": " + exception.getMessage() : ""));
    // recorremos los pasos
    for (final StackTraceElement stackTrace : exception.getStackTrace())
        // agregamos el elemento
        log.append("\n" + logStart + "\t" + stackTrace.getClassName() + "." + stackTrace.getMethodName() + "("
                + stackTrace.getFileName() + ":" + stackTrace.getLineNumber() + ")");
    // verificamos si mostramos en consola
    if (level.isEnabled(this.consoleLevel))
        // verificamos si es >= ERROR
        if (level.isEnabled(Level.ERROR))
            // mostrar el mensaje en consola de error
            System.err.println(log);
        else
            // mostrar el mensaje en consola de error
            System.out.println(log);
    // verificamos si mostramos en el fichero
    if (level.isEnabled(this.fileLevel) && this.logToFile)
        // escribimos la linea en el fichero
        this.writeToFile(log.toString());
    // recorremos los listeners
    for (final LoggerListener listener : Logger.listeners)
        // enviamos el mensaje
        listener.log(this, log.toString(), level, true);
}

From source file:com.yourkey.billing.util.InAppBilling.java

private String getErrorLocation(int stackFrame) {
    StackTraceElement element = new Throwable().getStackTrace()[stackFrame + 1];
    String className = element.getClassName();
    if (className.startsWith(packageName + "."))
        className = className.substring(packageName.length() + 1);
    return ("Error location: " + element.getFileName() + " (" + Integer.toString(element.getLineNumber())
            + ")\n" + className + "." + element.getMethodName());
}

From source file:com.centurylink.mdw.services.test.TestCaseRun.java

public void finishExecution(Throwable e) {
    if (isLoadTest()) {
        if (e != null)
            e.printStackTrace(); // otherwise won't see errors
        if (log != System.out && log != System.err)
            log.close();/*from w ww  . j a  v  a2  s .  c  o  m*/
        return;
    }
    // function test only below
    if (e == null) {
    } else if (e instanceof TestException) {
        passed = false;
        message = firstLine(e.getMessage());
        log.println(message);
        if (e.getCause() instanceof TestFailedException) {
            // find the script line number
            for (StackTraceElement el : e.getStackTrace()) {
                if (el.getFileName() != null && el.getFileName().endsWith(".groovy")) {
                    log.println(" --> at " + getTestCase().getPath() + ":" + el.getLineNumber());
                }
            }
        } else {
            e.printStackTrace(log);
        }
    } else if (e instanceof ParseException) {
        passed = false;
        message = "Command syntax error at line " + ((ParseException) e).getErrorOffset() + ": "
                + e.getMessage();
        log.println(message);
        e.printStackTrace(log);
    } else {
        passed = false;
        message = firstLine(e.toString());
        if ("Assertion failed: ".equals(message))
            message += "See execution log for details.";
        log.println("Exception " + message);
        e.printStackTrace(log);
    }
    TestCase.Status status = testCase.getStatus();
    Date endDate = new Date();
    if (isVerbose()) {
        long seconds = (endDate.getTime() - testCase.getStart().getTime()) / 1000;
        if (status == TestCase.Status.Errored)
            log.println("===== case " + testCase.getPath() + " Errored after " + seconds + " seconds");
        else if (status == TestCase.Status.Stopped)
            log.println("===== case " + testCase.getPath() + " Stopped after " + seconds + " seconds");
        else
            log.println("===== case " + testCase.getPath() + (passed ? " Passed" : " Failed") + " after "
                    + seconds + " seconds");
    }
    if (log != System.out && log != System.err)
        log.close();

    if (status != TestCase.Status.Errored && status != TestCase.Status.Stopped) {
        testCase.setEnd(endDate);
        testCase.setStatus(passed ? TestCase.Status.Passed : TestCase.Status.Failed);
    }

    if (testCase.getItems() != null) {
        if (e != null)
            e.printStackTrace(); // else would have to dig in testCase (not item) log
        for (TestCaseItem item : testCase.getItems()) {
            if (e != null) {
                // don't leave unfinished items
                if (item.getStatus() == Status.InProgress) {
                    item.setStatus(testCase.getStatus());
                    item.setMessage(testCase.getMessage());
                }
            }
        }
    }
}

From source file:org.kuali.kfs.module.purap.service.impl.ElectronicInvoiceHelperServiceImpl.java

/**
 * @param element/*from  www  .  ja  v a  2 s .  c o  m*/
 * @return String describing the given StackTraceElement
 */
private static String describeStackTraceElement(StackTraceElement element) {
    StringBuffer description = new StringBuffer();
    if (element == null) {
        description.append("invalid (null) element");
    }
    description.append(element.getClassName());
    description.append(".");
    description.append(element.getMethodName());
    description.append("(");
    description.append(element.getFileName());
    description.append(":");
    description.append(element.getLineNumber());
    description.append(")");

    return description.toString();
}

From source file:edu.umd.cs.marmoset.modelClasses.TestOutcome.java

private boolean coversLineOrPreviousLines(StackTraceElement stackTraceElement, int range,
        CodeCoverageResults coverage) throws IOException {
    // If we weren't able to extract a stack trace for some reason, then simply return false
    if (stackTraceElement == null)
        return false;
    if (!isCoverageType())
        return false;
    FileWithCoverage fileWithCoverage = coverage.getFileWithCoverage(stackTraceElement.getFileName());
    if (fileWithCoverage == null) {
        // ERROR: Can't find the appropriate file in this set of coverage results
        System.err.println("No coverage for " + stackTraceElement.getFileName());
        return false;
    }/*from   w  w  w. j ava  2s .  com*/
    for (int ii = stackTraceElement.getLineNumber(); ii >= stackTraceElement.getLineNumber() - range; ii--) {
        if (fileWithCoverage.isLineCovered(ii))
            return true;
    }
    return false;
}

From source file:org.csploit.android.core.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    action what_to_do = (action) intent.getSerializableExtra(ACTION);
    boolean exitForError = true;

    if (what_to_do == null) {
        Logger.error("received null action");
        return;/*from w ww  .ja va 2 s.  c  o m*/
    }

    mRunning = true;

    switch (what_to_do) {
    case apk_update:
        mCurrentTask = mApkInfo;
        break;
    case core_update:
        mCurrentTask = mCoreInfo;
        break;
    case ruby_update:
        mCurrentTask = mRubyInfo;
        break;
    case msf_update:
        mCurrentTask = mMsfInfo;
        break;
    case gems_update:
        mCurrentTask = new ArchiveMetadata();
        break;
    }

    try {
        setupNotification();

        synchronized (mCurrentTask) {
            mCurrentTask.errorOccurred = true;
            if (!haveLocalFile())
                downloadFile();

            if (what_to_do == action.core_update)
                System.shutdownCoreDaemon();

            extract();

            if (what_to_do == action.msf_update)
                installGems();
            else if (what_to_do == action.gems_update)
                updateGems();
            else if (what_to_do == action.core_update)
                System.initCore();

            deleteTemporaryFiles();
            createVersionFile();

            mCurrentTask.errorOccurred = exitForError = false;
        }

        sendDone(what_to_do);
    } catch (SecurityException e) {
        sendError(what_to_do, R.string.bad_permissions);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (KeyException e) {
        sendError(what_to_do, R.string.checksum_failed);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        sendError(what_to_do, R.string.error_occured);
        System.errorLogging(e);
    } catch (CancellationException e) {
        sendError(what_to_do, R.string.update_cancelled);
        Logger.warning(e.getClass().getName() + ": " + e.getMessage());
    } catch (IOException e) {
        sendError(what_to_do, R.string.error_occured);
        System.errorLogging(e);
    } catch (RuntimeException e) {
        sendError(what_to_do, R.string.error_occured);

        StackTraceElement[] stack = e.getStackTrace();
        StackTraceElement frame = e.getStackTrace()[0];

        for (StackTraceElement f : stack) {
            if (f.getClassName().startsWith("org.csploit.android")) {
                frame = f;
                break;
            }
        }

        Logger.error(String.format("%s: %s [%s:%d]", e.getClass().getName(), e.getMessage(),
                frame.getFileName(), frame.getLineNumber()));
    } catch (InterruptedException e) {
        sendError(what_to_do, R.string.error_occured);
        System.errorLogging(e);
    } catch (ChildManager.ChildNotStartedException e) {
        sendError(what_to_do, R.string.error_occured);
        System.errorLogging(e);
    } catch (ChildManager.ChildDiedException e) {
        sendError(what_to_do, R.string.error_occured);
        System.errorLogging(e);
    } catch (System.SuException e) {
        sendError(what_to_do, R.string.only_4_root);
    } catch (System.DaemonException e) {
        sendError(what_to_do, R.string.heart_attack);
        Logger.error(e.getMessage());
    } finally {
        if (exitForError) {
            if (what_to_do == action.msf_update || what_to_do == action.gems_update)
                clearGemsCache();
            if (what_to_do != action.core_update)
                wipe();
        }
        stopSelf();
        mRunning = false;
    }
}

From source file:com.ichi2.libanki.Collection.java

/**
 * Logging/* ww  w .  j  av a 2s.c o  m*/
 * ***********************************************************
 */

public void log(Object... args) {
    if (!mDebugLog) {
        return;
    }
    StackTraceElement trace = Thread.currentThread().getStackTrace()[3];
    // Overwrite any args that need special handling for an appropriate string representation
    for (int i = 0; i < args.length; i++) {
        if (args[i] instanceof long[]) {
            args[i] = Arrays.toString((long[]) args[i]);
        }
    }
    String s = String.format("[%s] %s:%s(): %s", Utils.intNow(), trace.getFileName(), trace.getMethodName(),
            TextUtils.join(",  ", args));
    mLogHnd.println(s);
    Timber.d(s);
}

From source file:edu.isi.wings.ontapi.jena.KBAPIJena.java

private boolean checkNulls(Object... vars) {
    for (Object var : vars) {
        if (var == null) {
            StackTraceElement[] stack = Thread.currentThread().getStackTrace();
            StackTraceElement method = stack[2];
            StackTraceElement caller = stack[3];
            String warnstr = method.getMethodName() + ": " + Arrays.toString(vars);
            warnstr += ", called from " + caller.getFileName() + ":" + caller.getLineNumber();
            Logger.getLogger(this.getClass()).warn(warnstr);
            return false;
        }//from  www  . jav  a 2s .c  om
    }
    return true;
}