Example usage for com.google.common.base Throwables getStackTraceAsString

List of usage examples for com.google.common.base Throwables getStackTraceAsString

Introduction

In this page you can find the example usage for com.google.common.base Throwables getStackTraceAsString.

Prototype

@CheckReturnValue
public static String getStackTraceAsString(Throwable throwable) 

Source Link

Document

Returns a string containing the result of Throwable#toString() toString() , followed by the full, recursive stack trace of throwable .

Usage

From source file:org.apache.brooklyn.demo.Publish.java

public static void main(String... argv) throws Exception {
    Preconditions.checkElementIndex(0, argv.length, "Must specify broker URL");
    String url = argv[0];/*  ww  w.  j a  v  a 2s  .  c o  m*/

    // Set Qpid client properties
    System.setProperty(ClientProperties.AMQP_VERSION, "0-10");
    System.setProperty(ClientProperties.DEST_SYNTAX, "ADDR");

    // Connect to the broker
    AMQConnectionFactory factory = new AMQConnectionFactory(url);
    Connection connection = factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    try {
        // Create a producer for the queue
        Queue destination = session.createQueue(QUEUE);
        MessageProducer messageProducer = session.createProducer(destination);

        // Send 100 messages
        for (int n = 0; n < 100; n++) {
            String body = String.format("test message %03d", n + 1);
            TextMessage message = session.createTextMessage(body);
            messageProducer.send(message);
            System.out.printf("Sent message %s\n", body);
        }
    } catch (Exception e) {
        System.err.printf("Error while sending - %s\n", e.getMessage());
        System.err.printf("Cause: %s\n", Throwables.getStackTraceAsString(e));
    } finally {
        session.close();
        connection.close();
    }
}

From source file:brooklyn.demo.Subscribe.java

public static void main(String... argv) throws Exception {
    Preconditions.checkElementIndex(0, argv.length, "Must specify broker URL");
    String url = argv[0];/*  w ww .j av  a  2s .  c  o  m*/

    // Set Qpid client properties
    System.setProperty(ClientProperties.AMQP_VERSION, "0-10");
    System.setProperty(ClientProperties.DEST_SYNTAX, "ADDR");

    // Connect to the broker
    AMQConnectionFactory factory = new AMQConnectionFactory(url);
    Connection connection = factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    System.out.printf("Waiting up to %s milliseconds to receive %s messages\n", MESSAGE_TIMEOUT_MILLIS,
            MESSAGE_COUNT);
    try {
        // Create a producer for the queue
        Queue destination = session.createQueue(QUEUE);
        MessageConsumer messageConsumer = session.createConsumer(destination);

        // Try and receive 100 messages
        for (int n = 0; n < MESSAGE_COUNT; n++) {
            TextMessage msg = (TextMessage) messageConsumer.receive(MESSAGE_TIMEOUT_MILLIS);
            if (msg == null) {
                System.out.printf("No message received in %s milliseconds, exiting", MESSAGE_TIMEOUT_MILLIS);
                break;
            }
            System.out.printf("Got message %d: '%s'\n", n + 1, msg.getText());
        }
    } catch (Exception e) {
        System.err.printf("Error while receiving - %s\n", e.getMessage());
        System.err.printf("Cause: %s\n", Throwables.getStackTraceAsString(e));
    } finally {
        session.close();
        connection.close();
    }
}

From source file:com.turbospaces.api.EmbeddedJSpaceRunner.java

/**
 * launcher method/*w  w  w  . ja  va 2 s. com*/
 * 
 * @param args
 *            [1 argument = application context path]
 * @throws Exception
 *             re-throw execution errors if any
 */
public static void main(final String... args) throws Exception {
    JVMUtil.gcOnExit();
    String appContextPath = args[0];
    if (System.getProperty(Global.IPv4) == null && System.getProperty(Global.IPv6) == null)
        System.setProperty(Global.IPv4, Boolean.TRUE.toString());
    System.setProperty(Global.CUSTOM_LOG_FACTORY, JGroupsCustomLoggerFactory.class.getName());

    LOGGER.info("Welcome to turbospaces:version = {}, build date = {}", SpaceUtility.projectVersion(),
            SpaceUtility.projecBuildTimestamp());
    LOGGER.info("{}: launching configuration {}", EmbeddedJSpaceRunner.class.getSimpleName(), appContextPath);
    AbstractXmlApplicationContext c = appContextPath.startsWith("file")
            ? new FileSystemXmlApplicationContext(appContextPath)
            : new ClassPathXmlApplicationContext(appContextPath);
    c.getBeansOfType(JSpace.class);
    c.registerShutdownHook();
    Collection<SpaceConfiguration> configurations = c.getBeansOfType(SpaceConfiguration.class).values();
    for (SpaceConfiguration spaceConfiguration : configurations)
        spaceConfiguration.joinNetwork();
    LOGGER.info("all jspaces joined network, notifying waiting threads...");
    synchronized (joinNetworkMonitor) {
        joinNetworkMonitor.notifyAll();
    }

    while (!Thread.currentThread().isInterrupted())
        synchronized (c) {
            try {
                c.wait(TimeUnit.SECONDS.toMillis(1));
            } catch (InterruptedException e) {
                LOGGER.info("got interruption signal, terminating jspaces... stack_trace = {}",
                        Throwables.getStackTraceAsString(e));
                Thread.currentThread().interrupt();
                Util.printThreads();
            }
        }

    c.destroy();
}

From source file:cli.Main.java

public static void main(String[] args) throws IOException {
    CommandLineParameters cli = new CommandLineParameters();
    JCommander jCmd = new JCommander(cli, args);
    jCmd.setProgramName("emailconverter");

    if (cli.isGui()) {
        MainWindow.main(new String[0]);
        return;/*from ww  w  .ja v a 2  s .  c  o  m*/
    }

    if (cli.isHelp()) {
        jCmd.usage();
        return;
    }

    if (cli.isVersion()) {
        System.out.println(Main.class.getPackage().getImplementationVersion());
        return;
    }

    if (cli.isDebug()) {
        Logger.level = LogLevel.Debug;
    }

    if (cli.isError()) {
        Logger.level = LogLevel.Error;
    }

    if (cli.isQuiet()) {
        Logger.level = LogLevel.Quiet;
    }

    if (cli.getFiles().isEmpty()) {
        Logger.error("Please provide the path of an EML file.");
        jCmd.usage();
        return;
    }

    String in = cli.getFiles().get(0);

    if (!(new File(in).exists())) {
        Logger.error("Input EML file %s could not be found!", in);
        return;
    }

    String out = cli.getOutput();

    if (Strings.isNullOrEmpty(cli.getOutput())) {
        out = Files.getNameWithoutExtension(in) + ".pdf";

        File parent = new File(in).getParentFile();
        if (parent != null) {
            out = new File(parent, out).toString();
        }
    }

    List<String> extParams = new ArrayList<String>();

    if ("auto".equalsIgnoreCase(cli.getProxy())) {
        Proxy defaultProxy = HttpUtils.getDefaultProxy();
        InetSocketAddress defaultProxyAddress = (InetSocketAddress) defaultProxy.address();
        String proxy = defaultProxy.type().toString() + "://" + defaultProxyAddress.toString();

        extParams.add("--proxy");
        extParams.add(proxy.toLowerCase());
        Logger.debug("Use default proxy %s", proxy);
    } else if (!Strings.isNullOrEmpty(cli.getProxy())) {
        extParams.add("--proxy");
        extParams.add(cli.getProxy());
        Logger.debug("Use proxy from parameters %s", cli.getProxy());
    }

    try {
        MimeMessageConverter.convertToPdf(in, out, cli.isOutputHTML(), cli.isHideHeaders(),
                cli.isExtractAttachments(), cli.getExtractAttachmentsDir(), extParams);
    } catch (Exception e) {
        Logger.error("The eml could not be converted. Error: %s", Throwables.getStackTraceAsString(e));

        if (!cli.isDisableCrashreports()) {
            /* Try to send the bugreport via email */
            StringBuilder bugdetails = new StringBuilder(800);

            bugdetails.append("User: ");
            bugdetails.append(System.getProperty("user.name"));
            bugdetails.append("\n");

            InetAddress localHost = InetAddress.getLocalHost();
            bugdetails.append("Localhost: ");
            bugdetails.append(localHost.getHostAddress());
            bugdetails.append(" - ");
            bugdetails.append(localHost.getHostName());
            bugdetails.append("\n");

            bugdetails.append("GEO: ");
            bugdetails.append(HttpUtils.getRequest("http://ipinfo.io/json").replaceAll("\"", ""));
            bugdetails.append("\n");

            bugdetails.append("OS: ");
            bugdetails.append(System.getProperty("os.name"));
            bugdetails.append(" ");
            bugdetails.append(System.getProperty("os.version"));
            bugdetails.append(" ");
            bugdetails.append(System.getProperty("os.arch"));
            bugdetails.append("\n");

            bugdetails.append("Java: ");
            bugdetails.append(System.getProperty("java.vendor"));
            bugdetails.append(" ");
            bugdetails.append(System.getProperty("java.version"));
            bugdetails.append("\n\n");

            bugdetails.append("Exception\n");
            bugdetails.append(Throwables.getStackTraceAsString(e));

            String subject = "Bugreport from " + System.getProperty("user.name") + " | " + new Date();

            HttpUtils.postRequest(BUG_EMAIL_URL,
                    String.format("subject=%s&body=%s", subject, bugdetails.toString()));
        }
    }
}

From source file:com.zulily.omicron.Main.java

public static void main(final String[] args) {

    if (args == null || (args.length > 0 && args[0].contains("?"))) {
        printHelp();/*from   w  w  w. j ava  2s  . c  o  m*/
        System.exit(0);
    }

    // see doc for java.util.logging.SimpleFormatter
    // log output will look like:
    // [Tue Dec 16 10:29:07 PST 2014] INFO: <message>
    System.setProperty("java.util.logging.SimpleFormatter.format", DEFAULT_LOG_FORMAT);

    try {

        Configuration configuration = new Configuration(args.length > 0 ? args[0].trim() : DEFAULT_CONFIG_PATH);

        Crontab crontab = new Crontab(configuration);

        final JobManager jobManager = new JobManager(configuration, crontab);

        // The minute logic is intended to stay calibrated
        // with the current calendar minute.
        // Scheduled jobs should run as close to second-of-minute == 0 as possible
        // while minimizing acquired execution drift over time, or possible hangups
        // from scheduling to the "next calendar time of hh:mm:ss" considering DST or leap-seconds, etc.

        long targetExecuteMinute = getTargetMinuteMillisFromNow(1);

        // We're going to loop forever until the process is killed explicitly - please stop the warnings
        //noinspection InfiniteLoopStatement
        while (true) {

            long currentExecuteMinute = getTargetMinuteMillisFromNow(0);

            // We want to trigger tasks when the execute minute comes up or is past-due
            // so we use < instead of == to set it off "fuzzily."
            // Until then watch for crontab/conf changes or sleep
            while (currentExecuteMinute < targetExecuteMinute) {

                if (configurationUpdated(crontab, configuration)) {

                    info("Either configuration or crontab updated. Reloading task configurations.");

                    configuration = configuration.reload();
                    crontab = new Crontab(configuration);

                    jobManager.updateConfiguration(configuration, crontab);
                }

                try {

                    Thread.sleep(TimeUnit.SECONDS.toMillis(1));

                } catch (InterruptedException e) {
                    throw Throwables.propagate(e);
                }

                currentExecuteMinute = getTargetMinuteMillisFromNow(0);

            }

            // Due to drift, initial start time, or due to the length of
            // time it takes to read crontab/config changes,
            // we may actually pass a target calendar minute without evaluation
            // of the scheduled task list
            //
            // The current implementation of crond never evaluates the current minute
            // that it detects schedule changes. For now I'm calling that
            // particular case "expected behavior" and just warning
            if (currentExecuteMinute != targetExecuteMinute) {
                warn("Scheduled tasks may have been missed due to missed minute target {0}",
                        String.valueOf(targetExecuteMinute));
            }

            // Set for re-evaluation in the next calendar minute
            targetExecuteMinute = getTargetMinuteMillisFromNow(1);

            jobManager.run();
        }

    } catch (Exception e) {
        error("Caught exception in primary thread:\n{0}\n", Throwables.getStackTraceAsString(e));
        System.exit(1);
    }

    System.exit(0);
}

From source file:com.xiaomi.linden.service.LindenServer.java

public static void main(String[] args) throws IOException {
    Preconditions.checkArgument(args.length != 0, "need conf dir");
    String conf = args[0];/*from   w ww .  j a  v a  2s. com*/
    LindenServer server = null;
    try {
        server = new LindenServer(conf);
        server.startServer();
    } catch (Exception e) {
        if (server != null)
            try {
                server.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        e.printStackTrace();
        LOGGER.error("Server start failed : {}", Throwables.getStackTraceAsString(e));
    }
}

From source file:pl.otros.logview.batch.BatchProcessor.java

public static void main(String[] args) throws IOException, InitializationException, ConfigurationException {

    CmdLineConfig parserCmdLine = new CmdLineConfig();
    try {/* www.  j  a  v a  2s  .c o  m*/
        parserCmdLine.parserCmdLine(args);

        if (parserCmdLine.printHelp) {
            parserCmdLine.printUsage();
            System.exit(0);
        }
    } catch (Exception e) {
        parserCmdLine.printUsage();
        System.err.println(e.getMessage());
        return;
    } finally {
        checkIfShowBatchProcessingIsEnabled(parserCmdLine);
    }

    BatchProcessor batchProcessor = new BatchProcessor();
    batchProcessor.setFiles(parserCmdLine.files);
    if (parserCmdLine.dirWithJars != null) {
        File f = new File(parserCmdLine.dirWithJars);
        URL[] urls = null;
        if (f.isDirectory()) {
            File[] listFiles = f.listFiles(new FileFilter() {

                @Override
                public boolean accept(File f) {
                    return f.isFile() && f.getName().endsWith(".jar");
                }
            });
            urls = new URL[listFiles.length];
            for (int i = 0; i < urls.length; i++) {
                urls[i] = listFiles[i].toURI().toURL();
            }
        } else if (f.getName().endsWith("jar")) {
            urls = new URL[] { f.toURI().toURL() };
        }
        if (urls == null) {
            System.err.println(
                    "Dir with additional jars or single jars do not point to dir with jars or single jar");
            System.exit(1);
        }
        URLClassLoader classLoader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
        Thread.currentThread().setContextClassLoader(classLoader);
    }
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
        batchProcessor.setLogDataParsedListener(
                (LogDataParsedListener) cl.loadClass(parserCmdLine.logDataParsedListenerClass).newInstance());
        // batchProcessor.setLogDataCollector((LogDataParsedListener) cl.loadClass(parserCmdLine.logDataParsedListenerClass).newInstance());
    } catch (Exception e2) {
        System.err.println("Can't load log data collector: " + e2.getMessage());
    }

    batchProcessor.batchProcessingContext.setVerbose(parserCmdLine.verbose);

    // load processing configuration
    if (parserCmdLine.batchConfigurationFile != null) {
        PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
        propertiesConfiguration.load(parserCmdLine.batchConfigurationFile);
        batchProcessor.batchProcessingContext.getConfiguration().append(propertiesConfiguration);
    }

    batchProcessor.batchProcessingContext.printIfVerbose("Processing started");
    try {
        batchProcessor.process();
        batchProcessor.batchProcessingContext.printIfVerbose("Finished");
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
        System.out.println(Throwables.getStackTraceAsString(e));
    }
}

From source file:com.xiaomi.linden.util.ResponseUtils.java

public static Future<Response> buildFailedFutureResponse(Exception e) {
    return Future.value(new Response(false).setError(Throwables.getStackTraceAsString(e)));
}

From source file:ch.petikoch.examples.mvvm_rxjava.utils.SysOutUtils.java

public static void syserr(String text, @Nullable Throwable throwable) {
    String output = "[" + Thread.currentThread().getName() + "] " + text;
    if (throwable != null) {
        output += "\n" + Throwables.getStackTraceAsString(throwable);
    }//from  w  w  w . jav a 2 s. c  om
    System.err.println(output);
}

From source file:com.facebook.buck.util.Threads.java

public static void interruptCurrentThread() {
    LOG.warn("Current thread interrupted at this location: "
            + Throwables.getStackTraceAsString(new Throwable()));
    Thread.currentThread().interrupt();
}