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:net.sourceforge.fenixedu.presentationTier.util.ExceptionInformation.java

public ExceptionInformation(HttpServletRequest request, Throwable ex) {
    StringBuilder tempBuilder = new StringBuilder();

    StringBuilder exceptionInfo = headerAppend(ex);

    // user// w  w  w  .  ja  va2s.  co  m
    this.requestBean = userInfoContextAppend(request, exceptionInfo);

    // mapping
    mappingContextAppend(request, exceptionInfo);

    // requestContext
    requestContextAppend(request, tempBuilder);
    this.requestContext = tempBuilder.toString();
    exceptionInfo.append("\n[RequestContext] \n");
    exceptionInfo.append(tempBuilder);
    exceptionInfo.append("\n\n");
    tempBuilder.setLength(0);

    // sessionContext
    exceptionInfo.append("\n[SessionContext]\n");
    sessionContextAppend(request, tempBuilder);
    this.sessionContext = tempBuilder.toString();
    exceptionInfo.append(tempBuilder);
    exceptionInfo.append("\n\n");
    tempBuilder.setLength(0);

    // stackTrace
    stackTrace2StringAppend(ex.getStackTrace(), tempBuilder);
    this.stackTrace = tempBuilder.toString();
    exceptionInfo.append(tempBuilder);

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    ex.printStackTrace(pw);
    String formattedST = sw.toString();
    this.formattedStackTrace = formattedST;

    ActionMapping mapping = this.getActionMapping();
    if (mapping != null) {
        StackTraceElement element = getStackTraceElementForActionMapping(request, mapping, ex.getStackTrace());
        if (element != null) {
            this.actionErrorFile = element.getFileName();
            this.actionErrorLine = element.getLineNumber();
        }
    }
    this.exceptionInfo = exceptionInfo.toString();

    if (ex.getClass().getName().equals("org.apache.jasper.JasperException")) {
        String message = ex.getLocalizedMessage();
        if (message.contains("\n")) {
            String[] name = message.split("\n");
            final Pattern lastIntPattern = Pattern.compile("([0-9]+)$");
            Matcher matcher = lastIntPattern.matcher(name[0]);
            if (matcher.find()) {
                jspExceptionLine = matcher.group(1);
                jspExceptionMessage = name[0];
                setJspExceptionSourceBefore(new ArrayList<JSPLine>());
                setJspExceptionSourceAfter(new ArrayList<JSPLine>());
                int state = 0;
                for (String s : Arrays.copyOfRange(name, 2, name.length - 3)) {
                    int i = s.indexOf(":");
                    JSPLine line = new JSPLine(s.substring(0, i).toString(),
                            s.substring(i + 1, s.length()).toString());
                    switch (state) {
                    case 0:
                        if (s.startsWith(jspExceptionLine)) {

                            setJspExceptionSourceLine(line);
                            state = 1;
                        } else {
                            getJspExceptionSourceBefore().add(line);
                        }
                        break;
                    case 1:
                        getJspExceptionSourceAfter().add(line);
                    default:
                        break;
                    }
                }
            }
        }
    }
}

From source file:com.seleniumtests.reporter.SeleniumTestsReporter.java

public void afterInvocation(final IInvokedMethod method, final ITestResult result) {
    Reporter.setCurrentTestResult(result);

    // Handle Soft CustomAssertion
    if (method.isTestMethod()) {
        final List<Throwable> verificationFailures = CustomAssertion.getVerificationFailures();

        final int size = verificationFailures.size();
        if (size == 0) {
            return;
        } else if (result.getStatus() == TestResult.FAILURE) {
            return;
        }//from w w w. j ava2  s .c om

        result.setStatus(TestResult.FAILURE);

        if (size == 1) {
            result.setThrowable(verificationFailures.get(0));
        } else {

            // create failure message with all failures and stack traces barring last failure)
            final StringBuilder failureMessage = new StringBuilder("!!! Many Test Failures (").append(size)
                    .append(")\n");
            for (int i = 0; i < size - 1; i++) {
                failureMessage.append("Failure ").append(i + 1).append(" of ").append(size).append("\n");

                final Throwable t = verificationFailures.get(i);
                final String fullStackTrace = Utils.stackTrace(t, false)[1];
                failureMessage.append(fullStackTrace).append("\n");
            }

            // final failure
            final Throwable last = verificationFailures.get(size - 1);
            failureMessage.append("Failure ").append(size).append(" of ").append(size).append(":n");
            failureMessage.append(last.toString());

            // set merged throwable
            final Throwable merged = new Throwable(failureMessage.toString());
            merged.setStackTrace(last.getStackTrace());

            result.setThrowable(merged);
        }
    }
}

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

/**
 * Almacena el mensaje de una excepcion en el log
 * //  ww  w .  ja  v a 2s  .  c om
 * @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.seleniumtests.reporter.SeleniumTestsReporter.java

protected void generateTheStackTrace(final Throwable exception, final ITestNGMethod method, final String title,
        final StringBuffer contentBuffer, final String lastline) {
    contentBuffer.append(" <div class='stContainer' >" + exception.getClass() + ":" + escape(title)
            + "(<a  href='javascript:void(0);'  class='exceptionlnk'>stacktrace</a>)");

    contentBuffer.append("<div class='exception' style='display:none'>");

    final StackTraceElement[] s1 = exception.getStackTrace();
    Throwable t2 = exception.getCause();
    if (t2 == exception) {
        t2 = null;/*w  w w.ja  v  a  2s .  co  m*/
    }

    for (int x = 0; x < s1.length; x++) {
        contentBuffer.append((x > 0 ? "<br/>at " : "") + escape(s1[x].toString()));
    }

    if (t2 != null) {
        generateExceptionReport(t2, method, "Caused by " + t2.getLocalizedMessage(), contentBuffer, ""); // jerry
    }

    contentBuffer.append("</div></div>");
}

From source file:org.openinfinity.core.aspect.ExceptionTranslatorAspect.java

private void resolveException(Throwable throwable) {
    if (throwable instanceof ApplicationException) {
        ApplicationException applicationException = (ApplicationException) throwable;
        if (!applicationException.isLogged()) {
            LOGGER.warn(getStackTraceString(applicationException));
            applicationException.setLogged(true);
        }// w w  w.jav  a2 s . com
        throw applicationException;
    } else if (throwable instanceof SystemException) {
        SystemException systemException = (SystemException) throwable;
        if (!systemException.isLogged()) {
            LOGGER.error(getStackTraceString(systemException));
            systemException.setLogged(true);
        }
        throw systemException;
    } else if (throwable instanceof BusinessViolationException) {
        BusinessViolationException businessViolationException = (BusinessViolationException) throwable;
        if (!businessViolationException.isLogged()) {
            LOGGER.error(getStackTraceString(businessViolationException));
            businessViolationException.setLogged(true);
        }
        throw businessViolationException;
    } else if (throwable instanceof NestedCheckedException) {
        LOGGER.warn("Resolving NestedCheckedException");
        SystemException systemException = new SystemException(
                "Caught NestedCheckedException, converting to SystemException: ",
                ((NestedCheckedException) throwable).getMostSpecificCause());
        systemException.setStackTrace(throwable.getStackTrace());
        LOGGER.error(getStackTraceString(systemException));
        systemException.setLogged(true);
        throw systemException;
    } else if (throwable instanceof NestedRuntimeException) {
        LOGGER.warn("Resolving NestedRuntimeException");
        SystemException systemException = new SystemException(
                "Caught NestedRuntimeException, converting to SystemException: ",
                ((NestedRuntimeException) throwable).getMostSpecificCause());
        systemException.setStackTrace(throwable.getStackTrace());
        LOGGER.error(getStackTraceString(systemException));
        systemException.setLogged(true);
        throw systemException;
    } else {
        LOGGER.warn(
                "Resolving unknown exception (use BusinessViolationException, SystemException or ApplicationException instead).");
        SystemException systemException = new SystemException(
                "Caught unknown exception, converting to SystemException: " + throwable.toString());
        systemException.setStackTrace(throwable.getStackTrace());
        LOGGER.error(getStackTraceString(systemException));
        systemException.setLogged(true);
        throw systemException;
    }
}

From source file:org.alfresco.repo.node.integrity.IntegrityChecker.java

/**
 * Loops through all the integrity events and checks integrity.
 * <p>/*from   w w w.jav  a 2  s . c o m*/
 * The events are stored in a set, so there are no duplicates.  Since each
 * event performs a particular type of check, this ensures that we don't
 * duplicate checks.
 * 
 * @return Returns a list of integrity violations, up to the
 *      {@link #maxErrorsPerTransaction the maximum defined}
 */
@SuppressWarnings("unchecked")
private List<IntegrityRecord> processAllEvents() {
    // the results
    ArrayList<IntegrityRecord> allIntegrityResults = new ArrayList<IntegrityRecord>(0); // generally empty

    // get all the events for the transaction (or unit of work)
    // duplicates have been elimiated
    Map<IntegrityEvent, IntegrityEvent> events = (Map<IntegrityEvent, IntegrityEvent>) AlfrescoTransactionSupport
            .getResource(KEY_EVENT_SET);
    if (events == null) {
        // no events were registered - nothing of significance happened
        return allIntegrityResults;
    }

    // failure results for the event
    List<IntegrityRecord> integrityRecords = new ArrayList<IntegrityRecord>(0);

    // cycle through the events, performing checking integrity
    for (IntegrityEvent event : events.keySet()) {
        try {
            event.checkIntegrity(integrityRecords);
        } catch (Throwable e) {
            // This means that integrity checking itself failed.  This is serious.
            // There are some exceptions that can be handled by transaction retries, so
            // we attempt to handle these and let them get out to trigger the retry.
            // Thanks to Carina Lansing.
            Throwable retryThrowable = RetryingTransactionHelper.extractRetryCause(e);
            if (retryThrowable != null) {
                // The transaction will be retrying on this, so there's no need for the aggressive
                // reporting that would normally happen
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                } else {
                    throw new RuntimeException(e);
                }
            }
            e.printStackTrace();
            // log it as an error and move to next event
            IntegrityRecord exceptionRecord = new IntegrityRecord("" + e.getMessage());
            exceptionRecord.setTraces(Collections.singletonList(e.getStackTrace()));
            allIntegrityResults.add(exceptionRecord);
            // move on
            continue;
        }

        // keep track of results needing trace added
        if (traceOn) {
            // record the current event trace if present
            for (IntegrityRecord integrityRecord : integrityRecords) {
                integrityRecord.setTraces(event.getTraces());
            }
        }

        // copy all the event results to the final results
        allIntegrityResults.addAll(integrityRecords);
        // clear the event results
        integrityRecords.clear();

        if (allIntegrityResults.size() >= maxErrorsPerTransaction) {
            // only so many errors wanted at a time
            break;
        }
    }
    // done
    return allIntegrityResults;
}

From source file:com.aol.framework.helper.report.CustomizedReporter.java

private void generateExceptionReport(Throwable exception, ITestNGMethod method, String title,
        PrintWriter m_out) {//from w  w w  .  j  a v a2s.c om

    m_out.println("<p>" + exception.getClass() + ": " + title + "</p><p>");

    StackTraceElement[] s1 = exception.getStackTrace();
    Throwable t2 = exception.getCause();
    if (t2 == exception) {
        t2 = null;
    }
    int maxlines = Math.min(100, StackTraceTools.getTestRoot(s1, method));
    for (int x = 0; x <= maxlines; x++) {
        m_out.println((x > 0 ? "<br/>at " : "") + Utils.escapeHtml(s1[x].toString()));
    }
    if (maxlines < s1.length) {
        m_out.println("<br/>" + (s1.length - maxlines) + " lines not shown");
    }
    if (t2 != null) {
        generateExceptionReport(t2, method, "Caused by " + t2.getLocalizedMessage(), m_out);
    }
    m_out.println("</p>");
    m_out.flush();
}

From source file:com.evolveum.midpoint.schema.result.OperationResult.java

private OperationResultType createOperationResultType(OperationResult opResult) {
    OperationResultType result = new OperationResultType();
    result.setToken(opResult.getToken());
    result.setStatus(OperationResultStatus.createStatusType(opResult.getStatus()));
    if (opResult.getCount() != 1) {
        result.setCount(opResult.getCount());
    }/*from  ww w  .j av a 2 s. c  o  m*/
    result.setOperation(opResult.getOperation());
    result.setMessage(opResult.getMessage());
    result.setMessageCode(opResult.getMessageCode());

    if (opResult.getCause() != null || !opResult.details.isEmpty()) {
        StringBuilder detailsb = new StringBuilder();

        // Record text messages in details (if present)
        if (!opResult.details.isEmpty()) {
            for (String line : opResult.details) {
                detailsb.append(line);
                detailsb.append("\n");
            }
        }

        // Record stack trace in details if a cause is present
        if (opResult.getCause() != null) {
            Throwable ex = opResult.getCause();
            detailsb.append(ex.getClass().getName());
            detailsb.append(": ");
            detailsb.append(ex.getMessage());
            detailsb.append("\n");
            StackTraceElement[] stackTrace = ex.getStackTrace();
            for (int i = 0; i < stackTrace.length; i++) {
                detailsb.append(stackTrace[i].toString());
                detailsb.append("\n");
            }
        }

        result.setDetails(detailsb.toString());
    }

    if (StringUtils.isNotEmpty(opResult.getLocalizationMessage())) {
        LocalizedMessageType message = new LocalizedMessageType();
        message.setKey(opResult.getLocalizationMessage());
        if (opResult.getLocalizationArguments() != null) {
            message.getArgument().addAll(opResult.getLocalizationArguments());
        }
        result.setLocalizedMessage(message);
    }

    //      Set<Entry<String, Serializable>> params = opResult.getParams();
    //      if (!params.isEmpty()) {
    ParamsType paramsType = ParamsTypeUtil.toParamsType(opResult.getParams());
    result.setParams(paramsType);

    //         for (Entry<String, Serializable> entry : params) {
    //            paramsType.getEntry().add(createEntryElement(entry.getKey(),entry.getValue()));
    //         }
    //      }

    //      Set<Entry<String, Serializable>> context = opResult.getContext().entrySet();
    //      if (!context.isEmpty()) {
    paramsType = ParamsTypeUtil.toParamsType(opResult.getContext());
    result.setContext(paramsType);

    //         for (Entry<String, Serializable> entry : context) {
    //            paramsType.getEntry().add(createEntryElement(entry.getKey(),entry.getValue()));
    //         }
    //      }

    //      Set<Entry<String, Serializable>> returns = opResult.getReturns().entrySet();
    //      if (!returns.isEmpty()) {
    paramsType = ParamsTypeUtil.toParamsType(opResult.getReturns());
    result.setReturns(paramsType);

    //         for (Entry<String, Serializable> entry : returns) {
    //            paramsType.getEntry().add(createEntryElement(entry.getKey(),entry.getValue()));
    //         }
    //      }

    for (OperationResult subResult : opResult.getSubresults()) {
        result.getPartialResults().add(opResult.createOperationResultType(subResult));
    }

    return result;
}

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();/*ww w  . j  av  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:com.idega.core.cache.filter.Filter.java

private void logThrowable(final Throwable throwable, final HttpServletRequest httpRequest)
        throws ServletException {
    StringBuffer messageBuffer = new StringBuffer("Throwable thrown during doFilter on request with URI: ")
            .append(httpRequest.getRequestURI()).append(" and Query: ").append(httpRequest.getQueryString());
    String message = messageBuffer.toString();
    boolean matchFound = matches(throwable);
    if (matchFound) {
        try {/*ww w.jav a 2 s  .  co  m*/
            if (this.suppressStackTraces) {
                Method method = Log.class.getMethod(this.exceptionsToLogDifferentlyLevel,
                        new Class[] { Object.class });
                method.invoke(LOG, new Object[] { throwable.getMessage() });
            } else {
                Method method = Log.class.getMethod(this.exceptionsToLogDifferentlyLevel,
                        new Class[] { Object.class, Throwable.class });
                method.invoke(LOG, new Object[] { throwable.getMessage(), throwable });
            }
        } catch (Exception e) {
            LOG.fatal("Could not invoke Log method for " + this.exceptionsToLogDifferentlyLevel, e);
        }
        throw new ServletException(message, throwable);
    } else {

        if (this.suppressStackTraces) {
            LOG.warn(messageBuffer.append(throwable.getMessage()).append("\nTop StackTraceElement: ")
                    .append(throwable.getStackTrace()[0].toString()));
        } else {
            LOG.warn(messageBuffer.append(throwable.getMessage()), throwable);
        }
        throw new ServletException(throwable);
    }
}