Example usage for java.io IOException printStackTrace

List of usage examples for java.io IOException printStackTrace

Introduction

In this page you can find the example usage for java.io IOException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

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

Usage

From source file:eu.earthobservatory.org.StrabonEndpoint.client.SPARQLEndpoint.java

public static void main(String args[]) {
    if (args.length < 4) {
        System.err.println(/*w  w w  . j  a va  2s.c o  m*/
                "Usage: eu.earthobservatory.org.StrabonEndpoint.client.SPARQLEndpoint <HOST> <PORT> <APPNAME> [<FORMAT>]");
        System.err.println("       where <HOST>       is the hostname of the Strabon Endpoint");
        System.err.println("             <PORT>       is the port to connect to on the host");
        System.err.println(
                "             <APPNAME>    is the application name of Strabon Endpoint as deployed in the Tomcat container");
        System.err.println("             <QUERY>      is the query to execute on the endpoint");
        System.err.println(
                "             [<FORMAT>]   is the format of your results. Should be one of XML (default), KML, KMZ, GeoJSON, TSV, or HTML.");
        System.exit(1);
    }

    String host = args[0];
    Integer port = new Integer(args[1]);
    String appName = args[2];
    String query = args[3];
    String format = "";

    if (args.length == 5) {
        format = args[4];

    } else {
        format = "XML";
    }

    SPARQLEndpoint endpoint = new SPARQLEndpoint(host, port, appName);

    try {
        EndpointResult result = endpoint.query(query,
                (stSPARQLQueryResultFormat) stSPARQLQueryResultFormat.valueOf(format));

        System.out.println("Status code: " + result.getStatusCode());
        System.out.println("Status text: " + result.getStatusText());
        System.out.println("<----- Result ----->");
        System.out.println(result.getResponse().replaceAll("\n", "\n\t"));
        System.out.println("<----- Result ----->");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:niclients.main.getni.java

/**
 * Main of the GET NI./*from ww w .ja v  a2 s. c  om*/
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) throws UnsupportedEncodingException {
    HttpClient client = new DefaultHttpClient();
    boolean done;
    String dst = null;
    JSONArray loc_array = new JSONArray();
    String c_type;
    HttpResponse response;
    int resp_code = 0;

    if (commandparser(args)) {

        dst = fqdn;
        done = false;

        try {
            while (!done) {
                if (createget(dst, niname)) {

                    response = client.execute(post);
                    resp_code = response.getStatusLine().getStatusCode();

                    if (200 == resp_code) {
                        // Get content type
                        c_type = response.getEntity().getContentType().getValue();

                        if ("application/json".equalsIgnoreCase(c_type)) {
                            // Response is location list
                            InputStream content = response.getEntity().getContent();
                            String resp = convertStreamToString(content);

                            // String to JSONArray
                            Object obj = JSONValue.parse(resp);
                            JSONArray array = (JSONArray) obj;

                            // add new locations to loc_array   
                            for (int i = 0; i < array.size(); i++) {
                                loc_array.add(array.get(i));
                            }
                            // Get next location from the loc_array and remove it from the loc_array
                            if (!loc_array.isEmpty()) {

                                // Check if new dst is type ni://
                                String tmp_dst = loc_array.get(0).toString();
                                tmp_dst = niUtils.mapNiToWKU(loc_array.get(0).toString());

                                if (tmp_dst == null) {
                                    //Check id new dst is type nihttp://
                                    tmp_dst = niUtils.mapNiHttpToWKU(loc_array.get(0).toString());
                                    if (tmp_dst != null)
                                        // is nihttp://
                                        dst = tmp_dst;
                                    else
                                        // is http://
                                        dst = loc_array.get(0).toString();
                                } else {
                                    // is ni://
                                    dst = tmp_dst;
                                }
                                loc_array.remove(0);
                            }
                        } else if ("application/octet-stream".equalsIgnoreCase(c_type)) {
                            // Response is content
                            InputStream content = response.getEntity().getContent();
                            if (output_filename == null)
                                writeCacheCopyToStdOut(content);
                            else {
                                writeCacheCopy(content, output_filename);
                                System.err.println("Content was stored to '" + output_filename + "'");
                            }
                            // so we can end the while
                            done = true;
                        } else {
                            // Response content type is not something we expected
                            System.err.println("Unsupported Content type = " + c_type);
                        }
                    } else {
                        // Response codetype is not success (we expected that)
                        System.err.println("RESP_CODE: " + Integer.toString(resp_code));
                    }
                } else {
                    System.err.println("Command parse failed!");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.google.flightmap.parsing.faa.nfd.tools.NfdAnalyzer.java

public static void main(String args[]) {
    CommandLine line = null;//from  w  w  w.  j ava 2  s  . c o m
    try {
        final CommandLineParser parser = new PosixParser();
        line = parser.parse(OPTIONS, args);
    } catch (ParseException pEx) {
        System.err.println(pEx.getMessage());
        printHelp(line);
        System.exit(1);
    }

    if (line.hasOption(HELP_OPTION)) {
        printHelp(line);
        System.exit(0);
    }

    final String nfdPath = line.getOptionValue(NFD_OPTION);
    final File nfd = new File(nfdPath);

    try {
        (new NfdAnalyzer(nfd)).execute();
    } catch (IOException ioEx) {
        ioEx.printStackTrace();
        System.exit(2);
    }
}

From source file:de.tu.darmstadt.lt.ner.preprocessing.GermaNERMain.java

public static void main(String[] arg) throws Exception {
    long startTime = System.currentTimeMillis();
    String usage = "USAGE: java -jar germanner.jar [-c config.properties] \n"
            + " [-f trainingFileName] -t testFileName -d ModelOutputDirectory-o outputFile";
    long start = System.currentTimeMillis();

    ChangeColon c = new ChangeColon();

    List<String> argList = Arrays.asList(arg);
    try {/*from  w  w w  . java  2s.  c om*/

        if (argList.contains("-c") && argList.get(argList.indexOf("-c") + 1) != null) {
            if (!new File(argList.get(argList.indexOf("-c") + 1)).exists()) {
                LOG.error("Default configuration is read from the system\n");
            } else {
                configFile = new FileInputStream(argList.get(argList.indexOf("-c") + 1));
            }

        }

        if (argList.contains("-t") && argList.get(argList.indexOf("-t") + 1) != null) {
            if (!new File(argList.get(argList.indexOf("-t") + 1)).exists()) {
                LOG.error("There is no test file to tag");
                System.exit(1);
            }
            Configuration.testFileName = argList.get(argList.indexOf("-t") + 1);
        }

        if (argList.contains("-f") && argList.get(argList.indexOf("-f") + 1) != null) {
            if (!new File(argList.get(argList.indexOf("-f") + 1)).exists()) {
                LOG.error("The system is running in tagging mode. No training data provided");
            } else {
                Configuration.trainFileName = argList.get(argList.indexOf("-f") + 1);
            }
        }

        if (argList.contains("-d") && argList.get(argList.indexOf("-d") + 1) != null) {
            if (new File(argList.get(argList.indexOf("-d") + 1)).exists()) {
                Configuration.modelDir = argList.get(argList.indexOf("-d") + 1);
            } else {
                File dir = new File(argList.get(argList.indexOf("-d") + 1));
                dir.mkdirs();
                Configuration.modelDir = dir.getAbsolutePath();
            }
        }
        // load a properties file
        initNERModel();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    try {
        setModelDir();

        File outputtmpFile = new File(modelDirectory, "result.tmp");
        File outputFile = null;
        if (argList.contains("-o") && argList.get(argList.indexOf("-o") + 1) != null) {
            outputFile = new File(argList.get(argList.indexOf("-o") + 1));
        } else {
            LOG.error("The directory for this output file does not exist. Output file "
                    + "will be found in the current directury under folder \"output\"");
            outputFile = new File(modelDirectory, "result.tsv");
        }

        if (Configuration.mode.equals("ft")
                && (Configuration.trainFileName == null || Configuration.testFileName == null)) {
            LOG.error(usage);
            System.exit(1);
        }
        if (Configuration.mode.equals("f") && Configuration.trainFileName == null) {
            LOG.error(usage);
            System.exit(1);
        }
        if (Configuration.mode.equals("t") && Configuration.testFileName == null) {
            LOG.error(usage);
            System.exit(1);
        }

        if (Configuration.mode.equals("f") && Configuration.trainFileName != null) {
            c.normalize(Configuration.trainFileName, Configuration.trainFileName + ".normalized");
            System.out.println("Start model generation");
            writeModel(new File(Configuration.trainFileName + ".normalized"), modelDirectory);
            System.out.println("Start model generation -- done");
            System.out.println("Start training");
            trainModel(modelDirectory);
            System.out.println("Start training ---done");
        } else if (Configuration.mode.equals("ft") && Configuration.trainFileName != null
                && Configuration.testFileName != null) {
            c.normalize(Configuration.trainFileName, Configuration.trainFileName + ".normalized");
            c.normalize(Configuration.testFileName, Configuration.testFileName + ".normalized");
            System.out.println("Start model generation");
            writeModel(new File(Configuration.trainFileName + ".normalized"), modelDirectory);
            System.out.println("Start model generation -- done");
            System.out.println("Start training");
            trainModel(modelDirectory);
            System.out.println("Start training ---done");
            System.out.println("Start tagging");
            classifyTestFile(modelDirectory, new File(Configuration.testFileName + ".normalized"),
                    outputtmpFile, null, null);
            System.out.println("Start tagging ---done");

            // re-normalized the colon changed text
            c.deNormalize(outputtmpFile.getAbsolutePath(), outputFile.getAbsolutePath());
        } else {
            c.normalize(Configuration.testFileName, Configuration.testFileName + ".normalized");
            System.out.println("Start tagging");
            classifyTestFile(modelDirectory, new File(Configuration.testFileName + ".normalized"),
                    outputtmpFile, null, null);
            // re-normalized the colon changed text
            c.deNormalize(outputtmpFile.getAbsolutePath(), outputFile.getAbsolutePath());

            System.out.println("Start tagging ---done");
        }
        long now = System.currentTimeMillis();
        UIMAFramework.getLogger().log(Level.INFO, "Time: " + (now - start) + "ms");
    } catch (Exception e) {
        LOG.error(usage);
        e.printStackTrace();
    }
    long endTime = System.currentTimeMillis();
    long totalTime = endTime - startTime;
    System.out.println("NER tarin/test done in " + totalTime / 1000 + " seconds");

}

From source file:SWTBrowserDemo.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new FillLayout());
    shell.setText(getResourceString("window.title"));
    InputStream stream = SWTBrowserDemo.class.getResourceAsStream(iconLocation);
    Image icon = new Image(display, stream);
    shell.setImage(icon);/*from  ww w  .j  a va2  s.co m*/
    try {
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    SWTBrowserDemo app = new SWTBrowserDemo(shell, true);
    app.setShellDecoration(icon, true);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    icon.dispose();
    app.dispose();
    display.dispose();
}

From source file:edu.caltech.ipac.firefly.server.catquery.SDSSQuery.java

public static void main(String[] args) {
    String url = "http://skyserver.sdss3.org/dr10/en/tools/search/x_sql.aspx?format=csv&cmd=SELECT%20p.objId,p.run,p.rerun,p.camcol,p.field,mjd,distance%20FROM%20PhotoObj%20as%20p%20JOIN%20dbo.fGetNearbyObjEq(185.0,-0.5,1)%20AS%20R%20ON%20P.objID=R.objID%20ORDER%20BY%20distance";
    URLConnection conn;/*w ww  .  j  a  v a  2  s  .  co m*/
    try {
        conn = URLDownload.makeConnection(new URL(url));
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    conn.setRequestProperty("Accept", "text/plain");

    try {
        URLDownload.getDataToFile(conn, new File("/tmp/a.csv"));
    } catch (FailedRequestException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:server.GeneralSPARQLEndpoint.java

public static void main(String args[]) {
    if (args.length < 4) {
        System.err.println(/*from  w  w  w  . j  av a2  s  .co m*/
                "Usage: eu.earthobservatory.org.StrabonEndpoint.client.SPARQLEndpoint <HOST> <PORT> <APPNAME> [<FORMAT>]");
        System.err.println("       where <HOST>       is the hostname of the Strabon Endpoint");
        System.err.println("             <PORT>       is the port to connect to on the host");
        System.err.println(
                "             <APPNAME>    is the application name of Strabon Endpoint as deployed in the Tomcat container");
        System.err.println("             <QUERY>      is the query to execute on the endpoint");
        System.err.println(
                "             [<FORMAT>]   is the format of your results. Should be one of XML (default), KML, KMZ, GeoJSON, TSV, or HTML.");
        System.exit(1);
    }

    String host = args[0];
    Integer port = new Integer(args[1]);
    String appName = args[2];
    String query = args[3];
    String format = "";
    String endpointType = "";

    if (args.length == 5) {
        format = args[4];

    } else {
        format = "XML";
    }

    GeneralSPARQLEndpoint endpoint = new GeneralSPARQLEndpoint(host, port, appName);

    try {
        EndpointResult result = endpoint.query(query,
                (stSPARQLQueryResultFormat) stSPARQLQueryResultFormat.valueOf(format), endpointType);

        System.out.println("Status code: " + result.getStatusCode());
        System.out.println("Status text: " + result.getStatusText());
        System.out.println("<----- Result ----->");
        System.out.println(result.getResponse().replaceAll("\n", "\n\t"));
        System.out.println("<----- Result ----->");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java

/**
 * @param args/*from   w w w .  j a v a 2s  .  c  om*/
 */
public static void main(String[] args) {

    // process command-line options
    Options options = new Options();
    options.addOption("n", "noaddr", false, "do not do any address matching (for testing)");
    options.addOption("i", "info", false, "create and populate address information table");
    options.addOption("h", "help", false, "this message");

    // database connection
    options.addOption("s", "server", true, "database server to connect to");
    options.addOption("d", "database", true, "OSM database name");
    options.addOption("u", "user", true, "OSM database user name");
    options.addOption("p", "pass", true, "OSM database password");

    // logging options
    options.addOption("l", "logdir", true, "log file directory (default './logs')");
    options.addOption("e", "loglevel", true, "log level (default 'FINEST')");

    // automatically generate the help statement
    HelpFormatter help_formatter = new HelpFormatter();

    // database URI for connection
    String dburi = null;

    // Information message for help screen
    String info_msg = "IzbirkomExtractor [options] <html_directory>";

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('h') || cmd.getArgs().length != 1) {
            help_formatter.printHelp(info_msg, options);
            System.exit(1);
        }

        /* prohibit n and i together */
        if (cmd.hasOption('n') && cmd.hasOption('i')) {
            System.err.println("Options 'n' and 'i' cannot be used together.");
            System.exit(1);
        }

        /* require database arguments without -n */
        if (cmd.hasOption('n')
                && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) {
            System.err.println("Options 'n' and does not need any databse parameters.");
            System.exit(1);
        }

        /* require all 4 database options to be used together */
        if (!cmd.hasOption('n')
                && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) {
            System.err.println(
                    "For database access all of the following arguments have to be specified: server, database, user, pass");
            System.exit(1);
        }

        /* useful variables */
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm");
        String dateString = formatter.format(new Date());

        /* setup logging */
        File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs");
        FileUtils.forceMkdir(logdir);
        File log_file_name = new File(
                logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log");
        FileHandler log_file = new FileHandler(log_file_name.getPath());

        /* create "latest" link to currently created log file */
        Path latest_log_link = Paths.get(logdir + "/latest");
        Files.deleteIfExists(latest_log_link);
        Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName()));

        log_file.setFormatter(new SimpleFormatter());
        LogManager.getLogManager().reset(); // prevents logging to console
        logger.addHandler(log_file);
        logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST);

        // open directory with HTML files and create file list
        File dir = new File(cmd.getArgs()[0]);
        if (!dir.isDirectory()) {
            System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting");
            System.exit(1);
        }
        PathMatcher pmatcher = FileSystems.getDefault()
                .getPathMatcher("glob:?  * ?*.html");
        ArrayList<File> html_files = new ArrayList<>();
        for (Path file : Files.newDirectoryStream(dir.toPath()))
            if (pmatcher.matches(file.getFileName()))
                html_files.add(file.toFile());
        if (html_files.size() == 0) {
            System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting");
            System.exit(1);
        }

        // create csvResultSink
        FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv");
        OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8");
        ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#'));

        // Connect to DB and osmAddressMatcher
        AddressMatcher osmAddressMatcher;
        DBSink dbSink = null;
        DBInfoSink dbInfoSink = null;
        if (cmd.hasOption('n')) {
            osmAddressMatcher = new DummyAddressMatcher();
        } else {
            dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d');
            Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'),
                    cmd.getOptionValue('p'));
            osmAddressMatcher = new OsmAddressMatcher(con);
            dbSink = new DBSink(con);
            if (cmd.hasOption('i'))
                dbInfoSink = new DBInfoSink(con);
        }

        /* create resultsinks */
        SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor();
        sm.addResultSink(csvResultSink);
        if (dbSink != null) {
            sm.addResultSink(dbSink);
            if (dbInfoSink != null)
                sm.addResultSink(dbInfoSink);
        }

        // create tableExtractor
        TableExtractor te = new TableExtractor(osmAddressMatcher, sm);

        // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters

        // iterate through files
        logger.info("Start processing " + html_files.size() + " files in " + dir);
        for (int i = 0; i < html_files.size(); i++) {
            System.err.println("Parsing #" + i + ": " + html_files.get(i));
            te.processHTMLfile(html_files.get(i));
        }

        System.err.println("Processed " + html_files.size() + " HTML files");
        logger.info("Finished processing " + html_files.size() + " files in " + dir);

    } catch (ParseException e1) {
        System.err.println("Failed to parse CLI: " + e1.getMessage());
        help_formatter.printHelp(info_msg, options);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("I/O Exception: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    } catch (SQLException e) {
        System.err.println("Database '" + dburi + "': " + e.getMessage());
        System.exit(1);
    } catch (ResultSinkException e) {
        System.err.println("Failed to initialize ResultSink: " + e.getMessage());
        System.exit(1);
    } catch (TableExtractorException e) {
        System.err.println("Failed to initialize Table Extractor: " + e.getMessage());
        System.exit(1);
    } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) {
        System.err.println("Something really odd happened: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:edu.umn.cs.spatialHadoop.operations.RangeQuery.java

public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));

    final Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();/*from  ww w  . j av a 2s .c  om*/
        System.exit(1);
    }
    if (paths.length >= 2 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }
    if (params.get("rect") == null) {
        System.err.println("You must provide a query range");
        printUsage();
        System.exit(1);
    }
    final Path inPath = params.getInputPath();
    final Path outPath = params.getOutputPath();
    final Rectangle[] queryRanges = params.getShapes("rect", new Rectangle());

    // All running jobs
    final Vector<Long> resultsCounts = new Vector<Long>();
    Vector<Job> jobs = new Vector<Job>();
    Vector<Thread> threads = new Vector<Thread>();

    long t1 = System.currentTimeMillis();
    for (int i = 0; i < queryRanges.length; i++) {
        final OperationsParams queryParams = new OperationsParams(params);
        OperationsParams.setShape(queryParams, "rect", queryRanges[i]);
        if (OperationsParams.isLocal(new JobConf(queryParams), inPath)) {
            // Run in local mode
            final Rectangle queryRange = queryRanges[i];
            final Shape shape = queryParams.getShape("shape");
            final Path output = outPath == null ? null
                    : (queryRanges.length == 1 ? outPath : new Path(outPath, String.format("%05d", i)));
            Thread thread = new Thread() {
                @Override
                public void run() {
                    FSDataOutputStream outFile = null;
                    final byte[] newLine = System.getProperty("line.separator", "\n").getBytes();
                    try {
                        ResultCollector<Shape> collector = null;
                        if (output != null) {
                            FileSystem outFS = output.getFileSystem(queryParams);
                            final FSDataOutputStream foutFile = outFile = outFS.create(output);
                            collector = new ResultCollector<Shape>() {
                                final Text tempText = new Text2();

                                @Override
                                public synchronized void collect(Shape r) {
                                    try {
                                        tempText.clear();
                                        r.toText(tempText);
                                        foutFile.write(tempText.getBytes(), 0, tempText.getLength());
                                        foutFile.write(newLine);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            };
                        } else {
                            outFile = null;
                        }
                        long resultCount = rangeQueryLocal(inPath, queryRange, shape, queryParams, collector);
                        resultsCounts.add(resultCount);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (outFile != null)
                                outFile.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            thread.start();
            threads.add(thread);
        } else {
            // Run in MapReduce mode
            queryParams.setBoolean("background", true);
            Job job = rangeQueryMapReduce(inPath, outPath, queryParams);
            jobs.add(job);
        }
    }

    while (!jobs.isEmpty()) {
        Job firstJob = jobs.firstElement();
        firstJob.waitForCompletion(false);
        if (!firstJob.isSuccessful()) {
            System.err.println("Error running job " + firstJob);
            System.err.println("Killing all remaining jobs");
            for (int j = 1; j < jobs.size(); j++)
                jobs.get(j).killJob();
            System.exit(1);
        }
        Counters counters = firstJob.getCounters();
        Counter outputRecordCounter = counters.findCounter(Task.Counter.MAP_OUTPUT_RECORDS);
        resultsCounts.add(outputRecordCounter.getValue());
        jobs.remove(0);
    }
    while (!threads.isEmpty()) {
        try {
            Thread thread = threads.firstElement();
            thread.join();
            threads.remove(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    long t2 = System.currentTimeMillis();

    System.out.println("Time for " + queryRanges.length + " jobs is " + (t2 - t1) + " millis");
    System.out.println("Results counts: " + resultsCounts);
}

From source file:net.dv8tion.jda.player.Bot.java

public static void main(String[] args) {
    try {/*from www  . ja v  a 2s  .  c o  m*/
        JSONObject obj = new JSONObject(new String(Files.readAllBytes(Paths.get("Config.json"))));
        JDA api = new JDABuilder().setBotToken(obj.getString("botToken")).addListener(new Bot())
                .buildBlocking();

    } catch (IllegalArgumentException e) {
        System.out.println("The config was not populated. Please provide a token.");
    } catch (LoginException e) {
        System.out.println("The provided botToken was incorrect. Please provide valid details.");
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        System.err.println(
                "Encountered a JSON error. Most likely caused due to an outdated or ill-formated config.\n"
                        + "Please delete the config so that it can be regenerated. JSON Error:\n");
        e.printStackTrace();
    } catch (IOException e) {
        JSONObject obj = new JSONObject();
        obj.put("botToken", "");
        try {
            Files.write(Paths.get("Config.json"), obj.toString(4).getBytes());
            System.out.println("No config file was found. Config.json has been generated, please populate it!");
        } catch (IOException e1) {
            System.out.println("No config file was found and we failed to generate one.");
            e1.printStackTrace();
        }
    }
}