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.alfresco.repo.audit.AuditMethodInterceptor.java

/**
 * Audit values after the invocation/*w  ww.  ja v  a2s.co  m*/
 * 
 * @param serviceName       the service name
 * @param methodName        the method name
 * @param namedArguments    the named arguments passed to the invocation
 * @param ret               the result of the execution (may be <tt>null</tt>)
 * @param thrown            the error thrown by the invocation (may be <tt>null</tt>)
 * @param preAuditedData    the audited data from before the method call.
 * 
 * @since 3.2
 */
private void auditInvocationAfter(String serviceName, String methodName,
        Map<String, Serializable> namedArguments, Object ret, final Throwable thrown,
        Map<String, Serializable> preAuditedData) {
    final String rootPath = AuditApplication.buildPath(AUDIT_PATH_API_POST, serviceName, methodName);

    final Map<String, Serializable> auditData = new HashMap<String, Serializable>(23);
    if (namedArguments.isEmpty()) {
        auditData.put(AUDIT_SNIPPET_ARGS, null);
    } else {
        for (Map.Entry<String, Serializable> entry : namedArguments.entrySet()) {
            String argName = entry.getKey();
            Serializable argValue = entry.getValue();
            auditData.put(AuditApplication.buildPath(AUDIT_SNIPPET_ARGS, argName), argValue);
        }
    }

    // Add audited data prior to the method call, so it may be repeated
    for (Entry<String, Serializable> entry : preAuditedData.entrySet()) {
        String path = AuditApplication.buildPath(AUDIT_SNIPPET_PRE_CALL_DATA, entry.getKey());
        auditData.put(path, entry.getValue());
    }

    Serializable value = getRecordableValue(ret);
    if (value != null && value != NOT_RECORDABLE) {
        auditData.put(AUDIT_SNIPPET_RESULT, value);
    }

    if (thrown != null) {
        // ALF-3055: an exception has occurred - make sure the audit occurs in a new thread
        //     rather than a nested transaction to avoid contention for the same audit table
        // ALF-12638: ensure that the new thread context matches the current thread context
        final Authentication authContext = AuthenticationUtil.getFullAuthentication();
        threadPoolExecutor.execute(new Runnable() {
            public void run() {
                Map<String, Serializable> auditedData;

                StringBuilder sb = new StringBuilder(1024);
                StackTraceUtil.buildStackTrace(thrown.getMessage(), thrown.getStackTrace(), sb,
                        Integer.MAX_VALUE);
                auditData.put(AUDIT_SNIPPET_ERROR, SchemaBootstrap.trimStringForTextFields(sb.toString()));

                // Ensure we have a transaction
                RetryingTransactionCallback<Map<String, Serializable>> auditCallback = new RetryingTransactionCallback<Map<String, Serializable>>() {
                    public Map<String, Serializable> execute() throws Throwable {
                        // Record thrown exceptions regardless of userFilter in case of failed authentication
                        // see MNT-11760
                        if (thrown instanceof AuthenticationException) {
                            return auditComponent.recordAuditValuesWithUserFilter(rootPath, auditData, false);
                        } else {
                            return auditComponent.recordAuditValues(rootPath, auditData);
                        }

                    }
                };
                try {
                    AuthenticationUtil.setFullAuthentication(authContext);
                    auditedData = transactionService.getRetryingTransactionHelper()
                            .doInTransaction(auditCallback, false, true);
                } finally {
                    AuthenticationUtil.clearCurrentSecurityContext();
                }

                // Done
                if (logger.isDebugEnabled() && auditedData.size() > 0) {
                    logger.debug("Audited after invocation: \n"
                            + (thrown == null ? "" : "   Exception: " + thrown.getMessage() + "\n")
                            + "   Values: " + auditedData);
                }
            }
        });
    } else {
        Map<String, Serializable> auditedData;
        // Add the "no error" indicator
        auditData.put(AUDIT_SNIPPET_NO_ERROR, null);
        // The current transaction will be fine
        auditedData = auditComponent.recordAuditValues(rootPath, auditData);

        // Done
        if (logger.isDebugEnabled() && auditedData.size() > 0) {
            logger.debug("Audited after invocation: \n"
                    + (thrown == null ? "" : "   Exception: " + thrown.getMessage() + "\n") + "   Values: "
                    + auditedData);
        }
    }
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * Creates an UnhandledException dialog.
 * @param message the string//from  ww  w  . j a v a2s  . c  o m
 */
/*public static void showUnhandledException(final String message)
{
UnhandledExceptionDialog dlg = instance.new UnhandledExceptionDialog(message);
dlg.setVisible(true);
throw new RuntimeException(message);
}*/

protected static boolean doesContain(final Throwable e, final String className, final String methodName) {
    for (StackTraceElement ste : e.getStackTrace()) {
        if (ste.getClassName().equals(className)
                && (methodName == null || ste.getMethodName().equals(methodName))) {
            return true;
        }
    }
    return false;
}

From source file:org.nanocom.console.Application.java

/**
 * Renders a caught exception.//from  ww w  .  java2 s .com
 *
 * @param e      An exception instance
 * @param output An OutputInterface instance
 */
public void renderException(Exception e, OutputInterface output) {
    Throwable t = e;
    do {
        String title = String.format("  [%s]  ", t.getClass().getSimpleName());
        int len = title.length();
        Integer width = getTerminalWidth();

        if (null == width) {
            width = Integer.MAX_VALUE;
        } else {
            width--;
        }

        List<String> lines = new ArrayList<String>();
        String[] splittedMessage = t.getMessage().split("\r?\n");

        for (String line : splittedMessage) {
            String[] lines2 = split(line, width - 4);
            for (String line2 : lines2) {
                lines.add(String.format("  %s  ", line2));
                len = Math.max(line2.length() + 4, len);
            }
        }

        List<String> messages = new ArrayList<String>();
        messages.add(repeat(" ", len));
        messages.add(title + repeat(" ", Math.max(0, len - title.length())));

        for (String line : lines) {
            messages.add(line + repeat(" ", len - line.length()));
        }

        messages.add(repeat(" ", len));

        output.writeln(EMPTY);
        output.writeln(EMPTY);

        for (String message : messages) {
            output.writeln(String.format("<error>%s</error>", message));
        }

        output.writeln(EMPTY);
        output.writeln(EMPTY);

        if (OutputInterface.VerbosityLevel.VERBOSE.equals(output.getVerbosity())) {
            output.writeln("<comment>Exception trace:</comment>");

            // exception related properties
            StackTraceElement[] trace = t.getStackTrace();
            StackTraceElement[] fullTrace = ArrayUtils
                    .addAll(new StackTraceElement[] { new StackTraceElement(EMPTY, trace[0].getMethodName(),
                            trace[0].getFileName(), trace[0].getLineNumber()) }, trace);

            int count = fullTrace.length;
            int i;
            for (i = 0; i < count; i++) {
                String clazz = null != fullTrace[i].getClassName() ? fullTrace[i].getClassName() : EMPTY;
                String function = fullTrace[i].getMethodName();
                String file = null != fullTrace[i].getFileName() ? fullTrace[i].getFileName() : "n/a";
                String line = String.valueOf(fullTrace[i].getLineNumber());

                output.writeln(String.format(" %s%s() at <info>%s:%s</info>", clazz, function, file, line));
            }

            output.writeln(EMPTY);
            output.writeln(EMPTY);
        }
    } while (null != (t = t.getCause()));

    if (null != runningCommand) {
        output.writeln(
                String.format("<info>%s</info>", String.format(runningCommand.getSynopsis(), getName())));
        output.writeln(EMPTY);
        output.writeln(EMPTY);
    }
}

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

private static String _doneRecursingForRootString(final Throwable lastt, final int numDeep,
        final StringBuffer buf, final boolean suffixClassChain, final List parentMsgs, final List parentTypes,
        final int includedParentMsgs, final boolean alsoStackTraces, final List parentStacktraces) {

    if (numDeep == 0) {
        return null; // *** EARLY RETURN ***
    }// w  ww. ja  va2 s.c  om

    if (numDeep == 1) {
        return buf.toString(); // *** EARLY RETURN ***
    }

    final String main = buf.toString();

    if (!suffixClassChain) {
        return main; // *** EARLY RETURN ***
    }

    final int numMsgs = parentMsgs.size();
    if (numMsgs != parentTypes.size()) {
        return main + "\n[[**** PROBLEM WITH ATTAINING CAUSE CHAIN: "
                + "parentMsgs and parentTypes sizes do not match ****]]";
    }

    final StringBuffer retbuf = new StringBuffer(main);
    retbuf.append("\n[[**** Cause chain report ****]]");

    for (int i = 0; i < numMsgs; i++) {
        retbuf.append("\n  ");
        for (int j = 0; j < i; j++) {
            retbuf.append(" ");
        }
        final String type = (String) parentTypes.get(i);
        retbuf.append("caused by (#").append(i + 1).append("): ").append(type);
    }
    retbuf.append("\n");

    int startIncluding = numMsgs - includedParentMsgs;
    if (startIncluding < 0) {
        startIncluding = 0;
    }

    for (int i = 0; i < numMsgs; i++) {
        if (i >= startIncluding) {
            retbuf.append("\n");
            final String msg = (String) parentMsgs.get(i);
            retbuf.append("Message for #").append(i + 1).append(":\n").append(msg);
            if (includedParentMsgs > 1) {
                retbuf.append("\n========================================");
            }

            if (alsoStackTraces) {

                final String thisTraceName = "Stacktrace for #" + (i + 1);

                retbuf.append("\n\n").append(thisTraceName).append(":\n").append(msg);

                final StackTraceElement[] traces = (StackTraceElement[]) parentStacktraces.get(i);

                if (traces == null || traces.length == 0) {
                    retbuf.append("     no stacktrace available (?)");
                } else {
                    for (int j = 0; j < traces.length; j++) {
                        final StackTraceElement trace = traces[j];
                        retbuf.append("\tat ").append(trace).append("\n");
                    }
                }

                retbuf.append("\n(END ").append(thisTraceName).append(")");

                if (includedParentMsgs > 1) {
                    retbuf.append("\n========================================");
                }
                retbuf.append("\n");
            }
        }
    }

    retbuf.append("\n\nOriginal message:\n").append(main);

    if (alsoStackTraces) {
        retbuf.append("\nStacktrace for original problem: ");
        if (lastt == null) {
            retbuf.append("     no throwable available (?)");
        } else {

            final StackTraceElement[] traces = lastt.getStackTrace();
            if (traces == null || traces.length == 0) {
                retbuf.append("     no stacktrace available (?)");
            } else {
                for (int j = 0; j < traces.length; j++) {
                    final StackTraceElement trace = traces[j];
                    retbuf.append("\tat ").append(trace).append("\n");
                }
            }
        }
        retbuf.append("\n(END stacktrace for original problem)");
    }

    retbuf.append("\n[[**** end of cause chain report ****]]\n\n");
    return retbuf.toString();
}

From source file:mesquite.lib.MesquiteModule.java

/** Reports crash or error to Mesquite server*/
public void reportCrashToHome(Throwable e, String s) {
    StackTraceElement[] stack = e.getStackTrace();
    String report = MesquiteException.lastLocMessage() + "\n";
    report += e + "\n";
    report += s + "\n";
    for (int i = 0; i < stack.length; i++)
        report += stack[i] + "\n";
    if (MainThread.emergencyCancelled)
        report += "\n\nEMERGENCY CANCELLED";

    report += "\n\n\n";
    report += logWindow.getText();/* w  ww .  jav  a 2 s .c om*/
    report += "\n\n\n";
    reportProblemToHome(report);
    MesquiteTrunk.errorReportedToHome = true;
}

From source file:de.decoit.visa.rdf.RDFManager.java

/**
 * Remove all named models and statements in the default model from the TDB
 * database and delete all uploaded source files. After cleaning up close
 * the connection to the TDB database./*w w w  .ja v a  2s . c om*/
 *
 * @throws IOException
 */
public void close() throws IOException {
    ds.begin(ReadWrite.WRITE);

    try {
        clearSourceFiles();

        // Remove all named models from the database that were not removed
        // by clearSourceFiles()
        Iterator<String> itNames = ds.listNames();
        ArrayList<String> names = new ArrayList<>();

        while (itNames.hasNext()) {
            names.add(itNames.next());
        }

        for (String n : names) {
            ds.removeNamedModel(n);
        }

        // Clear the default model
        ds.getDefaultModel().removeAll();

        ds.commit();
    } catch (Throwable ex) {
        StringBuilder sb = new StringBuilder("Caught: [");
        sb.append(ex.getClass().getSimpleName());
        sb.append("] ");
        sb.append(ex.getMessage());
        log.error(sb.toString());

        if (log.isDebugEnabled()) {
            for (StackTraceElement ste : ex.getStackTrace()) {
                log.debug(ste.toString());
            }
        }

        ds.abort();

        throw ex;
    } finally {
        ds.end();

        // Sync changes to disk
        TDB.sync(ds);

        // Close the TDB database connection
        ds.close();
    }
}

From source file:mesquite.lib.MesquiteModule.java

/** Displays an alert in connection to an exception*/
public void exceptionAlert(Throwable e, String s) {
    MesquiteTrunk.errorReportedDuringRun = true;
    StackTraceElement[] stt = e.getStackTrace();
    String rep = MesquiteException.lastLocMessage() + "\n";
    rep += getRootPath() + "\n";
    rep += e + "\n";
    rep += s + "\n";
    for (int i = 0; i < stt.length; i++)
        rep += stt[i] + "\n";
    s = rep;//from w w  w . ja v  a 2  s .  c  o m
    MesquiteDialog.cleanUpWizard();
    Thread t = Thread.currentThread();
    if (t instanceof MesquiteThread)
        ((MesquiteThread) t).doCleanUp();
    logln(s);
    if (!PhoneHomeUtil.phoneHomeSuccessful || !MesquiteTrunk.reportErrors
            || MesquiteTrunk.suppressErrorReporting) {
        if (!MesquiteThread.isScripting()
                && !AlertDialog.query(containerOfModule(), "Crash", s, "OK", "Force Quit"))
            MesquiteTrunk.mesquiteTrunk.exit(true, 0);
        return;
    }
    if (MesquiteThread.isScripting()) {
        return;
    }
    String addendum = "";
    if (isNonReportable(e)) {
        StackTraceElement[] stack = e.getStackTrace();
        String report = MesquiteException.lastLocMessage() + "\n";
        report += e + "\n";
        report += s + "\n";
        for (int i = 0; i < stack.length; i++)
            report += stack[i] + "\n";
        logln(report);
    } else if (MainThread.emergencyCancelled || MesquiteTrunk.errorReportedToHome) {// if emergency cancelled, reporting suppressed because silly user didn't restart!  Also, only one report per run.
        if (!MesquiteThread.isScripting()
                && !AlertDialog.query(containerOfModule(), "Crash", s, "OK", "Force Quit"))
            MesquiteTrunk.mesquiteTrunk.exit(true, 0);

    } else {
        int resp = AlertDialog.query(containerOfModule(), "Crash", s
                + "\n\nPlease send a report of this crash to the Mesquite server, to help us debug it and improve Mesquite.  None of your data will be sent, but your log file up to this point will be sent."
                + addendum, "OK, Send Report and Continue", "OK, Send and Force Quit", "Close without sending");
        if (resp < 2)
            reportCrashToHome(e, s);
        if (resp == 1)
            MesquiteTrunk.mesquiteTrunk.exit(true, 0);
    }
}

From source file:net.cbtltd.rest.nextpax.A_Handler.java

/**
 * Transfer accommodation products.// w  ww . j  a v a 2s.c  o  m
 * 
 * @param sqlSession the current SQL session.
 */
@Override
public synchronized void readProducts() {
    String message = "Read Products started NextpaxAPIKey: " + getApikey();
    LOG.debug(message);
    Date version = new Date();
    HashSet<String> productsProceeded = new HashSet<String>();

    try {
        createOrUpdateProducts(productsProceeded);
        /*LOG.debug("NextpaxAPIKEY: " + getApikey() + " Products update done.");
        readHousePropertyCodes();
        LOG.debug("NextpaxAPIKEY: " + getApikey() + " readHousePropertyCodes() done.");
        updateInactiveProducts(productsProceeded);
        // readDescriptions();
        // LOG.debug("NextpaxAPIKEY: "+getApikey()+" readDescriptions(); done.");
        // update/create images.
        // createImages();
        // readImages();
        // setLocation();
        // LOG.debug("NextpaxAPIKEY: "+getApikey()+" setLocation done.");
        LOG.debug("NextpaxAPIKEY: " + getApikey() + " ReadProducts_DONE");
        MonitorService.monitor(message, version);*/
    } catch (Throwable x) {
        LOG.error(x.getStackTrace());
    }
}

From source file:org.kuali.test.utils.Utils.java

public static String getStackTraceOutput(Throwable t) {
    StringBuilder retval = new StringBuilder(1024);

    retval.append(t.toString());//w ww  .j  a va2  s .c  o  m
    retval.append("\n----------------------------------------------------------------\n");
    for (StackTraceElement st : t.getStackTrace()) {
        retval.append(st.toString());
        retval.append("\n");
    }

    if (t.getCause() != null) {
        retval.append("Cause: ");
        retval.append(t.toString());
        retval.append("\n----------------------------------------------------------------\n");

        for (StackTraceElement st : t.getCause().getStackTrace()) {
            retval.append(st.toString());
            retval.append("\n");
        }
    }

    return retval.toString();
}

From source file:at.gv.egiz.pdfas.web.servlets.ErrorPage.java

protected void process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (PdfAsHelper.getFromDataUrl(request)) {
        // redirect to here!
        response.sendRedirect(PdfAsHelper.generateErrorURL(request, response));
        return;//w  ww.j a  v a2  s .  co  m
    } else {
        String errorURL = PdfAsHelper.getErrorURL(request, response);
        Throwable e = PdfAsHelper.getSessionException(request, response);

        StatisticEvent statisticEvent = PdfAsHelper.getStatisticEvent(request, response);
        if (statisticEvent != null) {
            if (!statisticEvent.isLogged()) {
                statisticEvent.setStatus(Status.ERROR);
                statisticEvent.setException(e);
                if (e instanceof PDFASError) {
                    statisticEvent.setErrorCode(((PDFASError) e).getCode());
                }
                statisticEvent.setEndNow();
                statisticEvent.setTimestampNow();
                StatisticFrontend.getInstance().storeEvent(statisticEvent);
                statisticEvent.setLogged(true);
            }
        }

        String message = PdfAsHelper.getSessionErrMessage(request, response);
        if (errorURL != null && WebConfiguration.isProvidePdfURLinWhitelist(errorURL)) {
            String template = PdfAsHelper.getErrorRedirectTemplateSL();

            URL url = new URL(errorURL);
            String errorURLProcessed = url.getProtocol() + "://" + // "http" + "://
                    url.getHost() + // "myhost"
                    ":" + // ":"
                    url.getPort() + // "8080"
                    url.getPath();

            template = template.replace("##ERROR_URL##", errorURLProcessed);

            String extraParams = UrlParameterExtractor.buildParameterFormString(url);
            template = template.replace("##ADD_PARAMS##", extraParams);

            String target = PdfAsHelper.getInvokeTarget(request, response);

            if (target == null) {
                target = "_self";
            }

            template = template.replace("##TARGET##", StringEscapeUtils.escapeHtml4(target));

            if (e != null && WebConfiguration.isShowErrorDetails()) {
                template = template.replace("##CAUSE##", URLEncoder.encode(e.getMessage(), "UTF-8"));
            } else {
                template = template.replace("##CAUSE##", "");
            }
            if (message != null) {
                template = template.replace("##ERROR##", URLEncoder.encode(message, "UTF-8"));
            } else {
                template = template.replace("##ERROR##", "Unbekannter Fehler");
            }
            response.setContentType("text/html");
            response.getWriter().write(template);
            response.getWriter().close();
        } else {
            if (errorURL != null) {
                logger.warn(errorURL + " is not allowed by whitelist");
            }

            String template = PdfAsHelper.getErrorTemplate();
            if (message != null) {
                template = template.replace(ERROR_MESSAGE, message);
            } else {
                template = template.replace(ERROR_MESSAGE, "Unbekannter Fehler");
            }

            if (e != null && WebConfiguration.isShowErrorDetails()) {
                template = template.replace(ERROR_STACK, HTMLFormater.formatStackTrace(e.getStackTrace()));
            } else {
                template = template.replace(ERROR_STACK, "");
            }

            response.setContentType("text/html");
            response.getWriter().write(template);
            response.getWriter().close();
        }
    }
}