001/*
002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     bstefanescu
016 */
017package org.nuxeo.shell.cmds;
018
019import java.io.PrintWriter;
020import java.io.StringWriter;
021
022import org.nuxeo.shell.Command;
023import org.nuxeo.shell.Context;
024import org.nuxeo.shell.Shell;
025
026/**
027 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
028 */
029@Command(name = "trace", help = "Print the last error stack trace if any")
030public class Trace implements Runnable {
031
032    @Context
033    protected Shell shell;
034
035    public void run() {
036        Throwable t = (Throwable) shell.getProperty("last.error");
037        if (t != null) {
038            shell.getConsole().println();
039            shell.getConsole().println(getStackTrace(t));
040        } else {
041            shell.getConsole().println("No stack trace to print");
042        }
043    }
044
045    public static String getStackTrace(Throwable t) {
046        StringWriter sw = new StringWriter();
047        PrintWriter pw = new PrintWriter(sw);
048        t.printStackTrace(pw);
049        if (t.getCause() != null && t.getCause().getClass().getName().endsWith(".RemoteException")) {
050            pw.println("Dumping remote stack trace:");
051            t.getCause().printStackTrace(pw);
052        }
053        pw.close();
054        return sw.getBuffer().toString();
055    }
056}