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:com.bstek.dorado.view.task.LongTaskThread.java

public ExceptionInfo(Exception e) {
    Throwable throwable = e;
    // while (throwable.getCause() != null) {
    // throwable = throwable.getCause();
    // }/*from   w  w w .j  a v a 2  s. c om*/

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

    StackTraceElement[] stackTraceElements = throwable.getStackTrace();
    stackTrace = new String[stackTraceElements.length];
    int i = 0;
    for (StackTraceElement stackTraceElement : stackTraceElements) {
        stackTrace[i] = stackTraceElement.getClassName() + '.' + stackTraceElement.getMethodName() + '('
                + stackTraceElement.getFileName() + ':' + stackTraceElement.getLineNumber() + ')';
        i++;
    }
}

From source file:com.gargoylesoftware.htmlunit.SimpleWebTestCase.java

/**
 * Finds from the call stack the active running JUnit test case
 * @return the test case method/*from w w  w . j a va2s  . co  m*/
 * @throws RuntimeException if no method could be found
 */
private Method findRunningJUnitTestMethod() {
    final Class<?> cl = getClass();
    final Class<?>[] args = new Class[] {};

    // search the initial junit test
    final Throwable t = new Exception();
    for (int i = t.getStackTrace().length - 1; i >= 0; i--) {
        final StackTraceElement element = t.getStackTrace()[i];
        if (element.getClassName().equals(cl.getName())) {
            try {
                final Method m = cl.getMethod(element.getMethodName(), args);
                if (isPublicTestMethod(m)) {
                    return m;
                }
            } catch (final Exception e) {
                // can't access, ignore it
            }
        }
    }

    throw new RuntimeException("No JUnit test case method found in call stack");
}

From source file:net.naijatek.myalumni.framework.struts.MyAlumniExceptionHandler.java

/**
 * This method handles any java.lang.Exceptions that are not caught in
 * previous classes. It will loop through and get all the causes (exception
 * chain), create ActionErrors, add them to_email the request and then
 * forward to_email the input./*from w w w .  j ava2 s.c  o m*/
 * 
 * @see org.apache.struts.action.ExceptionHandler#execute()
 *      java.lang.Exception, org.apache.struts.config.ExceptionConfig,
 *      org.apache.struts.action.ActionMapping,
 *      org.apache.struts.action.ActionForm,
 *      javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse )
 * 
 * @param ex
 *            Exception
 * @param ae
 *            ExceptionConfig
 * @param mapping
 *            ActionMapping
 * @param form
 *            ActionForm
 * @param request
 *            HttpServletRequest
 * @param response
 *            HttpServletResponse
 * @throws ServletException
 * @return ActionForward
 */
public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws ServletException {

    ActionMessages messages = new ActionMessages();

    // This is where it was suppose to forward to in the first place.
    ActionForward forward = super.execute(ex, ae, mapping, form, request, response);

    ServletContext sCtx = request.getSession().getServletContext();
    WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sCtx);
    IErrorLogService loggerService = (IErrorLogService) wac.getBean(BaseConstants.SERVICE_ERRORLOGGER_LOOKUP);

    String forwardKey = new String();
    Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");

    Throwable thr = (Throwable) request.getAttribute("javax.servlet.error.exception");
    StringBuffer strBuffer = new StringBuffer();

    if (thr != null) {
        StackTraceElement[] stack = thr.getStackTrace();
        for (int n = 0; n < stack.length; n++) {
            strBuffer.append(stack[n].toString());
            strBuffer.append("\n");
        }
    }

    //String messg = (String) request.getAttribute("javax.servlet.error.message");
    String messg = (String) ex.getMessage();
    messg = (messg != null && messg.length() >= 4000) ? messg.substring(0, 3999) : messg;

    String trace = strBuffer.toString();
    trace = (trace != null && trace.length() >= 4000) ? trace.substring(0, 3999) : trace;

    //String cause = (String) request.getAttribute("javax.servlet.error.request_uri");
    String cause = new String();
    if (ex.getCause() != null)
        cause = ex.getCause().toString();

    String userName = new String();

    try {
        MyAlumniUserContainer sessionObj = null;
        HttpSession session = request.getSession(false);
        if (session != null) {
            sessionObj = (MyAlumniUserContainer) session.getAttribute(BaseConstants.USER_CONTAINER);
            userName = sessionObj.getToken().getMemberUserName();
        }
    } catch (Exception npe) {
        // do nothing
        userName = "";
    }

    ErrorLogVO errorLog = new ErrorLogVO();
    errorLog.setErrorDate(new Date());
    errorLog.setLoggedBy(userName);
    errorLog.setLastModifiedBy(userName);
    errorLog.setErrorMessage(messg);
    errorLog.setCause(cause);
    errorLog.setTrace(trace);

    loggerService.addErrorLog(errorLog);

    // 700: Insufficient Priviledges
    // 701: Session Timed Out

    if (statusCode != null) {
        int sc = ((Integer) statusCode).intValue();

        switch (sc) {
        case 700:
            forwardKey = BaseConstants.SC_INSURFICIENT_PRIV_700;
            messages.add(BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00701"));
            storeException(request, BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00701"),
                    forward);
            break;

        case 701:
            forwardKey = BaseConstants.SC_SESSION_EXPIRED_701;
            messages.add(BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00702"));
            storeException(request, BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00702"),
                    forward);
            break;

        }
    }

    if (forwardKey != null && forwardKey.length() == 0) {
        String requestPathInfo = request.getPathInfo(); // request path info.

        if (requestPathInfo != null && requestPathInfo.startsWith("/admin/")) {
            forwardKey = BaseConstants.FWD_ADMIN;
            messages.add(BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00703"));
            storeException(request, BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00703"),
                    forward);
        } else if (requestPathInfo != null && requestPathInfo.startsWith("/member/")) {
            forwardKey = BaseConstants.FWD_MEMBER;
            messages.add(BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00704"));
            storeException(request, BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00704"),
                    forward);
        } else {
            forwardKey = BaseConstants.FWD_MEMBER;
            messages.add(BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00703"));
            storeException(request, BaseConstants.FATAL_KEY, new ActionMessage("core.errorcode.00703"),
                    forward);
        }
    }

    return mapping.findForward(forwardKey);
}

From source file:com.alliander.osgp.acceptancetests.devicemanagement.RetrieveReceivedEventNotificationsSteps.java

@DomainStep("the retrieve event notification request is received")
public void whenTheRetrieveEventNotificationRequestIsReceived() {
    LOGGER.info("WHEN: the retrieve event notification request is received");

    try {/*from  w  w  w.  j ava 2 s .  c  om*/
        // Send the find events request.
        this.response = this.deviceManagementEndpoint
                .findEventsRequest(this.organisation.getOrganisationIdentification(), this.request);
        if (this.response == null) {
            LOGGER.info("Response is null");
        }
    } catch (final Throwable t) {
        LOGGER.error("Exception [{}]: {}\nStacktrace: {}", t.getClass().getSimpleName(), t.getMessage(),
                t.getStackTrace());
    }
}

From source file:org.nimbustools.messaging.gt4_0.common.CommonUtil.java

/**
 * finds the root cause and prints its error description or if there is no
 * error description, just its class name
 *
 * Makes use of <code>BaseFaultType</code> awareness, via
 * <code>#faultString(BaseFaultType)</code>
 *
 * @param throwable may be null/*w  ww  .  j  a  v a  2  s  . c o m*/
 * @param suffixClassChain if true, class names of all errors involved are
 *        tacked on to the string like: [[ classname --> classname --> ...]]
 * @param numIncludedParentMsgs if suffixClassChain is true, this is the
 *        number of parents up from cause to print the exception messages
 *        for in the chain msg (not just the parent types)
 * @param lookForSysProp if true, the "nimbus.errors.parent.number" will
 *        be consulted and could possibly override the choice for
 *        numIncludedParentMsgs
 * @return LAST encountered error description/classname, only null if
 *         input is null (there is neither a type nor message to report)
 */
public static String recurseForRootString(final Throwable throwable, final boolean suffixClassChain,
        final int numIncludedParentMsgs, final boolean lookForSysProp) {

    int realNumIncludedParentMsgs = numIncludedParentMsgs;
    if (lookForSysProp) {
        final String numParentsString = System.getProperty(PRETTY_CAUSES_NUM_KEY);

        try {
            if (numParentsString != null && numParentsString.trim().length() != 0) {
                realNumIncludedParentMsgs = Integer.parseInt(numParentsString);
            }
        } catch (Throwable t2) {
            logger.error("Could not parse a number from the '" + PRETTY_CAUSES_NUM_KEY + "' system property.");
        }
    }

    final String alsoStackTracesStr = System.getProperty(PRETTY_CAUSES_STACKTRACES);

    boolean alsoStackTraces = false;
    if (alsoStackTracesStr != null && alsoStackTracesStr.trim().equalsIgnoreCase("true")) {
        alsoStackTraces = true;
    }

    final List parentMsgs = new LinkedList();
    final List parentTypes = new LinkedList();
    final List parentStacktraces = new LinkedList();
    final StringBuffer buf = new StringBuffer();

    int numDeep = 0;

    Throwable t = throwable;
    Throwable lastt = null;

    while (true) {

        if (t == null) {
            return _doneRecursingForRootString(lastt, numDeep, buf, suffixClassChain, parentMsgs, parentTypes,
                    realNumIncludedParentMsgs, alsoStackTraces, parentStacktraces);
        }

        numDeep += 1;

        String thisMsg = t.getMessage();
        if (thisMsg == null && t instanceof BaseFaultType) {
            thisMsg = faultString((BaseFaultType) t);
        }

        if (thisMsg == null) {

            if (t instanceof RuntimeException) {

                final StringBuffer lilStack = new StringBuffer();
                lilStack.append(
                        "No message, but RuntimeException so " + "including part of the stack trace: [[ ");
                lilStack.append("\n").append(t.getClass().getName());
                final StackTraceElement[] runTimeTraces = t.getStackTrace();
                for (int i = 0; i < runTimeTraces.length; i++) {
                    final StackTraceElement runTimeTrace = runTimeTraces[i];
                    lilStack.append("\n\t at ").append(runTimeTrace);

                    if (i == 10) {
                        final int remaining = runTimeTraces.length - i;
                        if (remaining > 0) {
                            lilStack.append("\n ...").append(remaining).append(" more.");
                        }
                        break;
                    }
                }

                lilStack.append("\n ]]");
                thisMsg = lilStack.toString();

            } else {
                thisMsg = "no message";
            }
        }

        final String thisType = t.getClass().getName();

        final Throwable thisCause = t.getCause();

        if (thisCause == null) {
            lastt = t;
            t = null;
            buf.append(thisMsg).append(" (").append(thisType).append(")");
        } else {
            // keep going deeper
            lastt = t;
            t = thisCause;
            parentMsgs.add(thisMsg);
            parentTypes.add(thisType);
            parentStacktraces.add(t.getStackTrace());
        }
    }
}

From source file:op.tools.SYSTools.java

public static String getThrowableAsHTML(Throwable exc) {
    String html = "";
    StackTraceElement[] stacktrace = exc.getStackTrace();

    html += SYSConst.html_h1("mail.errormail.attachment.line1");
    html += SYSConst.html_h2(exc.getClass().getName());
    html += SYSConst.html_paragraph(exc.getMessage());

    if (OPDE.getMainframe().getCurrentResident() != null) {
        html += SYSConst.html_h3("ResID: " + OPDE.getMainframe().getCurrentResident().getRID());
    }/*  w w w  . ja  va 2s.  com*/

    html += SYSConst.html_h3(OPDE.getMainframe().getCurrentVisiblePanel().getInternalClassID());

    String table = SYSConst.html_table_th("mail.errormail.attachment.tab.col1")
            + SYSConst.html_table_th("mail.errormail.attachment.tab.col2")
            + SYSConst.html_table_th("mail.errormail.attachment.tab.col3")
            + SYSConst.html_table_th("mail.errormail.attachment.tab.col4");

    for (int exception = 0; exception < stacktrace.length; exception++) {
        StackTraceElement element = stacktrace[exception];
        table += SYSConst.html_table_tr(SYSConst.html_table_td(element.getMethodName())
                + SYSConst.html_table_td(Integer.toString(element.getLineNumber()))
                + SYSConst.html_table_td(element.getClassName())
                + SYSConst.html_table_td(element.getFileName()));
    }

    html += SYSConst.html_table(table, "1");

    // Possible Cause
    if (exc.getCause() != null) {
        html += SYSConst.html_h3("Caused by: " + exc.getCause().getMessage());
        StackTraceElement[] stacktrace1 = exc.getCause().getStackTrace();
        String table1 = SYSConst.html_table_th("mail.errormail.attachment.tab.col1")
                + SYSConst.html_table_th("mail.errormail.attachment.tab.col2")
                + SYSConst.html_table_th("mail.errormail.attachment.tab.col3")
                + SYSConst.html_table_th("mail.errormail.attachment.tab.col4");

        for (int exception = 0; exception < stacktrace1.length; exception++) {
            StackTraceElement element = stacktrace1[exception];
            table1 += SYSConst.html_table_tr(SYSConst.html_table_td(element.getMethodName())
                    + SYSConst.html_table_td(Integer.toString(element.getLineNumber()))
                    + SYSConst.html_table_td(element.getClassName())
                    + SYSConst.html_table_td(element.getFileName()));
        }

        html += SYSConst.html_table(table1, "1");
    }

    return html;
}

From source file:org.apache.fineract.infrastructure.jobs.service.JobRegisterServiceImpl.java

private String getStackTraceAsString(final Throwable throwable) {
    final StackTraceElement[] stackTraceElements = throwable.getStackTrace();
    final StringBuffer sb = new StringBuffer(throwable.toString());
    for (final StackTraceElement element : stackTraceElements) {
        sb.append("\n \t at ").append(element.getClassName()).append(".").append(element.getMethodName())
                .append("(").append(element.getLineNumber()).append(")");
    }/*from  w ww.  j  a v  a 2  s.  co  m*/
    return sb.toString();
}

From source file:com.consol.citrus.report.HtmlReporter.java

/**
 * Construct HTML code snippet for stack trace information.
 * @param cause the causing error./*  w ww . j  a  va2 s.co  m*/
 * @return
 */
private String getStackTraceHtml(Throwable cause) {
    StringBuilder stackTraceBuilder = new StringBuilder();
    stackTraceBuilder.append(cause.getClass().getName() + ": " + cause.getMessage() + "\n ");
    for (int i = 0; i < cause.getStackTrace().length; i++) {
        stackTraceBuilder.append("\n\t at ");
        stackTraceBuilder.append(cause.getStackTrace()[i]);
    }

    return "<tr><td colspan=\"2\">" + "<div class=\"error-detail\"><pre>" + stackTraceBuilder.toString()
            + "</pre>" + getCodeSnippetHtml(cause) + "</div></td></tr>";
}

From source file:org.eclipse.epp.internal.logging.aeri.ui.LogListenerTest.java

@Test
public void testNoAcceptingOtherPackages() {
    Throwable t = new RuntimeException();
    t.fillInStackTrace();/*from  w  w  w .  ja  va 2  s. c  om*/
    StackTraceElement[] stackTrace = t.getStackTrace();
    stackTrace[0] = new StackTraceElement("any.third.party.Clazz", "thirdPartyMethod", "Clazz.java", 42);
    t.setStackTrace(stackTrace);
    Status status = new Status(IStatus.ERROR, TEST_PLUGIN_ID, "Error Message", t);

    configuration.setAcceptOtherPackages(false);

    sut.logging(status, "");
    verifyNoErrorReportLogged();
}

From source file:at.ac.tuwien.infosys.jcloudscale.server.JCloudScaleServer.java

void logException(Throwable e) {
    StackTraceElement[] trace = e.getStackTrace();
    StringBuilder sb = new StringBuilder();
    sb.append("Exception Trace\n");
    sb.append(e.getClass().getName() + ": ");
    if (e.getMessage() != null)
        sb.append(e.getMessage() + "\n");
    for (StackTraceElement el : trace) {
        sb.append("\tat " + el.toString());
        sb.append("\n");
    }//from  w ww  . java2 s. co m
    this.log.severe(sb.toString());
}