List of usage examples for org.apache.commons.cli ParseException printStackTrace
public void printStackTrace()
From source file:com.google.endpoints.examples.bookstore.BookstoreServer.java
public static void main(String[] args) throws Exception { Options options = createOptions();//from w w w . j av a 2s.c o m CommandLineParser parser = new DefaultParser(); CommandLine line; try { line = parser.parse(options, args); } catch (ParseException e) { System.err.println("Invalid command line: " + e.getMessage()); printUsage(options); return; } int port = DEFAULT_PORT; if (line.hasOption("port")) { String portOption = line.getOptionValue("port"); try { port = Integer.parseInt(portOption); } catch (java.lang.NumberFormatException e) { System.err.println("Invalid port number: " + portOption); printUsage(options); return; } } final BookstoreData data = initializeBookstoreData(); final BookstoreServer server = new BookstoreServer(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { System.out.println("Shutting down"); server.stop(); } catch (Exception e) { e.printStackTrace(); } } }); server.start(port, data); System.out.format("Bookstore service listening on %d\n", port); server.blockUntilShutdown(); }
From source file:lemontree.modulenetwork.RunCli.java
/** * Parse command line options and run LeMoNe * /*from w w w . j a v a 2 s . c o m*/ * @param args command-line arguments string * */ public static void main(String[] args) { // set dummy values for those parameters, they'll be filled later String task = null; String gene_file = null; String data_file = null; String reg_file = null; String tree_file = null; String output_file = null; String range = null; int num_steps = 0; int burn_in = 0; int sample_steps = 0; String cluster_file = null; String go_annot_file = null; String go_ref_file = null; String top_regulators = null; String map_file = null; String go_ontology_file = null; String draw_experiment_color = null; // set default values for those parameters, users can override them double alpha = 0.1; double beta = 0.1; double mu = 0.0; double lambda = 0.1; double score_gain = 0.0; int init_num_clust = 0; int num_runs = 1; boolean use_bayesian_score = true; int num_reg = 10; double beta_reg = 20; String go_p_value = "0.05"; String go_namespace = "biological_process"; boolean use_global_mean = false; boolean use_regulator_mean = false; int cut_level = 0; double min_weight = 0.25; int min_clust_size = 10; int min_clust_score = 2; Boolean node_clustering = true; boolean draw_experiment_names = true; // create the different options Options opts = new Options(); opts.addOption("task", true, "task to perform"); opts.addOption("gene_file", true, "gene file"); opts.addOption("data_file", true, "data file (genes)"); opts.addOption("reg_file", true, "regulators file"); opts.addOption("tree_file", true, "tree file"); opts.addOption("output_file", true, "output file name"); opts.addOption("num_steps", true, "number of steps (Gibbs sampler)"); opts.addOption("burn_in", true, "number of burn-in steps (Gibbs sampler)"); opts.addOption("sample_steps", true, "sample steps interval (Gibbs sampler)"); opts.addOption("cluster_file", true, "cluster file name"); opts.addOption("num_clust", true, "number of clusters"); opts.addOption("alpha", true, "alpha0 parameter value"); opts.addOption("beta", true, "beta0 parameter value"); opts.addOption("mu", true, "mu0 parameter value"); opts.addOption("lambda", true, "lambda0 parameter value"); opts.addOption("score_gain", true, "score gain cutoff value"); opts.addOption("init_num_clust", true, "initial number of clusters (Gibbs sampler)"); opts.addOption("num_runs", true, "number of runs (Gibbs sampler)"); opts.addOption("num_reg", true, "maximum number of regulators assigned for each node"); opts.addOption("beta_reg", true, "beta parameter value for regulators assignment"); opts.addOption("num_split", true, "number of splits for the module set"); opts.addOption("prefix", true, "java command prefix for the split option command line"); opts.addOption("range", true, "module set range for the assignment of the regulators"); opts.addOption("go_annot_file", true, "GO custom annotation file"); opts.addOption("go_ontology_file", true, "GO ontology file name"); opts.addOption("go_ref_file", true, "GO refence gene list file name"); opts.addOption("go_p_value", true, "GO p-value cutoff"); opts.addOption("go_namespace", true, "GO namespace"); opts.addOption("go_annot_def", false, "GO annotation file flag"); opts.addOption("matlab", false, "Matlab format for output files"); opts.addOption("help", false, "help"); opts.addOption("h", false, "help"); opts.addOption("top_regulators", true, "Top regulators file name"); opts.addOption("use_global_mean", false, "Use global mean for the figures"); opts.addOption("use_regulator_mean", false, "Use regulator mean for the figures"); opts.addOption("all_regulators", false, "Print all regulators"); opts.addOption("map_file", true, "Gene names map file"); opts.addOption("cut_level", true, "Regulation tree cut level"); opts.addOption("min_weight", true, "Tight clusters minimum weight"); opts.addOption("min_clust_size", true, "Tight clusters minimum cluster size"); opts.addOption("min_clust_score", true, "Tight clusters minimum cluster score"); opts.addOption("node_clustering", true, "Perform node clustering (true) or edge clustering (false)"); opts.addOption("draw_experiment_names", true, "Draw experiment names in the figures"); opts.addOption("draw_experiment_color", true, "Draw experiment color codes in the figures"); // build a parser object and parse the command line (!) CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(opts, args); if (cmd.hasOption("min_weight")) min_weight = Double.parseDouble(cmd.getOptionValue("min_weight")); if (cmd.hasOption("min_clust_size")) min_clust_size = Integer.parseInt(cmd.getOptionValue("min_clust_size")); if (cmd.hasOption("min_clust_score")) min_clust_score = Integer.parseInt(cmd.getOptionValue("min_clust_score")); if (cmd.hasOption("task")) task = cmd.getOptionValue("task"); if (cmd.hasOption("data_file")) data_file = cmd.getOptionValue("data_file"); if (cmd.hasOption("tree_file")) tree_file = cmd.getOptionValue("tree_file"); if (cmd.hasOption("gene_file")) gene_file = cmd.getOptionValue("gene_file"); if (cmd.hasOption("reg_file")) reg_file = cmd.getOptionValue("reg_file"); if (cmd.hasOption("output_file")) output_file = cmd.getOptionValue("output_file"); if (cmd.hasOption("cluster_file")) cluster_file = cmd.getOptionValue("cluster_file"); if (cmd.hasOption("alpha")) alpha = Double.parseDouble(cmd.getOptionValue("alpha")); if (cmd.hasOption("beta")) beta = Double.parseDouble(cmd.getOptionValue("beta")); if (cmd.hasOption("lambda")) lambda = Double.parseDouble(cmd.getOptionValue("lambda")); if (cmd.hasOption("mu")) mu = Double.parseDouble(cmd.getOptionValue("mu")); if (cmd.hasOption("score_gain")) score_gain = Double.parseDouble(cmd.getOptionValue("score_gain")); if (cmd.hasOption("num_steps")) num_steps = Integer.parseInt(cmd.getOptionValue("num_steps")); if (cmd.hasOption("burn_in")) burn_in = Integer.parseInt(cmd.getOptionValue("burn_in")); if (cmd.hasOption("sample_steps")) sample_steps = Integer.parseInt(cmd.getOptionValue("sample_steps")); if (cmd.hasOption("init_num_clust")) init_num_clust = Integer.parseInt(cmd.getOptionValue("init_num_clust")); if (cmd.hasOption("num_reg")) num_reg = Integer.parseInt(cmd.getOptionValue("num_reg")); if (cmd.hasOption("beta_reg")) beta_reg = Double.parseDouble(cmd.getOptionValue("beta_reg")); if (cmd.hasOption("range")) range = cmd.getOptionValue("range"); if (cmd.hasOption("go_annot_file")) go_annot_file = cmd.getOptionValue("go_annot_file"); if (cmd.hasOption("go_ontology_file")) go_ontology_file = cmd.getOptionValue("go_ontology_file"); if (cmd.hasOption("go_ref_file")) go_ref_file = cmd.getOptionValue("go_ref_file"); if (cmd.hasOption("go_p_value")) go_p_value = cmd.getOptionValue("go_p_value"); if (cmd.hasOption("go_namespace")) go_namespace = cmd.getOptionValue("go_namespace"); if (cmd.hasOption("top_regulators")) top_regulators = cmd.getOptionValue("top_regulators"); if (cmd.hasOption("use_global_mean")) use_global_mean = true; if (cmd.hasOption("use_regulator_mean")) use_regulator_mean = true; if (cmd.hasOption("map_file")) map_file = cmd.getOptionValue("map_file"); if (cmd.hasOption("cut_level")) cut_level = Integer.parseInt(cmd.getOptionValue("cut_level")); if (cmd.hasOption("node_clustering")) if (cmd.getOptionValue("node_clustering").equalsIgnoreCase("false")) node_clustering = false; if (cmd.hasOption("draw_experiment_names")) if (cmd.getOptionValue("draw_experiment_names").equalsIgnoreCase("false")) draw_experiment_names = false; if (cmd.hasOption("draw_experiment_color")) draw_experiment_color = cmd.getOptionValue("draw_experiment_color"); } catch (ParseException exp) { System.out.println("Error while parsing command line:"); System.out.println(); exp.printStackTrace(); System.exit(1); } // print header printBanner(); // something has to be done, we need a task to be set if (task == null) Die("Error: task option must be set."); // --------------------------------------------------------------- // ganesh task: 2-way clustering of genes using the gibbs sampler // --------------------------------------------------------------- if (task.equalsIgnoreCase("ganesh")) { // those parameters must be set if (data_file == null) Die("Error: data_file option must be set."); if (output_file == null) Die("Error: output_file option must be set."); // set default values if the user did not change them if (num_runs == 0) num_runs = 1; if (num_steps == 0) num_steps = 100; if (burn_in == 0) burn_in = 50; if (sample_steps == 0) sample_steps = 100; System.out.println("Parameters"); System.out.println("----------"); System.out.println("task: " + task); System.out.println("data_file: " + data_file); System.out.println("gene_file: " + gene_file); System.out.println("output_file: " + output_file); System.out.println("lambda: " + lambda); System.out.println("mu: " + mu); System.out.println("alpha: " + alpha); System.out.println("beta: " + beta); System.out.println("num_steps: " + num_steps); System.out.println("burn_in: " + burn_in); System.out.println("sample_steps: " + sample_steps); System.out.println("score_gain: " + score_gain); // Create ModuleNetwork object ModuleNetwork M = new ModuleNetwork(); M.setNormalGammaPriors(lambda, mu, alpha, beta); M.readExpressionMatrix(data_file, gene_file); M.setNormalGammaPriors(lambda, mu, alpha, beta); // Gibbs sample different module sets with one tree per module M.gibbsSamplerGenes(init_num_clust, num_runs, num_steps, burn_in, sample_steps, score_gain, use_bayesian_score); // write results to text file M.writeClusters(output_file); } //------------------------------------------------------------------------------------- // tight_clusters task: node clustering to produce tight clusters //------------------------------------------------------------------------------------- else if (task.equalsIgnoreCase("tight_clusters")) { if (data_file == null) Die("Error: data_file option must be set."); if (cluster_file == null) Die("Error: cluster_file option must be set."); if (output_file == null) Die("Error: output_file option must be set."); System.out.println("Parameters"); System.out.println("----------"); System.out.println("task: " + task); System.out.println("data_file: " + data_file); System.out.println("cluster_file: " + cluster_file); System.out.println("output_file: " + output_file); System.out.println("node_clustering: " + node_clustering); System.out.println("min_weight: " + min_weight); System.out.println("min_clust_size: " + min_clust_size); System.out.println("min_clust_score: " + min_clust_score); System.out.println(); ModuleNetwork M = new ModuleNetwork(); M.readExpressionMatrix(data_file, null); M.readMultipleClusters(cluster_file); // find tight clusters with node clustering algorithm CentroidClustering cc = new CentroidClustering(M, node_clustering, min_weight, min_clust_size, min_clust_score); cc.doCentroidClustering(); cc.printClusters(output_file); } //------------------------------------------------------------------------------------- // regulators task: learn regulation programs (gibbs sampling exp. + assign regulators) //------------------------------------------------------------------------------------- else if (task.equalsIgnoreCase("regulators")) { // those parameters must be set if (data_file == null) Die("Error: data_file option must be set."); if (reg_file == null) Die("Error: reg_file option must be set."); if (cluster_file == null) Die("Error: cluster_file option must be set."); if (output_file == null) Die("Error: output_file option must be set."); // set default values if the user did not change them if (num_steps == 0) num_steps = 1100; if (burn_in == 0) burn_in = 100; if (sample_steps == 0) sample_steps = 100; System.out.println("Parameters"); System.out.println("----------"); System.out.println("task: " + task); System.out.println("data_file: " + data_file); System.out.println("reg_file: " + reg_file); System.out.println("cluster_file: " + cluster_file); System.out.println("output_file: " + output_file); System.out.println("lambda: " + lambda); System.out.println("mu: " + mu); System.out.println("alpha: " + alpha); System.out.println("beta: " + beta); System.out.println("num_runs: " + num_runs); System.out.println("num_steps: " + num_steps); System.out.println("burn_in: " + burn_in); System.out.println("sample_steps: " + sample_steps); System.out.println("score_gain: " + score_gain); System.out.println("num_reg: " + num_reg); // create module network object ModuleNetwork M = new ModuleNetwork(); M.setNormalGammaPriors(lambda, mu, alpha, beta); M.readExpressionMatrix(data_file, null); M.readClusters(cluster_file); M.readRegulators(reg_file); M.initStatisticsAndScore(); M.setDataMeanAndSDFromModuleset(); // cluster experiments using the gibbs sampler M.gibbsSamplerExpts(num_runs, num_steps, burn_in, sample_steps, score_gain, use_bayesian_score); // assign regulators M.assignRegulatorsNoAcyclStoch(beta_reg, num_reg); // write results as text file with all regulators, top 1%, random regulators and regulations trees as xml M.printRegulators(output_file + ".allreg.txt", true, false); M.printRegulators(output_file + ".topreg.txt", false, false); M.printRandomRegulators(output_file + ".randomreg.txt", false); M.writeRegTreeXML(output_file + ".xml.gz"); } //---------------------------------------------------------- // experiments task: cluster conditions using gibbs sampling //---------------------------------------------------------- else if (task.equalsIgnoreCase("experiments")) { // those parameters must be set if (data_file == null) Die("Error: data_file option must be set."); if (cluster_file == null) Die("Error: cluster_file option must be set."); if (output_file == null) Die("Error: output_file option must be set."); // set default values if the user did not change them if (num_steps == 0) num_steps = 1100; if (burn_in == 0) burn_in = 100; if (sample_steps == 0) sample_steps = 100; System.out.println("Parameters"); System.out.println("----------"); System.out.println("task: " + task); System.out.println("data_file: " + data_file); System.out.println("cluster_file: " + cluster_file); System.out.println("output_file: " + output_file); System.out.println("lambda: " + lambda); System.out.println("mu: " + mu); System.out.println("alpha: " + alpha); System.out.println("beta: " + beta); System.out.println("num_steps: " + num_steps); System.out.println("burn_in: " + burn_in); System.out.println("sample_steps: " + sample_steps); System.out.println("score_gain: " + score_gain); // read data and clusters ModuleNetwork M = new ModuleNetwork(); M.setNormalGammaPriors(lambda, mu, alpha, beta); M.readExpressionMatrix(data_file, null); M.readClusters(cluster_file); M.initStatisticsAndScore(); // cluster experiments using the gibbs sampler M.gibbsSamplerExpts(num_runs, num_steps, burn_in, sample_steps, score_gain, use_bayesian_score); // write results as xml file M.writeRegTreeXML(output_file); } //--------------------------------------------------------------- // split_reg task: assign regulators for a given range of modules //--------------------------------------------------------------- else if (task.equalsIgnoreCase("split_reg")) { // those parameters must be set if (data_file == null) Die("Error: data_file option must be set."); if (reg_file == null) Die("Error: reg_file option must be set."); if (cluster_file == null) Die("Error: cluster_file option must be set."); if (tree_file == null) Die("Error: tree_file option must be set."); if (output_file == null) Die("Error: output_file option must be set."); if (range == null) Die("Error: range option must be set."); System.out.println("Parameters"); System.out.println("----------"); System.out.println("task: " + task); System.out.println("data_file: " + data_file); System.out.println("reg_file: " + reg_file); System.out.println("cluster_file: " + cluster_file); System.out.println("output_file: " + output_file); System.out.println("num_reg: " + num_reg); System.out.println("beta_reg: " + beta_reg); System.out.println("range: " + range); ModuleNetwork M = new ModuleNetwork(); M.setNormalGammaPriors(lambda, mu, alpha, beta); M.readExpressionMatrix(data_file, null); M.readClusters(cluster_file); M.readRegulators(reg_file); M.initStatisticsAndScore(); M.readRegTreeXML(tree_file); String[] val = range.split(":"); int start_module = Integer.parseInt(val[0]); int stop_module = Integer.parseInt(val[1]); // assign regulators M.assignRegulatorsNoAcyclStoch(beta_reg, num_reg, start_module, stop_module); // write results M.printRegulators(output_file + ".allreg.txt", true, false); M.printRandomRegulators(output_file + ".randomreg.txt", false); M.writeRegTreeXML(output_file + ".xml.gz"); } //---------------------------------------------------------------------------- // go_annotation task: GO annotation of a cluster file //---------------------------------------------------------------------------- else if (task.equalsIgnoreCase("go_annotation")) { // those parameters must be set if (cluster_file == null) Die("Error: cluster_file parameter must be set."); if (output_file == null) Die("Error: output_file option must be set."); if (go_annot_file == null) Die("Error: go_annot_file option must be set."); if (go_ontology_file == null) Die("Error: go_ontology_file option must be set."); if (go_ref_file == null) Die("Error: go_ref_file option must be set."); System.out.println("Parameters"); System.out.println("----------"); System.out.println("task: " + task); System.out.println("cluster_file: " + cluster_file); System.out.println("output_file: " + output_file); System.out.println("go_annot_file: " + go_annot_file); System.out.println("go_ontology_file: " + go_ontology_file); System.out.println("go_ref_file: " + go_ref_file); System.out.println("go_p_value: " + go_p_value); System.out.println("go_namespace: " + go_namespace); System.out.println("map_file " + map_file); BiNGO b = new BiNGO(go_annot_file, go_ontology_file, go_p_value, go_namespace); try { b.GOstats(cluster_file, go_ref_file, output_file, map_file); } catch (IOException e) { e.printStackTrace(); } } //---------------------------------------------------------------------------- // figures task: create eps figures for each module //---------------------------------------------------------------------------- else if (task.equalsIgnoreCase("figures")) { // those parameters must be set if (top_regulators == null) Die("Error: top_regulators option must be set."); if (data_file == null) Die("Error: data_file option must be set."); if (reg_file == null) Die("Error: reg_file option must be set."); if (cluster_file == null) Die("Error: cluster_file option must be set."); if (tree_file == null) Die("Error: tree_file option must be set."); System.out.println("Parameters"); System.out.println("----------"); System.out.println("task: " + task); System.out.println("data_file: " + data_file); System.out.println("reg_file: " + reg_file); System.out.println("cluster_file: " + cluster_file); System.out.println("tree_file: " + tree_file); System.out.println("top_regulators: " + top_regulators); System.out.println("use_regulator_mean: " + use_regulator_mean); System.out.println("use_global_mean: " + use_global_mean); System.out.println("map_file: " + map_file); System.out.println("cut_level: " + cut_level); System.out.println("draw_experiment_names: " + draw_experiment_names); System.out.println("draw_experiment_color: " + draw_experiment_color); ModuleNetwork M = new ModuleNetwork(); //read expression data, genes, clusters and regulators from files M.setNormalGammaPriors(lambda, mu, alpha, beta); M.readExpressionMatrix(data_file, null); M.readClusters(cluster_file); M.readRegulators(reg_file); M.initStatisticsAndScore(); M.setDataMeanAndSDFromModuleset(); // read regulation trees from xml file M.readRegTreeXML(tree_file); M.setTestSplits(); // set top regulators for each module M.setTopRegulatorClasses(top_regulators); // calculate mean and sigma for all modules M.setModuleMeanSigma(); M.checkExperiments(); // use module mean (default) or global mean for figures M.setGlobalMeanForFigures(use_global_mean); // use individual regulators mean for figures (default false) M.setRegulatorlMeanForFigures(use_regulator_mean); if (use_regulator_mean == true) M.setRegulatorMeanSigma(); // change gene names if a map file is given if (map_file != null) M.changeGeneNames(map_file); // cut trees to a certain level if (cut_level > 0) { for (Module mod : M.moduleSet) { for (TreeNode t : mod.hierarchicalTrees) { t.testLevel(cut_level); } } } DrawModules dm = new DrawModules(M); if (draw_experiment_color != null) { M.setExperimentColor(draw_experiment_color); dm.enableExperimentColor(); } if (draw_experiment_names == false) { dm.unsetDrawExperimentNames(); } dm.drawAllModules(); } //---------------------------------------------------------------------------- // topdown task: run "old" heuristic algo //---------------------------------------------------------------------------- else if (task.equalsIgnoreCase("topdown")) { int maxParents = 3; double epsConvergence = 1E-3; // Create ModuleNetwork object ModuleNetwork M = new ModuleNetwork(); M.setNormalGammaPriors(lambda, mu, alpha, beta); M.readExpressionMatrix(data_file, gene_file); M.setNormalGammaPriors(lambda, mu, alpha, beta); M.readRegulators(reg_file); // Top-down search M.heuristicSearchMaxTopDown(maxParents, epsConvergence); // write results as xml file M.writeRegTreeXML(output_file); } else { System.out.println("task option '" + task + "' unknown."); System.out.println(); } }
From source file:io.minimum.minecraft.rbclean.RedisBungeeClean.java
public static void main(String... args) { Options options = new Options(); Option hostOption = new Option("h", "host", true, "Sets the Redis host to use."); hostOption.setRequired(true);/*from w w w . j a va 2s.c o m*/ options.addOption(hostOption); Option portOption = new Option("p", "port", true, "Sets the Redis port to use."); options.addOption(portOption); Option passwordOption = new Option("w", "password", true, "Sets the Redis password to use."); options.addOption(passwordOption); Option dryRunOption = new Option("d", "dry-run", false, "Performs a dry run (no data is modified)."); options.addOption(dryRunOption); CommandLine commandLine; try { commandLine = new DefaultParser().parse(options, args); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("RedisBungeeClean", options); return; } int port = commandLine.hasOption('p') ? Integer.parseInt(commandLine.getOptionValue('p')) : 6379; try (Jedis jedis = new Jedis(commandLine.getOptionValue('h'), port, 0)) { if (commandLine.hasOption('w')) { jedis.auth(commandLine.getOptionValue('w')); } System.out.println("Fetching UUID cache..."); Map<String, String> uuidCache = jedis.hgetAll("uuid-cache"); Gson gson = new Gson(); // Just in case we need it, compress everything in JSON format. if (!commandLine.hasOption('d')) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); File file = new File("uuid-cache-previous-" + dateFormat.format(new Date()) + ".json.gz"); try { file.createNewFile(); } catch (IOException e) { System.out.println("Can't write backup of the UUID cache, will NOT proceed."); e.printStackTrace(); return; } System.out.println("Creating backup (as " + file.getName() + ")..."); try (OutputStreamWriter bw = new OutputStreamWriter( new GZIPOutputStream(new FileOutputStream(file)))) { gson.toJson(uuidCache, bw); } catch (IOException e) { System.out.println("Can't write backup of the UUID cache, will NOT proceed."); e.printStackTrace(); return; } } System.out.println("Cleaning out the bird cage (this may take a while...)"); int originalSize = uuidCache.size(); for (Iterator<Map.Entry<String, String>> it = uuidCache.entrySet().iterator(); it.hasNext();) { CachedUUIDEntry entry = gson.fromJson(it.next().getValue(), CachedUUIDEntry.class); if (entry.expired()) { it.remove(); } } int newSize = uuidCache.size(); if (commandLine.hasOption('d')) { System.out.println( (originalSize - newSize) + " records would be expunged if a dry run was not conducted."); } else { System.out.println("Expunging " + (originalSize - newSize) + " records..."); Transaction transaction = jedis.multi(); transaction.del("uuid-cache"); transaction.hmset("uuid-cache", uuidCache); transaction.exec(); System.out.println("Expunging complete."); } } }
From source file:net.cyllene.hackerrank.downloader.HackerrankDownloader.java
public static void main(String[] args) { // Parse arguments and set up the defaults DownloaderSettings.cmd = parseArguments(args); if (DownloaderSettings.cmd.hasOption("help")) { printHelp();//from www . j a va2s .com System.exit(0); } if (DownloaderSettings.cmd.hasOption("verbose")) { DownloaderSettings.beVerbose = true; } /** * Output directory logic: * 1) if directory exists, ask for -f option to overwrite, quit with message * 2) if -f flag is set, check if user has access to a parent directory * 3) if no access, quit with error * 4) if everything is OK, remember the path */ String sDesiredPath = DownloaderSettings.outputDir; if (DownloaderSettings.cmd.hasOption("directory")) { sDesiredPath = DownloaderSettings.cmd.getOptionValue("d", DownloaderSettings.outputDir); } if (DownloaderSettings.beVerbose) { System.out.println("Checking output dir: " + sDesiredPath); } Path desiredPath = Paths.get(sDesiredPath); if (Files.exists(desiredPath) && Files.isDirectory(desiredPath)) { if (!DownloaderSettings.cmd.hasOption("f")) { System.out.println("I wouldn't like to overwrite existing directory: " + sDesiredPath + ", set the --force flag if you are sure. May lead to data loss, be careful."); System.exit(0); } else { System.out.println( "WARNING!" + System.lineSeparator() + "--force flag is set. Overwriting directory: " + sDesiredPath + System.lineSeparator() + "WARNING!"); } } if ((Files.exists(desiredPath) && !Files.isWritable(desiredPath)) || !Files.isWritable(desiredPath.getParent())) { System.err .println("Fatal error: " + sDesiredPath + " cannot be created or modified. Check permissions."); // TODO: use Exceptions instead of system.exit System.exit(1); } DownloaderSettings.outputDir = sDesiredPath; Integer limit = DownloaderSettings.ITEMS_TO_DOWNLOAD; if (DownloaderSettings.cmd.hasOption("limit")) { try { limit = ((Number) DownloaderSettings.cmd.getParsedOptionValue("l")).intValue(); } catch (ParseException e) { System.out.println("Incorrect limit: " + e.getMessage() + System.lineSeparator() + "Using default value: " + limit); } } Integer offset = DownloaderSettings.ITEMS_TO_SKIP; if (DownloaderSettings.cmd.hasOption("offset")) { try { offset = ((Number) DownloaderSettings.cmd.getParsedOptionValue("o")).intValue(); } catch (ParseException e) { System.out.println("Incorrect offset: " + e.getMessage() + " Using default value: " + offset); } } DownloaderCore dc = DownloaderCore.INSTANCE; List<HRChallenge> challenges = new LinkedList<>(); // Download everything first Map<String, List<Integer>> structure = null; try { structure = dc.getStructure(offset, limit); } catch (IOException e) { System.err.println("Fatal Error: could not get data structure."); e.printStackTrace(); System.exit(1); } challengesLoop: for (Map.Entry<String, List<Integer>> entry : structure.entrySet()) { String challengeSlug = entry.getKey(); HRChallenge currentChallenge = null; try { currentChallenge = dc.getChallengeDetails(challengeSlug); } catch (IOException e) { System.err.println("Error: could not get challenge info for: " + challengeSlug); if (DownloaderSettings.beVerbose) { e.printStackTrace(); } continue challengesLoop; } submissionsLoop: for (Integer submissionId : entry.getValue()) { HRSubmission submission = null; try { submission = dc.getSubmissionDetails(submissionId); } catch (IOException e) { System.err.println("Error: could not get submission info for: " + submissionId); if (DownloaderSettings.beVerbose) { e.printStackTrace(); } continue submissionsLoop; } // TODO: probably should move filtering logic elsewhere(getStructure, maybe) if (submission.getStatus().equalsIgnoreCase("Accepted")) { currentChallenge.getSubmissions().add(submission); } } challenges.add(currentChallenge); } // Now dump all data to disk try { for (HRChallenge currentChallenge : challenges) { if (currentChallenge.getSubmissions().isEmpty()) continue; final String sChallengePath = DownloaderSettings.outputDir + "/" + currentChallenge.getSlug(); final String sSolutionPath = sChallengePath + "/accepted_solutions"; final String sDescriptionPath = sChallengePath + "/problem_description"; Files.createDirectories(Paths.get(sDescriptionPath)); Files.createDirectories(Paths.get(sSolutionPath)); // FIXME: this should be done the other way String plainBody = currentChallenge.getDescriptions().get(0).getBody(); String sFname; if (!plainBody.equals("null")) { sFname = sDescriptionPath + "/english.txt"; if (DownloaderSettings.beVerbose) { System.out.println("Writing to: " + sFname); } Files.write(Paths.get(sFname), plainBody.getBytes(StandardCharsets.UTF_8.name())); } String htmlBody = currentChallenge.getDescriptions().get(0).getBodyHTML(); String temporaryHtmlTemplate = "<html></body>" + htmlBody + "</body></html>"; sFname = sDescriptionPath + "/english.html"; if (DownloaderSettings.beVerbose) { System.out.println("Writing to: " + sFname); } Files.write(Paths.get(sFname), temporaryHtmlTemplate.getBytes(StandardCharsets.UTF_8.name())); for (HRSubmission submission : currentChallenge.getSubmissions()) { sFname = String.format("%s/%d.%s", sSolutionPath, submission.getId(), submission.getLanguage()); if (DownloaderSettings.beVerbose) { System.out.println("Writing to: " + sFname); } Files.write(Paths.get(sFname), submission.getSourceCode().getBytes(StandardCharsets.UTF_8.name())); } } } catch (IOException e) { System.err.println("Fatal Error: couldn't dump data to disk."); System.exit(1); } }
From source file:com.atilika.kuromoji.benchmark.Benchmark.java
public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption("h", "help", false, "Display this help message and exit"); options.addOption("t", "tokenizer", true, "Tokenizer class to use"); options.addOption("u", "user-dictionary", true, "Optional user dictionary filename to use"); options.addOption("c", "count", true, "Number of documents ot process (Default: 0, which means all"); // options.addOption("v", "validation-input", true, "Validation filename"); options.addOption("o", "output", true, "Output filename. If unset, segmentation is done, but the result is discarded"); options.addOption("n", "n-best", true, "The number of tokenizations to get per input"); options.addOption(null, "benchmark-output", true, "Benchmark metrics output filename filename"); CommandLineParser parser = new DefaultParser(); CommandLine commandLine = null;// www . j av a2s. c o m try { commandLine = parser.parse(options, args); args = commandLine.getArgs(); if (args.length != 1) { throw new ParseException("A single input filename is required"); } } catch (ParseException e) { System.err.println(e.getMessage()); usage(options); } String inputFilename = args[0]; String className = commandLine.getOptionValue("t", "com.atilika.kuromoji.ipadic.Tokenizer"); className += "$Builder"; String userDictionaryFilename = commandLine.getOptionValue("u"); TokenizerBase tokenizer = null; try { Class clazz = Class.forName(className); // Make builder Object builder = clazz.getDeclaredConstructor(null).newInstance(); // Set user dictionary if (userDictionaryFilename != null) { builder.getClass().getMethod("userDictionary", String.class).invoke(builder, userDictionaryFilename); } // Build tokenizer tokenizer = (TokenizerBase) builder.getClass().getMethod("build").invoke(builder); } catch (Exception e) { System.err.println("Could not create tokenizer. Got " + e); e.printStackTrace(); System.exit(1); } File outputFile = null; String outputFilename = commandLine.getOptionValue("o"); if (outputFilename != null) { outputFile = new File(outputFilename); } File statisticsFile = null; String statisticsFilename = commandLine.getOptionValue("benchmark-output"); if (statisticsFilename != null) { statisticsFile = new File(statisticsFilename); } long count = Long.parseLong(commandLine.getOptionValue("c", "0")); int nbest = Integer.parseInt(commandLine.getOptionValue("n", "1")); Benchmark benchmark = new Builder().tokenizer(tokenizer).inputFile(new File(inputFilename)) .outputFile(outputFile).outputStatisticsFile(statisticsFile).setOutputStatistiscs(true).count(count) .nbest(nbest).build(); benchmark.benchmark(); }
From source file:com.gsma.iariauth.validator.util.IARIValidatorMain.java
public static void main(String[] args) { String formatstr = "IARIValidator [-d <authorization document>] [-n <package name>] [-ps <package signer fingerprint>] [-pk <package signer keystore>] [-pa <package signer certificate alias>] [-pp <package signer keystore password>] -k <keystore> -p <password> [-v]"; HelpFormatter formatter = new HelpFormatter(); GnuParser parser = new GnuParser(); Options opts = new Options(); opts.addOption(new ArgOption("d", "document", "IARI Authorization document")); opts.addOption(new ArgOption("pkgname", "package-name", "package name")); opts.addOption(new ArgOption("pkgsigner", "package-signer", "package signer fingerprint")); opts.addOption(new ArgOption("pkgkeystore", "package-keystore", "package signing keystore")); opts.addOption(new ArgOption("pkgalias", "package-key-alias", "package signing certificate alias")); opts.addOption(new ArgOption("pkgstorepass", "package-keystore-pass", "package signing keystore password")); opts.addOption(new Option("v", "verbose", false, "verbose output")); CommandLine cli = null;//from w w w. ja v a 2s . c o m try { cli = parser.parse(opts, args); } catch (ParseException e) { formatter.printHelp(formatstr, opts); return; } boolean verbose = cli.hasOption("v"); String packageName = cli.getOptionValue("pkgname"); String packageSigner = cli.getOptionValue("pkgsigner"); if (packageSigner == null) { String packageSignerKeystore = cli.getOptionValue("pkgkeystore"); String packageSignerKeystoreAlias = cli.getOptionValue("pkgalias"); String packageSignerKeystorePasswd = cli.getOptionValue("pkgstorepass"); if (packageSignerKeystore != null) { if (packageSignerKeystoreAlias == null) { System.err.println("No alias given for package signing certificate"); System.exit(1); } if (packageSignerKeystorePasswd == null) { System.err.println("No password given for package signing keystore"); System.exit(1); } KeyStore packageKeystore = loadKeyStore(packageSignerKeystore, packageSignerKeystorePasswd); if (packageKeystore == null) { System.err.println("Unable to read package keystore"); System.exit(1); } try { X509Certificate c = (X509Certificate) packageKeystore .getCertificate(packageSignerKeystoreAlias); if (c == null) { System.err.println("Unable to access package signing certificate"); System.exit(1); } packageSigner = getFingerprint(c); } catch (KeyStoreException e) { System.err.println("Unable to access package signing certificate"); System.exit(1); } catch (CertificateEncodingException e) { e.printStackTrace(); System.err.println("Unable to read package signing certificate"); System.exit(1); } } } String authDocumentPath = cli.getOptionValue("d"); if (authDocumentPath == null) { System.err.println("No auth document specified"); System.exit(1); } File authDocument = new File(authDocumentPath); if (!authDocument.exists() || !authDocument.isFile()) { System.err.println("Unable to read specified auth document"); System.exit(1); } PackageProcessor processor = new PackageProcessor(packageName, packageSigner); ProcessingResult result = processor.processIARIauthorization(authDocument); if (result.getStatus() != ProcessingResult.STATUS_OK) { System.err.println("Error validating authDocument:"); System.err.println(result.getError().toString()); System.exit(1); } if (verbose) { System.out.println(result.getAuthDocument().toString()); } System.exit(0); }
From source file:com.netscape.cms.servlet.test.CATest.java
public static void main(String args[]) { String host = null;//from ww w. j a va 2 s. c o m String port = null; String token_pwd = null; String db_dir = "./"; String protocol = "http"; // parse command line arguments Options options = new Options(); options.addOption("h", true, "Hostname of the CA"); options.addOption("p", true, "Port of the CA"); options.addOption("s", true, "Attempt Optional Secure SSL connection"); options.addOption("w", true, "Token password"); options.addOption("d", true, "Directory for tokendb"); options.addOption("c", true, "Optional SSL Client cert Nickname"); try { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { host = cmd.getOptionValue("h"); } else { System.err.println("Error: no hostname provided."); usage(options); } if (cmd.hasOption("p")) { port = cmd.getOptionValue("p"); } else { System.err.println("Error: no port provided"); usage(options); } if (cmd.hasOption("w")) { token_pwd = cmd.getOptionValue("w"); } else { log("Notice: no token password provided"); } if (cmd.hasOption("d")) { db_dir = cmd.getOptionValue("d"); } if (cmd.hasOption("s")) { if (cmd.getOptionValue("s") != null && cmd.getOptionValue("s").equals("true")) { protocol = "https"; } } if (cmd.hasOption("c")) { String nick = cmd.getOptionValue("c"); if (nick != null && protocol.equals("https")) { clientCertNickname = nick; } } } catch (ParseException e) { System.err.println("Error in parsing command line options: " + e.getMessage()); usage(options); } CryptoManager manager = null; CryptoToken token = null; // Initialize token try { CryptoManager.initialize(db_dir); } catch (AlreadyInitializedException e) { // it is ok if it is already initialized } catch (Exception e) { log("INITIALIZATION ERROR: " + e.toString()); System.exit(1); } // log into token try { manager = CryptoManager.getInstance(); token = manager.getInternalKeyStorageToken(); Password password = new Password(token_pwd.toCharArray()); try { token.login(password); } catch (Exception e) { log("login Exception: " + e.toString()); if (!token.isLoggedIn()) { token.initPassword(password, password); } } } catch (Exception e) { log("Exception in logging into token:" + e.toString()); } CAClient client; CACertClient certClient; ProfileClient profileClient; try { ClientConfig config = new ClientConfig(); config.setServerURL(protocol + "://" + host + ":" + port); config.setCertNickname(clientCertNickname); client = new CAClient(new PKIClient(config, null)); certClient = (CACertClient) client.getClient("cert"); profileClient = (ProfileClient) client.getClient("profile"); } catch (Exception e) { e.printStackTrace(); return; } Collection<CertRequestInfo> list = null; try { list = certClient.listRequests("complete", null, null, null, null, null).getEntries(); } catch (Exception e) { e.printStackTrace(); } printRequests(list); //Get a CertInfo int certIdToPrint = 1; CertId id = new CertId(certIdToPrint); CertData certData = null; try { certData = certClient.getCert(id); } catch (CertNotFoundException e) { e.printStackTrace(); log("Cert: " + certIdToPrint + " not found. \n" + e.toString()); } printCertificate(certData); //Try an invalid Cert to print out //Get a CertInfo int certIdBadToPrint = 9999999; CertId certIdBad = new CertId(certIdBadToPrint); CertData certDataBad = null; try { certDataBad = certClient.getCert(certIdBad); } catch (CertNotFoundException e) { e.printStackTrace(); log("Cert: " + certIdBadToPrint + " not found. \n" + e.toString()); } printCertificate(certDataBad); //Get a CertInfoList CertDataInfos infos = null; try { infos = certClient.listCerts("VALID", null, null, null, null); } catch (Exception e) { e.printStackTrace(); } printCertInfos(infos, "no search filter:"); //Initiate a Certificate Enrollment CertEnrollmentRequest data = createUserCertEnrollment(); enrollAndApproveCertRequest(certClient, data); // submit a RA authenticated user cert request CertEnrollmentRequest rdata = createRAUserCertEnrollment(); enrollCertRequest(certClient, rdata); // now try a manually approved server cert CertEnrollmentRequest serverData = createServerCertEnrollment(); enrollAndApproveCertRequest(certClient, serverData); // submit using an agent approval profile serverData.setProfileId("caAgentServerCert"); enrollCertRequest(certClient, serverData); //Perform a sample certificate search with advanced search terms CertSearchRequest searchData = new CertSearchRequest(); searchData.setSerialNumberRangeInUse(true); searchData.setSerialFrom("9999"); searchData.setSerialTo("99990"); infos = certClient.findCerts(searchData, 100, 10); printCertInfos(infos, new FilterBuilder(searchData).buildFilter()); // Try to get a non existing request RequestId idBad = new RequestId("999999"); CertRequestInfo infoBad = null; try { infoBad = certClient.getRequest(idBad); } catch (RequestNotFoundException e) { e.printStackTrace(); log("Exception getting request #: " + idBad.toString() + "\n" + e.toString()); } printRequestInfo(infoBad); //Perform another sample certificate search with advanced search terms searchData = new CertSearchRequest(); searchData.setSubjectInUse(true); searchData.setEmail("jmagne@redhat.com"); searchData.setMatchExactly(true); infos = certClient.findCerts(searchData, 100, 10); printCertInfos(infos, new FilterBuilder(searchData).buildFilter()); //Get a list of Profiles ProfileDataInfos pInfos = profileClient.listProfiles(null, null); printProfileInfos(pInfos); // Get a specific profile String pId = "caUserCert"; ProfileData pData = profileClient.retrieveProfile(pId); printProfileData(pData); }
From source file:com.edduarte.argus.Main.java
public static void main(String[] args) { installUncaughtExceptionHandler();// w ww.java 2 s .c om CommandLineParser parser = new GnuParser(); Options options = new Options(); options.addOption("t", "threads", true, "Number of threads to be used " + "for computation and indexing processes. Defaults to the number " + "of available cores."); options.addOption("p", "port", true, "Core server port. Defaults to 9000."); options.addOption("dbh", "db-host", true, "Database host. Defaults to localhost."); options.addOption("dbp", "db-port", true, "Database port. Defaults to 27017."); options.addOption("case", "preserve-case", false, "Keyword matching with case sensitivity."); options.addOption("stop", "stopwords", false, "Keyword matching with stopword filtering."); options.addOption("stem", "stemming", false, "Keyword matching with stemming (lexical variants)."); options.addOption("h", "help", false, "Shows this help prompt."); CommandLine commandLine; try { // Parse the program arguments commandLine = parser.parse(options, args); } catch (ParseException ex) { logger.error("There was a problem processing the input arguments. " + "Write -h or --help to show the list of available commands."); logger.error(ex.getMessage(), ex); return; } if (commandLine.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar argus-core.jar", options); return; } int maxThreads = Runtime.getRuntime().availableProcessors() - 1; maxThreads = maxThreads > 0 ? maxThreads : 1; if (commandLine.hasOption('t')) { String threadsText = commandLine.getOptionValue('t'); maxThreads = Integer.parseInt(threadsText); if (maxThreads <= 0 || maxThreads > 32) { logger.error("Invalid number of threads. Must be a number between 1 and 32."); return; } } int port = 9000; if (commandLine.hasOption('p')) { String portString = commandLine.getOptionValue('p'); port = Integer.parseInt(portString); } String dbHost = "localhost"; if (commandLine.hasOption("dbh")) { dbHost = commandLine.getOptionValue("dbh"); } int dbPort = 27017; if (commandLine.hasOption("dbp")) { String portString = commandLine.getOptionValue("dbp"); dbPort = Integer.parseInt(portString); } boolean isIgnoringCase = true; if (commandLine.hasOption("case")) { isIgnoringCase = false; } boolean isStoppingEnabled = false; if (commandLine.hasOption("stop")) { isStoppingEnabled = true; } boolean isStemmingEnabled = false; if (commandLine.hasOption("stem")) { isStemmingEnabled = true; } try { Context context = Context.getInstance(); context.setIgnoreCase(isIgnoringCase); context.setStopwordsEnabled(isStoppingEnabled); context.setStemmingEnabled(isStemmingEnabled); context.start(port, maxThreads, dbHost, dbPort); } catch (Exception ex) { ex.printStackTrace(); logger.info("Shutting down the server..."); System.exit(1); } }
From source file:com.edduarte.vokter.Main.java
public static void main(String[] args) { installUncaughtExceptionHandler();/*from w ww.j ava2s .co m*/ CommandLineParser parser = new GnuParser(); Options options = new Options(); options.addOption("t", "threads", true, "Number of threads to be used " + "for computation and indexing processes. Defaults to the number " + "of available cores."); options.addOption("p", "port", true, "Core server port. Defaults to 9000."); options.addOption("dbh", "db-host", true, "Database host. Defaults to localhost."); options.addOption("dbp", "db-port", true, "Database port. Defaults to 27017."); options.addOption("case", "preserve-case", false, "Keyword matching with case sensitivity."); options.addOption("stop", "stopwords", false, "Keyword matching with stopword filtering."); options.addOption("stem", "stemming", false, "Keyword matching with stemming (lexical variants)."); options.addOption("h", "help", false, "Shows this help prompt."); CommandLine commandLine; try { // Parse the program arguments commandLine = parser.parse(options, args); } catch (ParseException ex) { logger.error("There was a problem processing the input arguments. " + "Write -h or --help to show the list of available commands."); logger.error(ex.getMessage(), ex); return; } if (commandLine.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar vokter-core.jar", options); return; } int maxThreads = Runtime.getRuntime().availableProcessors() - 1; maxThreads = maxThreads > 0 ? maxThreads : 1; if (commandLine.hasOption('t')) { String threadsText = commandLine.getOptionValue('t'); maxThreads = Integer.parseInt(threadsText); if (maxThreads <= 0 || maxThreads > 32) { logger.error("Invalid number of threads. Must be a number between 1 and 32."); return; } } int port = 9000; if (commandLine.hasOption('p')) { String portString = commandLine.getOptionValue('p'); port = Integer.parseInt(portString); } String dbHost = "localhost"; if (commandLine.hasOption("dbh")) { dbHost = commandLine.getOptionValue("dbh"); } int dbPort = 27017; if (commandLine.hasOption("dbp")) { String portString = commandLine.getOptionValue("dbp"); dbPort = Integer.parseInt(portString); } boolean isIgnoringCase = true; if (commandLine.hasOption("case")) { isIgnoringCase = false; } boolean isStoppingEnabled = false; if (commandLine.hasOption("stop")) { isStoppingEnabled = true; } boolean isStemmingEnabled = false; if (commandLine.hasOption("stem")) { isStemmingEnabled = true; } try { Context context = Context.getInstance(); context.setIgnoreCase(isIgnoringCase); context.setStopwordsEnabled(isStoppingEnabled); context.setStemmingEnabled(isStemmingEnabled); context.start(port, maxThreads, dbHost, dbPort); } catch (Exception ex) { ex.printStackTrace(); logger.info("Shutting down the server..."); System.exit(1); } }
From source file:de.zazaz.iot.bosch.indego.util.CmdLineTool.java
public static void main(String[] args) { Options options = new Options(); StringBuilder commandList = new StringBuilder(); for (DeviceCommand cmd : DeviceCommand.values()) { if (commandList.length() > 0) { commandList.append(", "); }// www . j a va 2 s.c o m commandList.append(cmd.toString()); } options.addOption(Option // .builder() // .longOpt("base-url") // .desc("Sets the base URL of the web service") // .hasArg() // .build()); options.addOption(Option // .builder("u") // .longOpt("username") // .desc("The username for authentication (usually mail address)") // .required() // .hasArg() // .build()); options.addOption(Option // .builder("p") // .longOpt("password") // .desc("The password for authentication") // .required() // .hasArg() // .build()); options.addOption(Option // .builder("c") // .longOpt("command") // .desc(String.format("The command, which should be sent to the device (%s)", commandList)) // .hasArg() // .build()); options.addOption(Option // .builder("q") // .longOpt("query-status") // .desc("Queries the status of the device") // .build()); options.addOption(Option // .builder() // .longOpt("query-calendar") // .desc("Queries the calendar of the device") // .build()); options.addOption(Option // .builder("?") // .longOpt("help") // .desc("Prints this help") // .build()); CommandLineParser parser = new DefaultParser(); CommandLine cmds = null; try { cmds = parser.parse(options, args); } catch (ParseException ex) { System.err.println(ex.getMessage()); System.err.println(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(CmdLineTool.class.getName(), options); System.exit(1); return; } if (cmds.hasOption("?")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(CmdLineTool.class.getName(), options); return; } String baseUrl = cmds.getOptionValue("base-url"); String username = cmds.getOptionValue('u'); String password = cmds.getOptionValue('p'); String commandStr = cmds.getOptionValue('c'); boolean doQueryState = cmds.hasOption('q'); boolean doQueryCalendar = cmds.hasOption("query-calendar"); DeviceCommand command = null; if (commandStr != null) { try { command = DeviceCommand.valueOf(commandStr.toUpperCase()); } catch (IllegalArgumentException ex) { System.err.println("Unknown command: " + commandStr); System.exit(1); } } IndegoController controller = new IndegoController(baseUrl, username, password); try { System.out.println("Connecting to device"); controller.connect(); System.out.println(String.format("...Connection established. Device serial number is: %s", controller.getDeviceSerialNumber())); if (command != null) { System.out.println(String.format("Sending command (%s)...", command)); controller.sendCommand(command); System.out.println("...Command sent successfully!"); } if (doQueryState) { System.out.println("Querying device state"); DeviceStateInformation state = controller.getState(); printState(System.out, state); } if (doQueryCalendar) { System.out.println("Querying device calendar"); DeviceCalendar calendar = controller.getCalendar(); printCalendar(System.out, calendar); } } catch (IndegoException ex) { ex.printStackTrace(); System.exit(2); } finally { controller.disconnect(); } }