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

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

Introduction

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

Prototype

@CheckReturnValue
public static Throwable getRootCause(Throwable throwable) 

Source Link

Document

Returns the innermost cause of throwable .

Usage

From source file:fathom.Boot.java

/**
 * The Java entry point.//www. j  a  v  a  2s .c  o  m
 *
 * @param args
 */
public static void main(String... args) {
    try {
        final Boot boot = new Boot(args);
        boot.addShutdownHook().start();
    } catch (Exception e) {
        Exception root = (Exception) Throwables.getRootCause(e);
        root.printStackTrace();
        System.exit(1);
    }
}

From source file:org.apache.cassandra.tools.NodeTool.java

public static void main(String... args) {
    List<Class<? extends Runnable>> commands = newArrayList(Help.class, Info.class, Ring.class, NetStats.class,
            CfStats.class, TableStats.class, CfHistograms.class, TableHistograms.class, Cleanup.class,
            ClearSnapshot.class, Compact.class, Scrub.class, Verify.class, Flush.class, UpgradeSSTable.class,
            DisableAutoCompaction.class, EnableAutoCompaction.class, CompactionStats.class,
            CompactionHistory.class, Decommission.class, DescribeCluster.class, DisableBinary.class,
            EnableBinary.class, EnableGossip.class, DisableGossip.class, EnableHandoff.class,
            EnableThrift.class, GcStats.class, GetCompactionThreshold.class, GetCompactionThroughput.class,
            GetStreamThroughput.class, GetTraceProbability.class, GetInterDCStreamThroughput.class,
            GetEndpoints.class, GetSSTables.class, GossipInfo.class, InvalidateKeyCache.class,
            InvalidateRowCache.class, InvalidateCounterCache.class, Join.class, Move.class, PauseHandoff.class,
            ResumeHandoff.class, ProxyHistograms.class, Rebuild.class, Refresh.class, RemoveNode.class,
            Assassinate.class, Repair.class, SetCacheCapacity.class, SetHintedHandoffThrottleInKB.class,
            SetCompactionThreshold.class, SetCompactionThroughput.class, SetStreamThroughput.class,
            SetInterDCStreamThroughput.class, SetTraceProbability.class, Snapshot.class, ListSnapshots.class,
            Status.class, StatusBinary.class, StatusGossip.class, StatusThrift.class, StatusBackup.class,
            StatusHandoff.class, Stop.class, StopDaemon.class, Version.class, DescribeRing.class,
            RebuildIndex.class, RangeKeySample.class, EnableBackup.class, DisableBackup.class,
            ResetLocalSchema.class, ReloadTriggers.class, SetCacheKeysToSave.class, DisableThrift.class,
            DisableHandoff.class, Drain.class, TruncateHints.class, TpStats.class, TopPartitions.class,
            SetLoggingLevel.class, GetLoggingLevels.class, FailureDetectorInfo.class,
            RefreshSizeEstimates.class);

    Cli.CliBuilder<Runnable> builder = Cli.builder("nodetool");

    builder.withDescription("Manage your Cassandra cluster").withDefaultCommand(Help.class)
            .withCommands(commands);//from   w ww  . j  a  v  a2  s .c om

    // bootstrap commands
    builder.withGroup("bootstrap").withDescription("Monitor/manage node's bootstrap process")
            .withDefaultCommand(Help.class).withCommand(BootstrapResume.class);

    Cli<Runnable> parser = builder.build();

    int status = 0;
    try {
        Runnable parse = parser.parse(args);
        printHistory(args);
        parse.run();
    } catch (IllegalArgumentException | IllegalStateException | ParseArgumentsMissingException
            | ParseArgumentsUnexpectedException | ParseOptionConversionException | ParseOptionMissingException
            | ParseOptionMissingValueException | ParseCommandMissingException
            | ParseCommandUnrecognizedException e) {
        badUse(e);
        status = 1;
    } catch (Throwable throwable) {
        err(Throwables.getRootCause(throwable));
        status = 2;
    }

    System.exit(status);
}

From source file:com.spotify.asyncdatastoreclient.example.ExampleAsync.java

public static void main(final String... args) throws Exception {
    final DatastoreConfig config = DatastoreConfig.builder().connectTimeout(5000).requestTimeout(1000)
            .maxConnections(5).requestRetry(3).dataset("my-dataset").namespace("my-namespace")
            .credential(DatastoreHelper.getComputeEngineCredential()).build();

    final Datastore datastore = Datastore.create(config);

    // Add a two entities asynchronously
    final ListenableFuture<MutationResult> addFirst = addData(datastore);
    final ListenableFuture<MutationResult> addSecond = addDataInTransaction(datastore);
    final ListenableFuture<List<Object>> addBoth = Futures.allAsList(addFirst, addSecond);

    // Query the entities we've just inserted
    final ListenableFuture<QueryResult> query = Futures.transform(addBoth, (List<Object> result) -> {
        return queryData(datastore);
    });//w ww.j  a v  a  2s . c  o  m

    // Print the query results before clean up
    final ListenableFuture<MutationResult> delete = Futures.transform(query, (QueryResult result) -> {
        for (final Entity entity : result) {
            System.out.println("Employee name: " + entity.getString("fullname"));
            System.out.println("Employee age: " + entity.getInteger("age"));
        }
        return deleteData(datastore);
    });

    Futures.addCallback(delete, new FutureCallback<MutationResult>() {
        @Override
        public void onSuccess(final MutationResult result) {
            System.out.println("All complete.");
        }

        @Override
        public void onFailure(final Throwable throwable) {
            System.err.println("Storage exception: " + Throwables.getRootCause(throwable).getMessage());
        }
    });
}

From source file:com.torodb.standalone.Main.java

public static void main(String[] args) throws Exception {
    Console console = JCommander.getConsole();

    ResourceBundle cliBundle = PropertyResourceBundle.getBundle("CliMessages");
    final CliConfig cliConfig = new CliConfig();
    JCommander jCommander = new JCommander(cliConfig, cliBundle, args);
    jCommander.setColumnSize(Integer.MAX_VALUE);

    if (cliConfig.isHelp()) {
        jCommander.usage();//from   w w  w  .  j a  va2s .  c o m
        System.exit(0);
    }

    if (cliConfig.isHelpParam()) {
        console.println(cliBundle.getString("help-param-header"));
        ResourceBundle configBundle = PropertyResourceBundle.getBundle("ConfigMessages");
        ConfigUtils.printParamDescriptionFromConfigSchema(Config.class, configBundle, console, 0);
        System.exit(0);
    }

    final Config config = CliConfigUtils.readConfig(cliConfig);

    if (cliConfig.isPrintConfig()) {
        ConfigUtils.printYamlConfig(config, console);

        System.exit(0);
    }

    if (cliConfig.isPrintXmlConfig()) {
        ConfigUtils.printXmlConfig(config, console);

        System.exit(0);
    }

    configureLogger(cliConfig, config);

    config.getBackend().getBackendImplementation().accept(new BackendImplementationVisitor() {
        @Override
        public void visit(AbstractDerby value) {
            parseToropassFile(value);
        }

        @Override
        public void visit(AbstractPostgres value) {
            parseToropassFile(value);
        }

        public void parseToropassFile(BackendPasswordConfig value) {
            try {
                ConfigUtils.parseToropassFile(value);
            } catch (Exception ex) {
                throw new SystemException(ex);
            }
        }
    });
    if (config.getProtocol().getMongo().getReplication() != null) {
        for (AbstractReplication replication : config.getProtocol().getMongo().getReplication()) {
            if (replication.getAuth().getUser() != null) {
                HostAndPort syncSource = HostAndPort.fromString(replication.getSyncSource())
                        .withDefaultPort(27017);
                ConfigUtils.parseMongopassFile(new MongoPasswordConfig() {

                    @Override
                    public void setPassword(String password) {
                        replication.getAuth().setPassword(password);
                    }

                    @Override
                    public String getUser() {
                        return replication.getAuth().getUser();
                    }

                    @Override
                    public Integer getPort() {
                        return syncSource.getPort();
                    }

                    @Override
                    public String getPassword() {
                        return replication.getAuth().getPassword();
                    }

                    @Override
                    public String getMongopassFile() {
                        return config.getProtocol().getMongo().getMongopassFile();
                    }

                    @Override
                    public String getHost() {
                        return syncSource.getHostText();
                    }

                    @Override
                    public String getDatabase() {
                        return replication.getAuth().getSource();
                    }
                });
            }
        }
    }

    if (config.getBackend().isLike(AbstractPostgres.class)) {
        AbstractPostgres postgres = config.getBackend().as(AbstractPostgres.class);

        if (cliConfig.isAskForPassword()) {
            console.print("Database user " + postgres.getUser() + " password:");
            postgres.setPassword(readPwd());
        }
    } else if (config.getBackend().isLike(AbstractDerby.class)) {
        AbstractDerby derby = config.getBackend().as(AbstractDerby.class);

        if (cliConfig.isAskForPassword()) {
            console.print("Database user " + derby.getUser() + " password:");
            derby.setPassword(readPwd());
        }
    }

    try {
        Clock clock = Clock.systemDefaultZone();
        Service server;
        if (config.getProtocol().getMongo().getReplication() == null
                || config.getProtocol().getMongo().getReplication().isEmpty()) {
            Service toroDbServer = ToroDbBootstrap.createStandaloneService(config, clock);

            toroDbServer.startAsync();
            toroDbServer.awaitRunning();

            server = toroDbServer;
        } else {
            throw new UnsupportedOperationException("Replication not supported yet!");
        }

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            server.stopAsync();
            server.awaitTerminated();
        }));
    } catch (CreationException ex) {
        ex.getErrorMessages().stream().forEach(m -> {
            if (m.getCause() != null) {
                LOGGER.error(m.getCause().getMessage());
            } else {
                LOGGER.error(m.getMessage());
            }
        });
        System.exit(1);
    } catch (Throwable ex) {
        LOGGER.error("Fatal error on initialization", ex);
        Throwable rootCause = Throwables.getRootCause(ex);
        String causeMessage = rootCause.getMessage();
        JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage);
        System.exit(1);
    }
}

From source file:com.torodb.stampede.Main.java

public static void main(String[] args) throws Exception {
    try {//from  ww w . ja v  a 2s.  com
        Console console = JCommander.getConsole();

        ResourceBundle cliBundle = PropertyResourceBundle.getBundle("CliMessages");
        final CliConfig cliConfig = new CliConfig();
        JCommander jCommander = new JCommander(cliConfig, cliBundle, args);
        jCommander.setColumnSize(Integer.MAX_VALUE);

        if (cliConfig.isVersion()) {
            BuildProperties buildProperties = new DefaultBuildProperties();
            console.println(buildProperties.getFullVersion());
            System.exit(0);
        }

        if (cliConfig.isHelp()) {
            jCommander.usage();
            System.exit(0);
        }

        if (cliConfig.isHelpParam()) {
            console.println(cliBundle.getString("cli.help-param-header"));
            ConfigUtils.printParamDescriptionFromConfigSchema(Config.class, cliBundle, console, 0);
            System.exit(0);
        }

        cliConfig.addParams();

        final Config config = CliConfigUtils.readConfig(cliConfig);

        if (cliConfig.isPrintConfig()) {
            ConfigUtils.printYamlConfig(config, console);

            System.exit(0);
        }

        if (cliConfig.isPrintXmlConfig()) {
            ConfigUtils.printXmlConfig(config, console);

            System.exit(0);
        }

        if (cliConfig.isPrintParam()) {
            JsonNode jsonNode = ConfigUtils.getParam(config, cliConfig.getPrintParamPath());

            if (jsonNode != null) {
                console.print(jsonNode.asText());
            }

            System.exit(0);
        }

        configureLogger(cliConfig, config);

        config.getBackend().getBackendImplementation().accept(new BackendImplementationVisitor() {
            @Override
            public void visit(AbstractDerby value) {
                parseToropassFile(value);
            }

            @Override
            public void visit(AbstractPostgres value) {
                parseToropassFile(value);
            }

            public void parseToropassFile(BackendPasswordConfig value) {
                try {
                    ConfigUtils.parseToropassFile(value);
                } catch (Exception ex) {
                    throw new SystemException(ex);
                }
            }
        });
        AbstractReplication replication = config.getReplication();
        if (replication.getAuth().getUser() != null) {
            HostAndPort syncSource = HostAndPort.fromString(replication.getSyncSource()).withDefaultPort(27017);
            ConfigUtils.parseMongopassFile(new MongoPasswordConfig() {

                @Override
                public void setPassword(String password) {
                    replication.getAuth().setPassword(password);
                }

                @Override
                public String getUser() {
                    return replication.getAuth().getUser();
                }

                @Override
                public Integer getPort() {
                    return syncSource.getPort();
                }

                @Override
                public String getPassword() {
                    return replication.getAuth().getPassword();
                }

                @Override
                public String getMongopassFile() {
                    return config.getReplication().getMongopassFile();
                }

                @Override
                public String getHost() {
                    return syncSource.getHostText();
                }

                @Override
                public String getDatabase() {
                    return replication.getAuth().getSource();
                }
            });
        }

        if (config.getBackend().isLike(AbstractPostgres.class)) {
            AbstractPostgres postgres = config.getBackend().as(AbstractPostgres.class);

            if (cliConfig.isAskForPassword()) {
                console.print("Type database user " + postgres.getUser() + "'s password:");
                postgres.setPassword(readPwd());
            }

            if (postgres.getPassword() == null) {
                throw new SystemException("No password provided for database user " + postgres.getUser()
                        + ".\n\n" + "Please add following line to file " + postgres.getToropassFile() + ":\n"
                        + postgres.getHost() + ":" + postgres.getPort() + ":" + postgres.getDatabase() + ":"
                        + postgres.getUser() + ":<password>\n" + "Replace <password> for database user "
                        + postgres.getUser() + "'s password");
            }
        }

        try {
            Clock clock = Clock.systemDefaultZone();

            Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
                @Override
                @SuppressFBWarnings(value = "DM_EXIT", justification = "Since is really hard to stop cleanly all threads when an OOME is thrown we must "
                        + "exit to avoid no more action is performed that could lead to an unespected "
                        + "state")
                public void uncaughtException(Thread t, Throwable e) {
                    if (e instanceof OutOfMemoryError) {
                        try {
                            LOGGER.error("Fatal out of memory: " + e.getLocalizedMessage(), e);
                        } finally {
                            System.exit(1);
                        }
                    }
                }
            });

            Service stampedeService = StampedeBootstrap.createStampedeService(config, clock);

            stampedeService.startAsync();
            stampedeService.awaitTerminated();

            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                stampedeService.stopAsync();
                stampedeService.awaitTerminated();
            }));
        } catch (CreationException ex) {
            ex.getErrorMessages().stream().forEach(m -> {
                if (m.getCause() != null) {
                    LOGGER.error(m.getCause().getMessage());
                } else {
                    LOGGER.error(m.getMessage());
                }
            });
            LogManager.shutdown();
            System.exit(1);
        }
    } catch (Throwable ex) {
        LOGGER.debug("Fatal error on initialization", ex);
        Throwable rootCause = Throwables.getRootCause(ex);
        String causeMessage = rootCause.getMessage();
        LogManager.shutdown();
        JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage);
        System.exit(1);
    }
}

From source file:io.bazel.rules.closure.worker.Utilities.java

static boolean wasInterrupted(Throwable e) {
    Throwable cause = Throwables.getRootCause(e);
    return cause instanceof InterruptedException || cause instanceof InterruptedIOException
            || cause instanceof ClosedByInterruptException;
}

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

public static String getHumanReadableOrLocalizedMessage(Exception e) {
    if (e instanceof HumanReadableException) {
        return ((HumanReadableException) e).getHumanReadableErrorMessage();
    }/*w ww .j a  va2 s.  c om*/
    return Throwables.getRootCause(e).getLocalizedMessage();
}

From source file:org.gradle.internal.resolve.ResolveExceptionAnalyzer.java

public static boolean isCriticalFailure(Throwable throwable) {
    Throwable rootCause = Throwables.getRootCause(throwable);
    return isTimeoutException(rootCause) || isUnrecoverable5xxStatusCode(rootCause);
}

From source file:org.hawkular.metrics.api.jaxrs.exception.mappers.ExceptionMapperUtils.java

public static Response buildResponse(Throwable exception, Status status) {
    Response response = Response.status(status)
            .entity(new ApiError(Throwables.getRootCause(exception).getMessage()))
            .type(MediaType.APPLICATION_JSON_TYPE).build();
    if (log.isTraceEnabled()) {
        log.trace("Turning " + exception.getClass().getCanonicalName() + " into a " + response.getStatus() + " "
                + "response", exception);
    }//from  w w w.ja v a  2 s .  c  o m
    return response;
}

From source file:org.hawkular.rest.exception.mappers.ExceptionMapperUtils.java

public static Response buildResponse(Throwable exception, Response.Status status) {
    return buildResponse(new ApiError(Throwables.getRootCause(exception).getMessage()), exception, status);
}