Example usage for java.lang Throwable printStackTrace

List of usage examples for java.lang Throwable printStackTrace

Introduction

In this page you can find the example usage for java.lang Throwable printStackTrace.

Prototype

public void printStackTrace(PrintWriter s) 

Source Link

Document

Prints this throwable and its backtrace to the specified print writer.

Usage

From source file:gov.nih.nci.cadsr.cadsrpasswordchange.core.CommonUtil.java

public static String toString(Throwable theException) {
    // Create a StringWriter and a PrintWriter both of these object
    // will be used to convert the data in the stack trace to a string.
    ////from  ww  w.  ja v a 2 s.  c  om
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);

    //
    // Instead of writting the stack trace in the console we write it
    // to the PrintWriter, to get the stack trace message we then call
    // the toString() method of StringWriter.
    //
    theException.printStackTrace(pw);

    return sw.toString();

}

From source file:com.googlecode.dex2jar.v3.Main.java

public static void niceExceptionMessage(Throwable t, int deep) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < deep + 1; i++) {
        sb.append(".");
    }/*from w ww. j  a v a  2 s .c o  m*/
    sb.append(' ');
    if (t instanceof DexException) {
        sb.append(t.getMessage());
        System.err.println(sb.toString());
        if (t.getCause() != null) {
            niceExceptionMessage(t.getCause(), deep + 1);
        }
    } else {
        if (t != null) {
            System.err.println(sb.append("ROOT cause:").toString());
            t.printStackTrace(System.err);
        }
    }
}

From source file:com.zimbra.cs.index.LuceneViewer.java

private static void doCheck(CommandLine cl) throws Exception {
    Console console = new Console(cl.hasOption(CLI.O_VERBOSE));

    String indexDir = cl.getOptionValue(CLI.O_INPUT);
    console.info("Checking index " + indexDir);

    Directory dir = null;//  w w  w.  ja  v a2s .c  o  m
    try {
        dir = LuceneDirectory.open(new File(indexDir));
    } catch (Throwable t) {
        console.info("ERROR: could not open directory \"" + indexDir + "\"; exiting");
        t.printStackTrace(System.out);
        System.exit(1);
    }

    CheckIndex checker = new CheckIndex(dir);
    checker.setInfoStream(System.out);

    Status result = checker.checkIndex();
    console.info("Result:" + (result.clean ? "clean" : "not clean"));
}

From source file:ome.formats.importer.util.ErrorHandler.java

/**
 * Return stack trace from throwable//from   w w w .j a  v  a2 s.  c om
 * @param throwable
 * @return stack trace
 */
public static String getStackTrace(Throwable throwable) {
    final Writer writer = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(writer);
    throwable.printStackTrace(printWriter);
    return writer.toString();
}

From source file:com.nary.Debug.java

public static String getStackTraceAsString(Throwable t) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    t.printStackTrace(pw);
    pw.close();// w w w.  j a  v  a2  s  . c  o  m
    return sw.toString();
}

From source file:com.cloud.utils.script.Script.java

static String stackTraceAsString(Throwable throwable) {
    //TODO: a StringWriter is bit to heavy weight
    try (StringWriter out = new StringWriter(); PrintWriter writer = new PrintWriter(out);) {
        throwable.printStackTrace(writer);
        return out.toString();
    } catch (IOException e) {
        return "";
    }/*ww w .jav  a  2 s  .com*/
}

From source file:azkaban.common.utils.Utils.java

public static String stackTrace(Throwable t) {
    if (t == null) {
        return "Utils.stackTrace(...) -- Throwable was null.";
    }/*from   w w w  .ja  va  2 s .c o  m*/
    StringWriter writer = new StringWriter();
    t.printStackTrace(new PrintWriter(writer));
    return writer.toString();
}

From source file:de.codesourcery.jasm16.ide.ui.utils.UIUtils.java

public static void showErrorDialog(Component parent, String title, String textMessage, Throwable cause) {
    final String stacktrace;
    if (cause == null) {
        stacktrace = null;//from  w w w  . j  a  v  a2 s .c om
    } else {
        final ByteArrayOutputStream stackTrace = new ByteArrayOutputStream();
        cause.printStackTrace(new PrintStream(stackTrace));
        stacktrace = new String(stackTrace.toByteArray());
    }

    final JDialog dialog = new JDialog((Window) null, title);

    dialog.setModal(true);

    final JTextArea message = createMultiLineLabel(textMessage);
    final DialogResult[] outcome = { DialogResult.CANCEL };

    final JButton okButton = new JButton("Ok");
    okButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            outcome[0] = DialogResult.YES;
            dialog.dispose();
        }
    });

    final JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout());
    buttonPanel.add(okButton);

    final JPanel messagePanel = new JPanel();
    messagePanel.setLayout(new GridBagLayout());

    GridBagConstraints cnstrs = constraints(0, 0, true, true, GridBagConstraints.BOTH);
    cnstrs.weightx = 1;
    cnstrs.weighty = 0.1;
    cnstrs.gridheight = 1;
    messagePanel.add(message, cnstrs);

    if (stacktrace != null) {
        final JTextArea createMultiLineLabel = new JTextArea(stacktrace);

        createMultiLineLabel.setBackground(null);
        createMultiLineLabel.setEditable(false);
        createMultiLineLabel.setBorder(null);
        createMultiLineLabel.setLineWrap(false);
        createMultiLineLabel.setWrapStyleWord(false);

        final JScrollPane pane = new JScrollPane(createMultiLineLabel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        cnstrs = constraints(0, 1, true, true, GridBagConstraints.BOTH);
        cnstrs.weightx = 1.0;
        cnstrs.weighty = 0.9;
        cnstrs.gridwidth = GridBagConstraints.REMAINDER;
        cnstrs.gridheight = GridBagConstraints.REMAINDER;
        messagePanel.add(pane, cnstrs);
    }

    final JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());

    cnstrs = constraints(0, 0, true, false, GridBagConstraints.BOTH);
    cnstrs.gridwidth = GridBagConstraints.REMAINDER;
    cnstrs.gridheight = 1;
    cnstrs.weighty = 1.0;
    cnstrs.insets = new Insets(5, 2, 5, 2); // top,left,bottom,right           
    panel.add(messagePanel, cnstrs);

    cnstrs = constraints(0, 1, true, true, GridBagConstraints.HORIZONTAL);
    cnstrs.gridwidth = GridBagConstraints.REMAINDER;
    cnstrs.gridheight = 1;
    cnstrs.weighty = 0;
    cnstrs.insets = new Insets(0, 2, 10, 2); // top,left,bottom,right      
    panel.add(buttonPanel, cnstrs);

    dialog.getContentPane().add(panel);

    dialog.setMinimumSize(new Dimension(600, 400));
    dialog.setPreferredSize(new Dimension(600, 400));
    dialog.setMaximumSize(new Dimension(600, 400));

    dialog.pack();
    dialog.setVisible(true);
}

From source file:Main.java

/**
 * Like {@link #sprintFullStack(Throwable)}, renders a stacktrace as a String for logging,
 * but excludes stack trace elements common with the calling scope, which may
 * be considered irrelevant to application functionality testing
 * @param t an exception// w w w . j  a va 2 s.  c  o  m
 * @return a string representation of a shorter stack trace
 */
public static String sprintShortStack(final Throwable t) {
    if (t == null) {
        return "";
    }

    StringWriter writer = new StringWriter();
    Throwable local = new Throwable();

    StackTraceElement[] localStack = local.getStackTrace();
    StackTraceElement[] tStack = t.getStackTrace();

    int m = tStack.length - 1, n = localStack.length - 1;
    while (m >= 0 && n >= 0 && tStack[m].equals(localStack[n])) {
        m--;
        n--;
    }

    int framesInCommon = tStack.length - 1 - (m + 1);

    t.setStackTrace(Arrays.copyOf(t.getStackTrace(), m + 1, StackTraceElement[].class));
    t.printStackTrace(new PrintWriter(writer));
    t.setStackTrace(tStack);
    StringBuilder sb = new StringBuilder(writer.toString());
    if (framesInCommon != 0) {
        sb.append("\t... " + framesInCommon + " more");
    }
    return sb.toString();
}

From source file:MailHandlerDemo.java

/**
 * Used debug problems with the logging.properties. The system property
 * java.security.debug=access,stack can be used to trace access to the
 * LogManager reset.// w w w . j a va  2s .com
 *
 * @param prefix a string to prefix the output.
 * @param err any PrintStream or null for System.out.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private static void checkConfig(String prefix, PrintStream err) {
    if (prefix == null || prefix.trim().length() == 0) {
        prefix = "DEBUG";
    }

    if (err == null) {
        err = System.out;
    }

    try {
        err.println(prefix + ": java.version=" + System.getProperty("java.version"));
        err.println(prefix + ": LOGGER=" + LOGGER.getLevel());
        err.println(prefix + ": JVM id " + ManagementFactory.getRuntimeMXBean().getName());
        err.println(prefix + ": java.security.debug=" + System.getProperty("java.security.debug"));
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            err.println(prefix + ": SecurityManager.class=" + sm.getClass().getName());
            err.println(prefix + ": SecurityManager classLoader=" + toString(sm.getClass().getClassLoader()));
            err.println(prefix + ": SecurityManager.toString=" + sm);
        } else {
            err.println(prefix + ": SecurityManager.class=null");
            err.println(prefix + ": SecurityManager.toString=null");
            err.println(prefix + ": SecurityManager classLoader=null");
        }

        String policy = System.getProperty("java.security.policy");
        if (policy != null) {
            File f = new File(policy);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        }

        LogManager manager = LogManager.getLogManager();
        String key = "java.util.logging.config.file";
        String cfg = System.getProperty(key);
        if (cfg != null) {
            err.println(prefix + ": " + cfg);
            File f = new File(cfg);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        } else {
            err.println(prefix + ": " + key + " is not set as a system property.");
        }
        err.println(prefix + ": LogManager.class=" + manager.getClass().getName());
        err.println(prefix + ": LogManager classLoader=" + toString(manager.getClass().getClassLoader()));
        err.println(prefix + ": LogManager.toString=" + manager);
        err.println(prefix + ": MailHandler classLoader=" + toString(MailHandler.class.getClassLoader()));
        err.println(
                prefix + ": Context ClassLoader=" + toString(Thread.currentThread().getContextClassLoader()));
        err.println(prefix + ": Session ClassLoader=" + toString(Session.class.getClassLoader()));
        err.println(prefix + ": DataHandler ClassLoader=" + toString(DataHandler.class.getClassLoader()));

        final String p = MailHandler.class.getName();
        key = p.concat(".mail.to");
        String to = manager.getProperty(key);
        err.println(prefix + ": TO=" + to);
        if (to != null) {
            err.println(prefix + ": TO=" + Arrays.toString(InternetAddress.parse(to, true)));
        }

        key = p.concat(".mail.from");
        String from = manager.getProperty(key);
        if (from == null || from.length() == 0) {
            Session session = Session.getInstance(new Properties());
            InternetAddress local = InternetAddress.getLocalAddress(session);
            err.println(prefix + ": FROM=" + local);
        } else {
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, false)));
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, true)));
        }

        synchronized (manager) {
            final Enumeration<String> e = manager.getLoggerNames();
            while (e.hasMoreElements()) {
                final Logger l = manager.getLogger(e.nextElement());
                if (l != null) {
                    final Handler[] handlers = l.getHandlers();
                    if (handlers.length > 0) {
                        err.println(prefix + ": " + l.getClass().getName() + ", " + l.getName());
                        for (Handler h : handlers) {
                            err.println(prefix + ":\t" + toString(prefix, err, h));
                        }
                    }
                }
            }
        }
    } catch (Throwable error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }
    err.flush();
}