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() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.emc.vipr.sync.ViPRSync.java

public static void main(String[] args) {
    ViPRSync sync;//from www  .j a v a 2  s  . com
    try {
        CommandLine line = gnuParser.parse(mainOptions(), args, true);

        // Special check for help
        if (line.hasOption(HELP_OPTION)) {
            longHelp();
            System.exit(0);
        }

        if (line.hasOption(SPRING_CONFIG_OPTION)) {

            // Spring configuration
            sync = springBootstrap(line.getOptionValue(SPRING_CONFIG_OPTION));
        } else {

            // CLI configuration
            sync = cliBootstrap(args);
        }
    } catch (ParseException | ConfigurationException e) {
        System.err.println(e.getMessage());
        shortHelp();
        System.exit(1);
        return;
    }

    int exitCode = 0;
    try {
        sync.run();
    } catch (Throwable t) {
        t.printStackTrace();
        exitCode = 2;
    }

    System.out.print(sync.getStatsString());

    System.exit(exitCode);
}

From source file:hudson.cli.CLI.java

public static void main(final String[] _args) throws Exception {
    try {//from  www  .j  a v a2 s  .  c o  m
        System.exit(_main(_args));
    } catch (NotTalkingToJenkinsException ex) {
        System.err.println(ex.getMessage());
        System.exit(3);
    } catch (Throwable t) {
        // if the CLI main thread die, make sure to kill the JVM.
        t.printStackTrace();
        System.exit(-1);
    }
}

From source file:ca.gnewton.lusql.core.LuSqlMain.java

/**
 * Describe <code>main</code> method here.
 *
 * @param args a <code>String</code> value
 */// ww  w . jav a  2 s .  c o  m
public static final void main(final String[] args) {
    checkForSpecialArguments(args);

    long t0 = System.currentTimeMillis();
    LuSql lusql = new LuSql();
    lusql.setFieldMap(fieldMap);
    boolean optionsFlag;
    try {
        RunState state = handleOptions(lusql, args);
        switch (state) {
        case Done:
            break;
        case Work:
            // Txt file describing how index was made//
            initInfoFile(lusql);
            Util.setOut(infoOut);

            lusql.init();
            if (LuSql.isVerbose())
                printOptions(lusql);
            lusql.run();
            if (LuSql.isVerbose())
                log.info("Elapsed time: " + (System.currentTimeMillis() - t0) / 1000 + " seconds\n");
            if (infoOut != null)
                infoOut.close();
            break;
        case ExplainPlugin:
            explainPlugin();
            break;

        case ShowOptions:
        default:
            usage();
            break;
        }
    } catch (Throwable pe) {
        if (!silent) {
            pe.printStackTrace();
            usage();
        }
        System.exit(42);
    }
}

From source file:edu.umn.cs.sthadoop.operations.HSPKNNQ.java

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

    //./hadoop jar /export/scratch/louai/idea-stHadoop/st-hadoop-uber.jar pknn /mntgIndex/yyyy-MM-dd/2017-08-03 /pknn k:2 point:-78.9659,35.7998 shape:edu.umn.cs.sthadoop.mntg.STPointMntg -overwrite  
    //    args = new String[8];
    //    args[0] = "/export/scratch/mntgData/mntgIndex";
    //    args[1] = "/export/scratch/mntgData/pknn";
    //    args[2] = "-overwrite";
    //    args[3] = "k:10";
    //    args[4] = "point:-78.9659063204100,35.7903907684998";
    //    args[5] = "shape:edu.umn.cs.sthadoop.trajectory.STPointTrajectory";
    //    args[6] = "interval:2017-08-03,2017-08-04";
    //    args[7] = "-overwrite";
    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));
    Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();// w  w  w  .ja va 2 s  .  co m
        System.exit(1);
    }
    if (paths.length > 1 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }

    if (params.get("interval") == null) {
        System.err.println("Temporal range missing");
        printUsage();
        System.exit(1);
    }

    TextSerializable inObj = params.getShape("shape");
    if (!(inObj instanceof STPoint)) {
        if (!(inObj instanceof STRectangle)) {
            LOG.error("Shape is not instance of STPoint or instance of STRectangle");
            printUsage();
            System.exit(1);
        }

    }

    // path to the spatio-temporal index.
    List<Path> STPaths = new ArrayList<Path>();

    try {
        STPaths = STRangeQuery.getIndexedSlices(params);

    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    for (Path input : STPaths) {

        final Path inputFile = input;
        int count = params.getInt("count", 1);
        double closeness = params.getFloat("closeness", -1.0f);
        final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count];
        final FileSystem fs = inputFile.getFileSystem(params);
        final int k = params.getInt("k", 1);
        int concurrency = params.getInt("concurrency", 100);
        if (k == 0) {
            LOG.warn("k = 0");
        }

        if (queryPoints.length == 0) {
            printUsage();
            throw new RuntimeException("Illegal arguments");
        }
        final Path outputPath = paths.length > 1 ? new Path(paths[1].toUri() + "-" + input.getName()) : null;

        if (closeness >= 0) {
            // Get query points according to its closeness to grid intersections
            GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile);
            long seed = params.getLong("seed", System.currentTimeMillis());
            Random random = new Random(seed);
            for (int i = 0; i < count; i++) {
                int i_block = random.nextInt(gindex.size());
                int direction = random.nextInt(4);
                // Generate a point in the given direction
                // Get center point (x, y)
                Iterator<Partition> iterator = gindex.iterator();
                while (i_block-- >= 0)
                    iterator.next();
                Partition partition = iterator.next();
                double cx = (partition.x1 + partition.x2) / 2;
                double cy = (partition.y1 + partition.y2) / 2;
                double cw = partition.x2 - partition.x1;
                double ch = partition.y2 - partition.y1;
                int signx = ((direction & 1) == 0) ? 1 : -1;
                int signy = ((direction & 2) == 1) ? 1 : -1;
                double x = cx + cw * closeness / 2 * signx;
                double y = cy + ch * closeness / 2 * signy;
                queryPoints[i] = new Point(x, y);
            }
        }

        final BooleanWritable exceptionHappened = new BooleanWritable();

        Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread th, Throwable ex) {
                ex.printStackTrace();
                exceptionHappened.set(true);
            }
        };

        // Run each query in a separate thread
        final Vector<Thread> threads = new Vector<Thread>();
        for (int i = 0; i < queryPoints.length; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    try {
                        Point query_point = queryPoints[threads.indexOf(this)];
                        OperationsParams newParams = new OperationsParams(params);
                        OperationsParams.setShape(newParams, "point", query_point);
                        Job job = knn(inputFile, outputPath, params);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.setUncaughtExceptionHandler(h);
            threads.add(thread);
        }

        long t1 = System.currentTimeMillis();
        do {
            // Ensure that there is at least MaxConcurrentThreads running
            int i = 0;
            while (i < concurrency && i < threads.size()) {
                Thread.State state = threads.elementAt(i).getState();
                if (state == Thread.State.TERMINATED) {
                    // Thread already terminated, remove from the queue
                    threads.remove(i);
                } else if (state == Thread.State.NEW) {
                    // Start the thread and move to next one
                    threads.elementAt(i++).start();
                } else {
                    // Thread is still running, skip over it
                    i++;
                }
            }
            if (!threads.isEmpty()) {
                try {
                    // Sleep for 10 seconds or until the first thread terminates
                    threads.firstElement().join(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } while (!threads.isEmpty());
        long t2 = System.currentTimeMillis();
        if (exceptionHappened.get())
            throw new RuntimeException("Not all jobs finished correctly");

        System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis");
        System.out.println("Total iterations: " + TotalIterations);
    }
}

From source file:net.sf.jhylafax.JHylaFAX.java

/**
 * @param args/*from  w w  w . j  ava 2  s .co m*/
 */
public static void main(final String[] args) {
    final ArgsHandler handler = new ArgsHandler();
    handler.evaluate(args);

    evaluateArgumentsPreVisible(handler);

    ThreadGroup tg = new ThreadGroup("JHylaFAXThreadGroup") {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
        }
    };

    //      System.setProperty("sun.awt.exception.handler", 
    //                     "xnap.util.XNapAWTExceptionHandler");
    Thread mainRunner = new Thread(tg, "JHylaFAXMain") {
        public void run() {
            setContextClassLoader(JHylaFAX.class.getClassLoader());

            JHylaFAX app = new JHylaFAX();
            app.setVisible(true);

            app.evaluateArgumentsPostVisible(handler);
        }
    };
    mainRunner.start();
}

From source file:com.amazon.kinesis.streaming.agent.Agent.java

public static void main(String[] args) throws Exception {
    AgentOptions opts = AgentOptions.parse(args);
    String configFile = opts.getConfigFile();
    AgentConfiguration config = tryReadConfigurationFile(Paths.get(opts.getConfigFile()));
    Path logFile = opts.getLogFile() != null ? Paths.get(opts.getLogFile())
            : (config != null ? config.logFile() : null);
    String logLevel = opts.getLogLevel() != null ? opts.getLogLevel()
            : (config != null ? config.logLevel() : null);
    int logMaxBackupFileIndex = (config != null ? config.logMaxBackupIndex() : -1);
    long logMaxFileSize = (config != null ? config.logMaxFileSize() : -1L);
    Logging.initialize(logFile, logLevel, logMaxBackupFileIndex, logMaxFileSize);
    final Logger logger = Logging.getLogger(Agent.class);

    // Install an unhandled exception hook
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override// w  w w  .  ja v a2s. c  om
        public void uncaughtException(Thread t, Throwable e) {
            if (e instanceof OutOfMemoryError) {
                // This prevents the JVM from hanging in case of an OOME
                dontShutdownOnExit = true;
            }
            String msg = "FATAL: Thread " + t.getName() + " threw an unrecoverable error. Aborting application";
            try {
                try { // We don't know if logging is still working
                    logger.error(msg, e);
                } finally {
                    System.err.println(msg);
                    e.printStackTrace();
                }
            } finally {
                System.exit(1);
            }
        }
    });

    try {
        logger.info("Reading configuration from file: {}", configFile);
        if (config == null) {
            config = readConfigurationFile(Paths.get(opts.getConfigFile()));
        }
        // Initialize and start the agent
        AgentContext agentContext = new AgentContext(config);
        if (agentContext.flows().isEmpty()) {
            throw new ConfigurationException("There are no flows configured in configuration file.");
        }
        final Agent agent = new Agent(agentContext);

        // Make sure everything terminates cleanly when process is killed
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                if (!dontShutdownOnExit && agent.isRunning()) {
                    agent.stopAsync();
                    agent.awaitTerminated();
                }
            }
        });

        agent.startAsync();
        agent.awaitRunning();
        agent.awaitTerminated();
    } catch (Exception e) {
        logger.error("Unhandled error.", e);
        System.err.println("Unhandled error.");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:esg.gateway.client.ESGAccessLogClient.java

public static void main(String[] args) {
    String serviceHost = null;//from   w w  w.  j  a  v a2  s.c  o  m
    long startTime = 0;
    long endTime = Long.MAX_VALUE;

    try {
        serviceHost = args[0];
        startTime = Long.parseLong(args[1]);
        endTime = Long.parseLong(args[2]);
    } catch (Throwable t) {
        log.error(t.getMessage());
    }

    try {
        ESGAccessLogClient client = new ESGAccessLogClient();
        if (client.setEndpoint(serviceHost).ping()) {
            List<String[]> results = null;
            results = client.fetchAccessLogData(startTime, endTime);

            System.out.println("---results:[" + (results.size() - 1) + "]---");
            for (String[] record : results) {
                StringBuilder sb = new StringBuilder();
                for (String column : record) {
                    sb.append("[" + column + "] ");
                }
                System.out.println(sb.toString());
            }
        }
        System.out.println("-----------------");
    } catch (Throwable t) {
        log.error(t);
        t.printStackTrace();
    }
}

From source file:com.brainflow.application.toplevel.Brainflow.java

public static void main(String[] args) {

    final Brainflow bflow = getInstance();

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                log.info("Launching Brainflow ...");
                bflow.launch();//from w w  w.  java 2s. c  om
            } catch (Throwable e) {
                Logger.getAnonymousLogger().severe("Error Launching Brainflow, exiting");
                e.printStackTrace();
                System.exit(-1);

            }

        }
    });

}

From source file:edu.harvard.i2b2.navigator.CRCNavigator.java

/**
 * class entry point//from  w ww . java  2 s.  c o  m
 * 
 * @param args
 */
public static void main(String[] args) {
    // create application instance and set name to APP
    new CRCNavigator();
    // remove block on open so that dialog can show on initial startup
    // APP.setBlockOnOpen(true);
    APP.open();
    log.debug(getNow() + " AppStart debug  ");

    // get webservicename from crcnavigator.properties file
    String tempWeb = APP.getCRCNavigatorProperties();
    APP.setWebServiceName(tempWeb);

    // open login dialog
    APP.loginAction(true);
    log.debug(getNow() + " Returned from login dialog");

    Shell mainShell = APP.getShell();
    Display display = mainShell.getDisplay();
    while (mainShell != null && !mainShell.isDisposed()) {
        try {
            if (!display.readAndDispatch())
                display.sleep();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

From source file:com.emc.ecs.sync.EcsSync.java

public static void main(String[] args) {
    int exitCode = 0;

    System.out.println(versionLine());

    RestServer restServer = null;/*from   w  w w.j  ava2s.com*/
    try {

        // first, hush up the JDK logger (why does this default to INFO??)
        java.util.logging.LogManager.getLogManager().getLogger("").setLevel(java.util.logging.Level.WARNING);

        CliConfig cliConfig = CliHelper.parseCliConfig(args);

        if (cliConfig != null) {

            // configure logging for startup
            if (cliConfig.getLogLevel() != null)
                SyncJobService.getInstance().setLogLevel(cliConfig.getLogLevel());

            // start REST service
            if (cliConfig.isRestEnabled()) {
                if (cliConfig.getRestEndpoint() != null) {
                    String[] endpoint = cliConfig.getRestEndpoint().split(":");
                    restServer = new RestServer(endpoint[0], Integer.parseInt(endpoint[1]));
                } else {
                    restServer = new RestServer();
                    restServer.setAutoPortEnabled(true);
                }
                // set DB connect string if provided
                if (cliConfig.getDbConnectString() != null) {
                    SyncJobService.getInstance().setDbConnectString(cliConfig.getDbConnectString());
                }
                restServer.start();
            }

            // if REST-only, skip remaining logic (REST server thread will keep the VM running)
            if (cliConfig.isRestOnly())
                return;

            try {
                // determine sync config
                SyncConfig syncConfig;
                if (cliConfig.getXmlConfig() != null) {
                    syncConfig = loadXmlFile(new File(cliConfig.getXmlConfig()));
                } else {
                    syncConfig = CliHelper.parseSyncConfig(cliConfig, args);
                }

                // create the sync instance
                final EcsSync sync = new EcsSync();
                sync.setSyncConfig(syncConfig);

                // register for REST access
                SyncJobService.getInstance().registerJob(sync);

                // start sync job (this blocks until the sync is complete)
                sync.run();

                // print completion stats
                System.out.print(sync.getStats().getStatsString());
                if (sync.getStats().getObjectsFailed() > 0)
                    exitCode = 3;
            } finally {
                if (restServer != null)
                    try {
                        restServer.stop(0);
                    } catch (Throwable t) {
                        log.warn("could not stop REST service", t);
                    }
            }
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.out.println("    use --help for a detailed (quite long) list of options");
        exitCode = 1;
    } catch (Throwable t) {
        t.printStackTrace();
        exitCode = 2;
    }

    System.exit(exitCode);
}