Example usage for java.lang Throwable toString

List of usage examples for java.lang Throwable toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.cloud.utils.StringUtils.java

public static String getExceptionStackInfo(final Throwable e) {
    final StringBuffer sb = new StringBuffer();

    sb.append(e.toString()).append("\n");
    final StackTraceElement[] elemnents = e.getStackTrace();
    for (final StackTraceElement element : elemnents) {
        sb.append(element.getClassName()).append(".");
        sb.append(element.getMethodName()).append("(");
        sb.append(element.getFileName()).append(":");
        sb.append(element.getLineNumber()).append(")");
        sb.append("\n");
    }//  www  . j  ava 2 s  . com

    return sb.toString();
}

From source file:apm.common.utils.StringUtils.java

public static String traceExceptionMessage(Object source, Throwable e) {
    String newLine = System.getProperty("line.separator");
    StringBuffer exceptionInfo_sb = new StringBuffer(source.toString());
    exceptionInfo_sb.append(newLine + e.toString());
    StackTraceElement[] trace = e.getStackTrace();
    for (int i = 0; i < trace.length; i++) {
        exceptionInfo_sb.append(newLine + "\tat " + trace[i]);
    }//www.ja  v  a2 s .  c  o m
    return exceptionInfo_sb.toString();
}

From source file:com.quinsoft.zeidon.ZeidonException.java

/**
 * Wraps 't' with a ZeidonException and changes the call stack for the ZeidonException to
 * match 't'.  This is mostly used to re-throw checked exceptions as unchecked ones.
 *
 * @param t//from   w  ww.j  a v a 2 s. c o m
 * @return
 */
public static ZeidonException wrapException(Throwable t) {
    // If this is already a ZeidonException then we don't need to wrap it.
    if (t instanceof ZeidonException)
        return (ZeidonException) t;

    ZeidonException ze = new ZeidonException(t, t.toString());
    ze.setStackTrace(t.getStackTrace());
    return ze;
}

From source file:fr.xebia.audit.AuditAspect.java

protected static void appendThrowableCauses(Throwable throwable, String separator, StringBuilder toAppendTo) {
    List<Throwable> alreadyAppendedThrowables = new ArrayList<Throwable>();

    while (throwable != null) {
        // append
        toAppendTo.append(throwable.toString());
        alreadyAppendedThrowables.add(throwable);

        // cause/*from w w  w. j  a v a 2 s  . c  om*/
        Throwable cause = throwable.getCause();
        if (cause == null || alreadyAppendedThrowables.contains(cause)) {
            break;
        } else {
            throwable = cause;
            toAppendTo.append(separator);
        }
    }
}

From source file:com.aptana.core.epl.downloader.RepositoryStatusHelper.java

@SuppressWarnings("rawtypes")
public static Throwable unwind(Throwable t) {
    for (;;) {/*ww w.ja  va  2  s . com*/
        Class tc = t.getClass();

        // We don't use instanceof operator since we want
        // the explicit class, not subclasses.
        //
        if (tc != RuntimeException.class && tc != InvocationTargetException.class && tc != IOException.class)
            break;

        Throwable cause = t.getCause();
        if (cause == null)
            break;

        String msg = t.getMessage();
        if (msg != null && !msg.equals(cause.toString()))
            break;

        t = cause;
    }
    return t;
}

From source file:com.aptana.core.epl.downloader.RepositoryStatusHelper.java

private static void deeplyPrint(IStatus status, PrintStream strm, boolean stackTrace, int level) {
    appendLevelString(strm, level);/* w w  w  . j ava 2  s .  c  om*/
    String msg = status.getMessage();
    strm.println(msg);
    Throwable cause = status.getException();
    if (cause != null) {
        strm.print("Caused by: "); //$NON-NLS-1$
        if (stackTrace || !(msg.equals(cause.getMessage()) || msg.equals(cause.toString())))
            deeplyPrint(cause, strm, stackTrace, level);
    }

    if (status.isMultiStatus()) {
        IStatus[] children = status.getChildren();
        for (int i = 0; i < children.length; i++)
            deeplyPrint(children[i], strm, stackTrace, level + 1);
    }
}

From source file:eu.delving.services.core.Harvindexer.java

private static String exceptionToErrorString(HarvindexingException exception) {
    StringBuilder out = new StringBuilder();
    out.append(exception.getMessage());/*from  ww  w .  ja v  a  2 s  .  co m*/
    Throwable cause = exception.getCause();
    while (cause != null) {
        out.append('\n');
        out.append(cause.toString());
        cause = cause.getCause();
    }
    return out.toString();
}

From source file:de.dal33t.powerfolder.PowerFolder.java

/**
 * Starts a PowerFolder controller with the given command line arguments
 *
 * @param args/*from   w  w w.  j a v  a2  s . c o  m*/
 */
public static void startPowerFolder(String[] args) {

    // Touch Logger immediately to initialize handlers.
    LoggingManager.isLogToFile();

    // Default exception logger
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            log.log(Level.SEVERE, "Exception in " + t + ": " + e.toString(), e);
        }
    });

    CommandLine commandLine = parseCommandLine(args);
    if (commandLine == null) {
        return;
    }

    // -l --log console log levels (severe, warning, info, fine and finer).
    if (commandLine.hasOption("l")) {
        String levelName = commandLine.getOptionValue("l");
        Level level = LoggingManager.levelForName(levelName);
        if (level != null) {
            LoggingManager.setConsoleLogging(level);
        }
    }

    if (commandLine.hasOption("s")) {
        // Server mode, suppress debug output on console
        // Logger.addExcludeConsoleLogLevel(Logger.DEBUG);
    }

    if (commandLine.hasOption("h")) {
        // Show help
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("PowerFolder", COMMAND_LINE_OPTIONS);
        return;
    }

    int rconPort = Integer.valueOf(ConfigurationEntry.NET_RCON_PORT.getDefaultValue());
    String portStr = commandLine.getOptionValue("k");
    if (StringUtils.isNotBlank(portStr)) {
        try {
            rconPort = Integer.valueOf(portStr.trim());
        } catch (Exception e) {
            log.warning("Unable to parse rcon port: " + portStr + ". " + e);
        }
    }

    boolean runningInstanceFound = RemoteCommandManager.hasRunningInstance(rconPort);

    if (commandLine.hasOption("k")) {
        if (runningInstanceFound) {
            System.out.println("Stopping " + NAME);
            // Send quit command
            RemoteCommandManager.sendCommand(rconPort, RemoteCommandManager.QUIT);
        } else {
            System.err.println("Process not running");
        }

        // stop
        return;
    }

    // set language from commandline to preferences
    if (commandLine.hasOption("g")) {
        Preferences.userNodeForPackage(Translation.class).put("locale", commandLine.getOptionValue("g"));
    }

    if (JavaVersion.systemVersion().isOpenJDK()) {
        Object[] options = { "Open Oracle home page and exit", "Exit" };

        int n = JOptionPane.showOptionDialog(null,
                "You are using OpenJDK which is unsupported.\n"
                        + "Please install the client with bundled JRE or install the Oracle JRE",
                "Unsupported JRE", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                options[0]);

        if (n == 0) {
            try {
                BrowserLauncher.openURL("http://www.java.com");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        return;
    }

    // The controller.
    Controller controller = Controller.createController();

    String[] files = commandLine.getArgs();
    // Parsing of command line completed

    boolean commandContainsRemoteCommands = files != null && files.length >= 1 || commandLine.hasOption("e")
            || commandLine.hasOption("r") || commandLine.hasOption("a");
    // Try to start controller
    boolean startController = !commandContainsRemoteCommands || !runningInstanceFound;
    try {
        log.info("PowerFolder v" + Controller.PROGRAM_VERSION);

        // Start controller
        if (startController) {
            controller.startConfig(commandLine);
        }

        // Send remote command if there a files in commandline
        if (files != null && files.length > 0) {
            // Parse filenames and build remote command
            StringBuilder openFilesRCommand = new StringBuilder(RemoteCommandManager.OPEN);

            for (String file : files) {
                openFilesRCommand.append(file);
                // FIXME: Add ; separator ?
            }

            // Send remote command to running PowerFolder instance
            RemoteCommandManager.sendCommand(openFilesRCommand.toString());
        }

        if (commandLine.hasOption("e")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.MAKEFOLDER + commandLine.getOptionValue("e"));
        }
        if (commandLine.hasOption("r")) {
            RemoteCommandManager
                    .sendCommand(RemoteCommandManager.REMOVEFOLDER + commandLine.getOptionValue("r"));
        }
        if (commandLine.hasOption("a")) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.COPYLINK + commandLine.getOptionValue("a"));
        }
    } catch (Throwable t) {
        t.printStackTrace();
        log.log(Level.SEVERE, "Throwable", t);
        return;
    }

    // Begin monitoring memory usage.
    if (controller.isStarted() && controller.isUIEnabled()) {
        ScheduledExecutorService service = controller.getThreadPool();
        service.scheduleAtFixedRate(new MemoryMonitor(controller), 1, 1, TimeUnit.MINUTES);
    }

    // Not go into console mode if ui is open
    if (!startController) {
        if (runningInstanceFound) {
            RemoteCommandManager.sendCommand(RemoteCommandManager.SHOW_UI);
        }
        return;
    }

    System.out.println("------------ " + NAME + " " + Controller.PROGRAM_VERSION + " started ------------");

    boolean restartRequested = false;
    do {
        // Go into restart loop
        while (controller.isStarted() || controller.isShuttingDown()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.log(Level.WARNING, "InterruptedException", e);
                return;
            }
        }

        restartRequested = controller.isRestartRequested();
        if (restartRequested) {
            Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
            for (Thread thread : threads.keySet()) {
                if (thread.getName().startsWith("PoolThread") || thread.getName().startsWith("Reconnector")
                        || thread.getName().startsWith("ConHandler")) {
                    thread.interrupt();
                }
            }
            log.info("Restarting controller");
            System.out.println(
                    "------------ " + NAME + " " + Controller.PROGRAM_VERSION + " restarting ------------");
            controller = null;
            System.gc();
            controller = Controller.createController();
            // Start controller
            controller.startConfig(commandLine);
        }
    } while (restartRequested);
}

From source file:com.qualogy.qafe.business.integration.java.JavaServiceProcessor.java

private static String resolveErrorMessage(Throwable cause) {
    String errorMessage = null;/*from   www  .  j a  v  a2  s  .c om*/
    if (cause instanceof NullPointerException) {
        StackTraceElement[] stackTraceElements = ((NullPointerException) cause).getStackTrace();
        StackTraceElement stackTraceElement = stackTraceElements[0];
        errorMessage = cause.toString() + ": " + stackTraceElement.toString();
    } else {
        errorMessage = cause.getMessage();
    }
    if (errorMessage != null) {
        errorMessage = errorMessage.trim();
    }
    return errorMessage;
}

From source file:com.infinities.skyport.util.JsonUtil.java

public static String toLegendJson(Throwable e) {
    StringWriter wtr = new StringWriter();
    try {//from   ww w. j  a  v  a 2 s.  c o m
        JsonGenerator g = new JsonFactory().createGenerator(wtr);
        g.writeStartArray();
        g.writeStartObject();
        g.writeStringField("RES", "FALSE");
        g.writeStringField("REASON", e.toString());
        // g.writeStringField("REASON", Objects.firstNonNull(e.getMessage(),
        // e.toString()));
        g.writeEndObject();
        g.writeEndArray();
        g.close();
    } catch (Exception ee) {
        ArrayNode array = getObjectMapper().createArrayNode();
        ObjectNode reason = getObjectMapper().createObjectNode();
        ObjectNode status = getObjectMapper().createObjectNode();

        status.put(JsonConstants.STATUS, String.valueOf("FALSE"));
        reason.put(JsonConstants.REASON, "an unexpected error occurred");
        array.add(status).add(reason);

        // "[{\"RES\":\"FALSE\"}, {\"REASON\":\"an unexpected error occurred\"}]";
        return array.toString();
    }

    return wtr.toString();
}