Example usage for java.lang StackTraceElement toString

List of usage examples for java.lang StackTraceElement toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of this stack trace element.

Usage

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

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

    retval.append(t.toString());//  ww  w  . j ava2s  . co 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:org.openmrs.module.privilegehelper.PrivilegeLogger.java

/**
 * Inspects the stack trace to find a place where the privilege was checked
 * //from   w ww  .  j  av a  2  s .  co m
 * @return the class.method or <code>null</code> if it cannot be found
 */
private StackTraceInfo inspectStackTrace() {
    final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    boolean requiredPrivilege = false;
    for (int i = 0; i < stackTrace.length; i++) {
        final StackTraceElement unrelatedElement = stackTrace[i];

        if (UserContext.class.getName().equals(unrelatedElement.getClassName())
                && "hasPrivilege".equals(unrelatedElement.getMethodName())) {

            for (int j = i + 1; j < stackTrace.length; j++) {
                final StackTraceElement element = stackTrace[j];

                if (element.getFileName() != null && element.getFileName().endsWith("_jsp")) {
                    String jsp = element.getFileName();
                    int indexOfView = jsp.indexOf("view");
                    if (indexOfView > 0) {
                        jsp = jsp.substring(indexOfView);
                    }
                    jsp = jsp.replace(".", "/");
                    jsp = jsp.replace("_", ".");

                    return new StackTraceInfo(jsp, requiredPrivilege);
                }

                if (!element.getClassName().startsWith("org.openmrs")) {
                    continue;
                }

                //Determine if it is a required privilege or a simple check
                if (RequireTag.class.getName().equals(element.getClassName())) {
                    requiredPrivilege = true;
                    continue;
                }
                if (PrivilegeTag.class.getName().equals(element.getClassName())) {
                    requiredPrivilege = false;
                    continue;
                }
                if (AuthorizationAdvice.class.getName().equals(element.getClassName())) {
                    requiredPrivilege = true;
                    continue;
                }
                if (Context.class.getName().equals(element.getClassName())) {
                    if ("requirePrivilege".equals(element.getMethodName())) {
                        requiredPrivilege = true;
                    }
                    continue;
                }

                try {
                    final Class<?> clazz = OpenmrsClassLoader.getInstance().loadClass(element.getClassName());

                    if (clazz.isAnnotationPresent(Controller.class)) {
                        String url = "";

                        final RequestMapping clazzRequestMapping = clazz.getAnnotation(RequestMapping.class);
                        if (clazzRequestMapping != null) {
                            url = clazzRequestMapping.value()[0];
                        }

                        final Method[] methods = clazz.getMethods();
                        for (Method method : methods) {
                            if (method.getName().equals(element.getMethodName())) {
                                final RequestMapping requestMapping = method
                                        .getAnnotation(RequestMapping.class);
                                if (requestMapping != null) {
                                    url += requestMapping.value()[0];
                                }
                                break;
                            }
                        }

                        if (url.isEmpty()) {
                            return new StackTraceInfo(element.toString(), requiredPrivilege);
                        } else {
                            return new StackTraceInfo(element.toString() + ", URL: " + url, requiredPrivilege);
                        }
                    }
                } catch (ClassNotFoundException e) {
                }

                return new StackTraceInfo(element.toString(), requiredPrivilege);
            }
        }
    }
    return null;
}

From source file:org.infoglue.deliver.util.CacheController.java

private static void printThreads() {
    ThreadGroup tg = Thread.currentThread().getThreadGroup();
    int n = tg.activeCount();
    logger.warn("Number of active threads: " + n);
    Thread[] threadArray = new Thread[n];
    n = tg.enumerate(threadArray, false);
    for (int i = 0; i < n; i++) {
        String currentThreadId = "" + threadArray[i].getId();
        Thread t = threadArray[i];
        Map stacks = t.getAllStackTraces();

        Iterator stacksIterator = stacks.values().iterator();
        while (stacksIterator.hasNext()) {
            StackTraceElement[] el = (StackTraceElement[]) stacksIterator.next();

            String stackString = "";
            if (el != null && el.length != 0) {
                for (int j = 0; j < el.length; j++) {
                    StackTraceElement frame = el[j];
                    if (frame == null)
                        stackString += "    null stack frame" + "<br/>";
                    else
                        stackString += "    null stack frame" + frame.toString() + "<br/>";
                }//from www  .  j av  a  2s .  co  m
                logger.warn("\n\nThreads:\n\n " + stackString);
            }
        }
    }
}

From source file:pcgen.gui2.facade.CharacterFacadeImpl.java

/**
 * @see pcgen.facade.core.CharacterFacade#export(ExportHandler, BufferedWriter)
 *//*  w  w  w  . j  av a2  s . c  o m*/
@Override
public void export(ExportHandler theHandler, BufferedWriter buf) throws ExportException {
    final int maxRetries = 3;
    for (int i = 0; i < maxRetries; i++) {
        try {
            Logging.log(Logging.DEBUG, "Starting export at serial " + theCharacter.getSerial() + " to "
                    + theHandler.getTemplateFile());
            PlayerCharacter exportPc = getExportCharacter();
            theHandler.write(exportPc, buf);
            Logging.log(Logging.DEBUG, "Finished export at serial " + theCharacter.getSerial() + " to "
                    + theHandler.getTemplateFile());
            return;
        } catch (ConcurrentModificationException e) {
            Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
            for (Entry<Thread, StackTraceElement[]> threadEntry : allStackTraces.entrySet()) {
                if (threadEntry.getValue().length > 1) {
                    StringBuilder sb = new StringBuilder("Thread: " + threadEntry.getKey() + "\n");
                    for (StackTraceElement elem : threadEntry.getValue()) {
                        sb.append("  ");
                        sb.append(elem.toString());
                        sb.append("\n");
                    }
                    Logging.log(Logging.INFO, sb.toString());
                }
            }
            Logging.log(Logging.WARNING, "Retrying export after ConcurrentModificationException", e);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                Logging.errorPrint("Interrupted sleep - probably closing.");
                return;

            }
        }
    }
    Logging.errorPrint(
            "Unable to export using " + theHandler.getTemplateFile() + " due to concurrent modifications.");
}

From source file:org.apache.hadoop.hbase.coprocessor.transactional.SsccRegionEndpoint.java

/**
 * Formats the throwable stacktrace to a string
 * @param Throwable e// ww  w .  j av  a  2 s  . c  o  m
 * @return String 
 */
public String stackTraceToString(Throwable e) {
    StringBuilder sb = new StringBuilder();
    for (StackTraceElement element : e.getStackTrace()) {
        sb.append(element.toString());
        sb.append("\n");
    }
    return sb.toString();
}

From source file:org.tranche.get.GetFileToolUtil.java

/**
 * <p>Registers a failed download only if configured to do so.</p>
 * @param gft//from w  ww  . ja va2 s  . c om
 * @param report
 */
public static void registerFailedDownload(final GetFileTool gft, final GetFileToolReport report) {
    // no tests
    if (TestUtil.isTesting() || !report.isFailed()) {
        return;
    }

    try {
        String[] emailRecipients = ConfigureTranche.getAdminEmailAccounts();
        String subject = "["
                + ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_NAME)
                + "] Failed Download @ " + TextUtil.getFormattedDate(TimeUtil.getTrancheTimestamp());

        StringBuffer message = new StringBuffer();
        message.append("A download failed @ " + TextUtil.getFormattedDate(TimeUtil.getTrancheTimestamp())
                + " on " + ConfigureTranche.get(ConfigureTranche.CATEGORY_GENERAL, ConfigureTranche.PROP_NAME)
                + "\n\n");
        message.append(
                "--------------------------------------------------------------------------------------------\n");
        for (PropagationExceptionWrapper pew : report.getFailureExceptions()) {
            message.append(pew.toString() + "\n");
            for (StackTraceElement ste : pew.exception.getStackTrace()) {
                message.append("    " + ste + "\n");
            }
            message.append("\n");
        }
        message.append(
                "--------------------------------------------------------------------------------------------\n");
        message.append("\n");
        if (gft.getMetaData() != null && gft.getMetaData().getDataSetName() != null) {
            message.append("Title: " + gft.getMetaData().getDataSetName() + "\n");
        }
        message.append("Hash: " + gft.getHash().toString() + "\n");
        message.append("Using passphrase?: " + String.valueOf(gft.getPassphrase() != null) + "\n");

        File tempFile = null;
        try {
            tempFile = LogUtil.getTroubleshootingInformationFile();

            if (gft.getFailedChunksListener() != null) {

                BufferedWriter writer = null;
                try {
                    writer = new BufferedWriter(new FileWriter(tempFile, true));
                    GetFileToolFailedChunksListener failedChunksListener = gft.getFailedChunksListener();

                    // Any missing meta data chunks
                    int missingMDSize = failedChunksListener.getMissingMetaDataChunks().size();
                    if (missingMDSize > 0) {
                        writer.write("* Data set missing " + missingMDSize + " meta chunk"
                                + (missingMDSize == 1 ? "" : "s") + ":");
                        writer.newLine();
                        for (BigHash metaHash : failedChunksListener.getMissingMetaDataChunks()) {
                            writer.write("    - " + metaHash);
                            writer.newLine();
                        }
                    } else {
                        writer.write("* Data set not missing any meta data chunks.");
                        writer.newLine();
                    }
                    writer.newLine();

                    // Any missing data chunks
                    int missingDataChunksSize = 0,
                            missingFromFiles = failedChunksListener.getMissingDataChunks().size();

                    if (missingFromFiles > 0) {
                        for (BigHash metaHash : failedChunksListener.getMissingDataChunks().keySet()) {
                            Set<BigHash> dataChunks = failedChunksListener.getMissingDataChunks().get(metaHash);
                            missingDataChunksSize += dataChunks.size();
                        }

                        writer.write("A total of " + missingDataChunksSize + " data chunks missing in "
                                + missingFromFiles + " files:");
                        writer.newLine();

                        for (BigHash metaHash : failedChunksListener.getMissingDataChunks().keySet()) {
                            Set<BigHash> dataChunks = failedChunksListener.getMissingDataChunks().get(metaHash);
                            writer.write("    - File: " + metaHash);
                            writer.newLine();

                            for (BigHash dataHash : dataChunks) {
                                writer.write("        -> " + dataHash);
                                writer.newLine();
                            }
                        }
                    } else {
                        writer.write(
                                "* No missing data chunks were reported. (Note: data chunks might be missing and not reported because associated meta data not found.)");
                        writer.newLine();
                    }

                    writer.newLine();
                    writer.newLine();

                } finally {
                    IOUtil.safeClose(writer);
                }
            }

            EmailUtil.sendEmailHttp(subject, emailRecipients, message.toString(), tempFile);
        } finally {
            IOUtil.safeDelete(tempFile);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    final String logFailureURL = ConfigureTranche.get(ConfigureTranche.CATEGORY_LOGGING,
            ConfigureTranche.PROP_LOG_DOWNLOAD_FAILURE);
    if (logFailureURL == null || logFailureURL.equals("")) {
        return;
    }

    try {
        // make a new client
        HttpClient c = new HttpClient();
        PostMethod pm = new PostMethod(logFailureURL);

        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("hash", Base16.encode(gft.getHash().toByteArray())));

        // TODO: remove these in the registration script
        params.add(new NameValuePair("username", ""));
        params.add(new NameValuePair("toolType", ""));

        // TODO: refactor registration script to allow for multiple exceptions
        String exceptionName = "";
        String exceptionMessage = "";
        String exceptionStack = "";
        if (!report.getFailureExceptions().isEmpty()) {
            for (PropagationExceptionWrapper pew : report.getFailureExceptions()) {
                exceptionName = pew.exception.getClass().getName();
                exceptionMessage = pew.exception.getMessage();
                for (StackTraceElement ste : pew.exception.getStackTrace()) {
                    exceptionStack = exceptionStack + ste.toString() + "\n";
                }
            }
        }

        params.add(new NameValuePair("exceptionName", exceptionName == null ? "" : exceptionName));
        params.add(new NameValuePair("exceptionMessage", exceptionMessage == null ? "" : exceptionMessage));
        params.add(new NameValuePair("exceptionStack", exceptionStack == null ? "" : exceptionStack));
        params.add(new NameValuePair("buildNumber", "@buildNumber"));
        params.add(new NameValuePair("timestamp", String.valueOf(report.getTimestampEnd())));
        pm.setRequestBody(params.toArray(new NameValuePair[0]));

        // best effort, do not print anything
        c.executeMethod(pm);
    } catch (Exception e) {
        e.printStackTrace();
    }
}