List of usage examples for org.apache.commons.cli Option Option
public Option(String opt, String longOpt, boolean hasArg, String description) throws IllegalArgumentException
From source file:net.cliftonsnyder.svgchart.Main.java
public static void main(String[] args) { Options options = new Options(); options.addOption("c", "stylesheet", true, "CSS stylesheet (default: " + SVGChart.DEFAULT_STYLESHEET + ")"); options.addOption("h", "height", true, "chart height"); options.addOption("i", "input-file", true, "input file [default: stdin]"); options.addOption("o", "output-file", true, "output file [default: stdout]"); options.addOption("w", "width", true, "chart width"); options.addOption("?", "help", false, "print a brief help message"); Option type = new Option("t", "type", true, "chart type " + Arrays.toString(SVGChart.TYPES)); type.setRequired(true);//from w ww. j a v a 2 s . c o m options.addOption(type); CommandLineParser parser = new GnuParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); if (line.hasOption("help")) { formatter.printHelp(USAGE, options); System.exit(0); } } catch (ParseException exp) { // oops, something went wrong System.err.println("unable to parse command line: " + exp.getMessage()); formatter.printHelp(USAGE, options); System.exit(1); } SVGChart chart = null; String tmp = line.getOptionValue("type"); Matcher m = null; for (Pattern p : SVGChart.TYPE_PATTERNS) { if ((m = p.matcher(tmp)).matches()) { switch (m.group().charAt(0)) { case 'l': // DEBUG System.err.println("line"); break; case 'b': System.err.println("bar"); chart = new BarChart(); break; case 'p': System.err.println("pie"); break; default: System.err.println("unknown or unimplemented chart type: '" + tmp + "'"); System.exit(1); } } } try { chart.setWidth(Double.parseDouble(line.getOptionValue("width", "" + SVGChart.DEFAULT_WIDTH))); } catch (NumberFormatException e) { System.err.println( "unable to parse command line: invalid width value '" + line.getOptionValue("width") + "'"); System.exit(1); } try { chart.setHeight(Double.parseDouble(line.getOptionValue("height", "" + SVGChart.DEFAULT_HEIGHT))); } catch (NumberFormatException e) { System.err.println( "unable to parse command line: invalid height value '" + line.getOptionValue("height") + "'"); System.exit(1); } InputStream in = System.in; tmp = line.getOptionValue("input-file", "-"); if ("-".equals(tmp)) { in = System.in; } else { try { in = new FileInputStream(tmp); } catch (FileNotFoundException e) { System.err.println("input file not found: '" + tmp + "'"); System.exit(1); } } PrintStream out = System.out; tmp = line.getOptionValue("output-file", "-"); if ("-".equals(tmp)) { out = System.out; } else { try { out = new PrintStream(new FileOutputStream(tmp)); } catch (FileNotFoundException e) { System.err.println("output file not found: '" + tmp + "'"); System.exit(1); } } tmp = line.getOptionValue("stylesheet", SVGChart.DEFAULT_STYLESHEET); chart.setStyleSheet(tmp); try { chart.parseInput(in); } catch (IOException e) { System.err.println("I/O error while reading input"); System.exit(1); } catch (net.cliftonsnyder.svgchart.parse.ParseException e) { System.err.println("error parsing input: " + e.getMessage()); } chart.createChart(); try { chart.printChart(out, true); } catch (IOException e) { System.err.println("error serializing output"); System.exit(1); } }
From source file:fr.tpt.s3.mcdag.bench.MainBench.java
public static void main(String[] args) throws IOException, InterruptedException { // Command line options Options options = new Options(); Option input = new Option("i", "input", true, "MC-DAG XML models"); input.setRequired(true);// w ww .java2 s . c o m input.setArgs(Option.UNLIMITED_VALUES); options.addOption(input); Option output = new Option("o", "output", true, "Folder where results have to be written."); output.setRequired(true); options.addOption(output); Option uUti = new Option("u", "utilization", true, "Utilization."); uUti.setRequired(true); options.addOption(uUti); Option output2 = new Option("ot", "output-total", true, "File where total results are being written"); output2.setRequired(true); options.addOption(output2); Option oCores = new Option("c", "cores", true, "Cores given to the test"); oCores.setRequired(true); options.addOption(oCores); Option oLvls = new Option("l", "levels", true, "Levels tested for the system"); oLvls.setRequired(true); options.addOption(oLvls); Option jobs = new Option("j", "jobs", true, "Number of threads to be launched."); jobs.setRequired(false); options.addOption(jobs); Option debug = new Option("d", "debug", false, "Debug logs."); debug.setRequired(false); options.addOption(debug); /* * Parsing of the command line */ CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println(e.getMessage()); formatter.printHelp("Benchmarks MultiDAG", options); System.exit(1); return; } String inputFilePath[] = cmd.getOptionValues("input"); String outputFilePath = cmd.getOptionValue("output"); String outputFilePathTotal = cmd.getOptionValue("output-total"); double utilization = Double.parseDouble(cmd.getOptionValue("utilization")); boolean boolDebug = cmd.hasOption("debug"); int nbLvls = Integer.parseInt(cmd.getOptionValue("levels")); int nbJobs = 1; int nbFiles = inputFilePath.length; if (cmd.hasOption("jobs")) nbJobs = Integer.parseInt(cmd.getOptionValue("jobs")); int nbCores = Integer.parseInt(cmd.getOptionValue("cores")); /* * While files need to be allocated * run the tests in the pool of threads */ // For dual-criticality systems we call a specific thread if (nbLvls == 2) { System.out.println(">>>>>>>>>>>>>>>>>>>>> NB levels " + nbLvls); int i_files2 = 0; String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.')) .concat("-schedulability.csv"); PrintWriter writer = new PrintWriter(outFile, "UTF-8"); writer.println( "Thread; File; FSched (%); FPreempts; FAct; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization"); writer.close(); ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs); while (i_files2 != nbFiles) { BenchThreadDualCriticality bt2 = new BenchThreadDualCriticality(inputFilePath[i_files2], outFile, nbCores, boolDebug); executor2.execute(bt2); i_files2++; } executor2.shutdown(); executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); int fedTotal = 0; int laxTotal = 0; int edfTotal = 0; int hybridTotal = 0; int fedPreempts = 0; int laxPreempts = 0; int edfPreempts = 0; int hybridPreempts = 0; int fedActiv = 0; int laxActiv = 0; int edfActiv = 0; int hybridActiv = 0; // Read lines in file and do average int i = 0; File f = new File(outFile); @SuppressWarnings("resource") Scanner line = new Scanner(f); while (line.hasNextLine()) { String s = line.nextLine(); if (i > 0) { // To skip the first line try (Scanner inLine = new Scanner(s).useDelimiter("; ")) { int j = 0; while (inLine.hasNext()) { String val = inLine.next(); if (j == 2) { fedTotal += Integer.parseInt(val); } else if (j == 3) { fedPreempts += Integer.parseInt(val); } else if (j == 4) { fedActiv += Integer.parseInt(val); } else if (j == 5) { laxTotal += Integer.parseInt(val); } else if (j == 6) { laxPreempts += Integer.parseInt(val); } else if (j == 7) { laxActiv += Integer.parseInt(val); } else if (j == 8) { edfTotal += Integer.parseInt(val); } else if (j == 9) { edfPreempts += Integer.parseInt(val); } else if (j == 10) { edfActiv += Integer.parseInt(val); } else if (j == 11) { hybridTotal += Integer.parseInt(val); } else if (j == 12) { hybridPreempts += Integer.parseInt(val); } else if (j == 13) { hybridActiv += Integer.parseInt(val); } j++; } } } i++; } // Write percentage double fedPerc = (double) fedTotal / nbFiles; double laxPerc = (double) laxTotal / nbFiles; double edfPerc = (double) edfTotal / nbFiles; double hybridPerc = (double) hybridTotal / nbFiles; double fedPercPreempts = (double) fedPreempts / fedActiv; double laxPercPreempts = (double) laxPreempts / laxActiv; double edfPercPreempts = (double) edfPreempts / edfActiv; double hybridPercPreempts = (double) hybridPreempts / hybridActiv; Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true)); wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + fedPerc + "; " + fedPreempts + "; " + fedActiv + "; " + fedPercPreempts + "; " + laxPerc + "; " + laxPreempts + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts + "; " + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; " + hybridActiv + "; " + hybridPercPreempts + "\n"); wOutput.close(); } else if (nbLvls > 2) { int i_files2 = 0; String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.')) .concat("-schedulability.csv"); PrintWriter writer = new PrintWriter(outFile, "UTF-8"); writer.println( "Thread; File; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization"); writer.close(); ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs); while (i_files2 != nbFiles) { BenchThreadNLevels bt2 = new BenchThreadNLevels(inputFilePath[i_files2], outFile, nbCores, boolDebug); executor2.execute(bt2); i_files2++; } executor2.shutdown(); executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); int laxTotal = 0; int edfTotal = 0; int hybridTotal = 0; int laxPreempts = 0; int edfPreempts = 0; int hybridPreempts = 0; int laxActiv = 0; int edfActiv = 0; int hybridActiv = 0; // Read lines in file and do average int i = 0; File f = new File(outFile); @SuppressWarnings("resource") Scanner line = new Scanner(f); while (line.hasNextLine()) { String s = line.nextLine(); if (i > 0) { // To skip the first line try (Scanner inLine = new Scanner(s).useDelimiter("; ")) { int j = 0; while (inLine.hasNext()) { String val = inLine.next(); if (j == 2) { laxTotal += Integer.parseInt(val); } else if (j == 3) { laxPreempts += Integer.parseInt(val); } else if (j == 4) { laxActiv += Integer.parseInt(val); } else if (j == 5) { edfTotal += Integer.parseInt(val); } else if (j == 6) { edfPreempts += Integer.parseInt(val); } else if (j == 7) { edfActiv += Integer.parseInt(val); } else if (j == 8) { hybridTotal += Integer.parseInt(val); } else if (j == 9) { hybridPreempts += Integer.parseInt(val); } else if (j == 10) { hybridActiv += Integer.parseInt(val); } j++; } } } i++; } // Write percentage double laxPerc = (double) laxTotal / nbFiles; double edfPerc = (double) edfTotal / nbFiles; double hybridPerc = (double) hybridTotal / nbFiles; double laxPercPreempts = (double) laxPreempts / laxActiv; double edfPercPreempts = (double) edfPreempts / edfActiv; double hybridPercPreempts = (double) hybridPreempts / hybridActiv; Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true)); wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + laxPerc + "; " + laxPreempts + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts + "; " + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; " + hybridActiv + "; " + hybridPercPreempts + "\n"); wOutput.close(); } else { System.err.println("Wrong number of levels"); System.exit(-1); } System.out.println("[BENCH Main] Done benchmarking U = " + utilization + " Levels " + nbLvls); }
From source file:com.osrdata.etltoolbox.fileloader.Main.java
/** * Main entry point into the application. * @param args command line argunemtns/* w w w.j a v a 2s. c om*/ */ public static void main(String[] args) { Options options = new Options(); options.addOption(new Option("s", "spec", true, "Source-to-target specification file")); options.addOption(new Option("d", "directory", true, "Source directory to load")); options.addOption(new Option("f", "file", true, "File to perform operation on")); options.addOption(new Option("r", "replace", false, "Replace previously loaded data")); options.addOption(new Option("t", "trace", true, "Trace records processed at specified interval")); CommandLineParser parser = new BasicParser(); try { CommandLine line = parser.parse(options, args); if (line.hasOption("spec") && (line.hasOption("directory") || line.hasOption("file"))) { FileLoader loader = new FileLoader(line); loader.init(); if (line.hasOption("file")) { loader.load(new File(line.getOptionValue("file"))); } else if (line.hasOption("directory")) { File directory = new File(line.getOptionValue("directory")); if (directory.isDirectory()) { File[] files = directory.listFiles(); for (File file : files) { loader.load(file); } } else { log.fatal(directory.getAbsolutePath() + " does not appear to be a directory."); } } } else { usage(); } } catch (ParseException e) { usage(); } catch (IOException e) { e.printStackTrace(); } }
From source file:net.sf.jsignpdf.verify.SignatureCounter.java
/** * Main program.// w w w . jav a 2s . c om * * @param args */ public static void main(String[] args) { // create the Options final Option optHelp = new Option("h", "help", false, "print this message"); final Option optDebug = new Option("d", "debug", false, "enables debug output"); final Option optNames = new Option("n", "names", false, "print comma separated signature names instead of the count"); final Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); final Options options = new Options(); options.addOption(optHelp); options.addOption(optDebug); options.addOption(optNames); options.addOption(optPasswd); CommandLine line = null; try { // create the command line parser CommandLineParser parser = new PosixParser(); // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Unable to parse command line (Use -h for the help)\n" + exp.getMessage()); System.exit(Constants.EXIT_CODE_PARSE_ERR); } final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar SignatureCounter.jar [file1.pdf [file2.pdf ...]]", "JSignPdf SignatureCounter is a command line tool which prints count of signatures in given PDF document.", options, null, true); } else { byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } final boolean debug = line.hasOption("d"); final boolean names = line.hasOption("n"); for (String tmpFilePath : tmpArgs) { if (debug) { System.out.print("Counting signatures in " + tmpFilePath + ": "); } final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { System.err.println("Couldn't read the file. Check the path and permissions: " + tmpFilePath); System.exit(Constants.EXIT_CODE_CANT_READ_FILE); } try { final PdfReader pdfReader = PdfUtils.getPdfReader(tmpFilePath, tmpPasswd); @SuppressWarnings("unchecked") final List<String> sigNames = pdfReader.getAcroFields().getSignatureNames(); if (names) { //print comma-separated names boolean isNotFirst = false; for (String sig : sigNames) { if (isNotFirst) { System.out.println(","); } else { isNotFirst = true; } System.out.println(sig); } } else { //normal processing print only count of signatures System.out.println(sigNames.size()); if (debug) { System.out.println("Signature names: " + sigNames); } } } catch (IOException e) { e.printStackTrace(); System.exit(Constants.EXIT_CODE_COMMON_ERROR); } } } }
From source file:co.cask.cdap.data.tools.CoprocessorBuildTool.java
public static void main(final String[] args) throws ParseException { Options options = new Options().addOption(new Option("h", "help", false, "Print this usage message.")) .addOption(new Option("f", "force", false, "Overwrites any coprocessors that already exist.")); CommandLineParser parser = new BasicParser(); CommandLine commandLine = parser.parse(options, args); String[] commandArgs = commandLine.getArgs(); // if help is an option, or if there isn't a single 'ensure' command, print usage and exit. if (commandLine.hasOption("h") || commandArgs.length != 1 || !"check".equalsIgnoreCase(commandArgs[0])) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp(CoprocessorBuildTool.class.getName() + " check", "Checks that HBase coprocessors required by CDAP are loaded onto HDFS. " + "If not, the coprocessors are built and placed on HDFS.", options, ""); System.exit(0);//from w w w . j ava 2 s . c om } boolean overwrite = commandLine.hasOption("f"); CConfiguration cConf = CConfiguration.create(); Configuration hConf = HBaseConfiguration.create(); Injector injector = Guice.createInjector(new ConfigModule(cConf, hConf), // for LocationFactory new PrivateModule() { @Override protected void configure() { bind(FileContext.class).toProvider(FileContextProvider.class).in(Scopes.SINGLETON); expose(LocationFactory.class); } @Provides @Singleton private LocationFactory providesLocationFactory(Configuration hConf, CConfiguration cConf, FileContext fc) { final String namespace = cConf.get(Constants.CFG_HDFS_NAMESPACE); return new FileContextLocationFactory(hConf, fc, namespace); } }); try { SecurityUtil.loginForMasterService(cConf); } catch (Exception e) { LOG.error("Failed to login as CDAP user", e); System.exit(1); } LocationFactory locationFactory = injector.getInstance(LocationFactory.class); HBaseTableUtil tableUtil = new HBaseTableUtilFactory(cConf).get(); CoprocessorManager coprocessorManager = new CoprocessorManager(cConf, locationFactory, tableUtil); try { Location location = coprocessorManager.ensureCoprocessorExists(overwrite); LOG.info("coprocessor exists at {}.", location); } catch (IOException e) { LOG.error("Unable to build and upload coprocessor jars.", e); System.exit(1); } }
From source file:info.devopsabyss.CallSeleniumTest.java
public static void main(String[] args) throws Exception { // TODO: Selenium Server host and port as parameters CallSeleniumTest seTest = new CallSeleniumTest(); Option optionclass = new Option("c", "class", true, "full classname of testcase (required) e.g. \"com.example.tests.GoogleSeleniumTestCase\""); //optiontype.setRequired(true); Option optionverbose = new Option("v", "verbose", false, "show a lot of information (useful in case of problems)"); Option optionhelp = new Option("h", "help", false, "show this help screen"); Option optionNagios3 = new Option("3", "nagios3", false, "in case of a test failure, print a multiline message in nagios 3 format"); seTest.options = new Options(); seTest.options.addOption(optionclass); seTest.options.addOption(optionverbose); seTest.options.addOption(optionhelp); seTest.options.addOption(optionNagios3); CommandLineParser parser = new BasicParser(); CommandLine cmd = null;//from w ww .j a v a2s.com // TODO: verify baseURL // TODO: is there a possibility to verify classname? String output = seTest.NAGIOS_TEXT_UNKNOWN + " - Upps |"; int nagios_rc = seTest.NAGIOS_RC_UNKNOWN; try { cmd = parser.parse(seTest.options, args); // has to be checked manually, otherwise you can't access the help message without specifying correct parameters if (cmd.hasOption("h") || cmd.getOptionValue("c") == null) { usage(seTest.options); System.exit(nagios_rc); } Result result = seTest.runJUnitTest(cmd.getOptionValue("c")); if (result.wasSuccessful()) { output = seTest.NAGIOS_TEXT_OK + " - " + cmd.getOptionValue("c") + " Tests passed | ExecTime=" + result.getRunTime() + "ms"; nagios_rc = seTest.NAGIOS_RC_OK; } else { String failureMessage = result.getFailures().toString(); output = seTest.NAGIOS_TEXT_CRITICAL + " - " + cmd.getOptionValue("c"); if (cmd.hasOption("3")) { output += " Test Failures | ExecTime=" + result.getRunTime() + "ms\n" + failureMessage; } else { output += " Test Failures: " + withoutNewlines(failureMessage) + " | ExecTime=" + result.getRunTime() + "ms"; } nagios_rc = seTest.NAGIOS_RC_CRITICAL; } } catch (UnrecognizedOptionException ex) { output = seTest.NAGIOS_TEXT_UNKNOWN + " - " + "Parameter problems: " + messageWithoutNewlines(ex) + " |"; nagios_rc = seTest.NAGIOS_RC_UNKNOWN; usage(seTest.options); } catch (ParseException ex) { output = seTest.NAGIOS_TEXT_UNKNOWN + " - " + "Parameter problems: " + messageWithoutNewlines(ex) + " |"; nagios_rc = seTest.NAGIOS_RC_UNKNOWN; usage(seTest.options); } catch (NoClassDefFoundError ex) { printStackTraceWhenVerbose(cmd, ex); output = seTest.NAGIOS_TEXT_UNKNOWN + " - " + cmd.getOptionValue("c") + ": " + messageWithoutNewlines(ex) + " |"; nagios_rc = seTest.NAGIOS_RC_UNKNOWN; } catch (ClassNotFoundException ex) { output = seTest.NAGIOS_TEXT_UNKNOWN + " - " + cmd.getOptionValue("c") + ": Testcase class " + messageWithoutNewlines(ex) + " not found! |"; nagios_rc = seTest.NAGIOS_RC_UNKNOWN; } catch (Exception ex) { printStackTraceWhenVerbose(cmd, ex); output = seTest.NAGIOS_TEXT_CRITICAL + " - " + cmd.getOptionValue("c") + ": " + messageWithoutNewlines(ex) + " |"; nagios_rc = seTest.NAGIOS_RC_CRITICAL; } finally { System.out.println(output); System.exit(nagios_rc); } }
From source file:de.binfalse.jatter.App.java
/** * Run jatter's main.// w ww . ja v a 2s .c o m * * @param args * the arguments * @throws Exception * the exception */ public static void main(String[] args) throws Exception { Options options = new Options(); Option conf = new Option("c", "config", true, "config file path"); conf.setRequired(false); options.addOption(conf); Option t = new Option("t", "template", false, "show a config template"); t.setRequired(false); options.addOption(t); Option v = new Option("v", "verbose", false, "print information messages"); v.setRequired(false); options.addOption(v); Option d = new Option("d", "debug", false, "print debugging messages incl stack traces"); d.setRequired(false); options.addOption(d); Option h = new Option("h", "help", false, "show help"); h.setRequired(false); options.addOption(h); CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) throw new RuntimeException("showing the help page"); } catch (Exception e) { help(options, e.getMessage()); return; } if (cmd.hasOption("t")) { System.out.println(); BufferedReader br = new BufferedReader(new InputStreamReader( App.class.getClassLoader().getResourceAsStream("config.properties.template"))); while (br.ready()) System.out.println(br.readLine()); br.close(); System.exit(0); } if (cmd.hasOption("v")) LOGGER.setMinLevel(LOGGER.INFO); if (cmd.hasOption("d")) { LOGGER.setMinLevel(LOGGER.DEBUG); LOGGER.setLogStackTrace(true); } if (!cmd.hasOption("c")) help(options, "a config file is required for running jatter"); startJatter(cmd.getOptionValue("c")); }
From source file:microbiosima.Microbiosima.java
/** * @param args/* ww w.java 2s.c o m*/ * the command line arguments * @throws java.io.FileNotFoundException * @throws java.io.UnsupportedEncodingException */ public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { //Init with default values int populationSize = 500; int microSize = 1000; int numberOfSpecies = 150; int numberOfGeneration = 10000; int numberOfObservation = 100; int numberOfReplication = 1; double pctEnv = 0; double pctPool = 0; Options options = new Options(); Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print the version information and exit"); options.addOption(help); options.addOption(version); options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS") .desc("Number generation for observation [default: 100]").build()); options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP") .desc("Number of replication [default: 1]").build()); Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen") .desc("Four Parameters in the following orders: " + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation" + " [default: 500 1000 150 10000]"); options.addOption(C.build()); HelpFormatter formatter = new HelpFormatter(); String syntax = "microbiosima pctEnv pctPool"; String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n" + "required arguments:\n" + " pctEnv Percentage of environmental acquisition\n" + " pctPool Percentage of pooled environmental component\n" + "\noptional arguments:\n"; String footer = "\n"; formatter.setWidth(80); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); String[] pct_config = cmd.getArgs(); if (cmd.hasOption("h") || args.length == 0) { formatter.printHelp(syntax, header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { System.out.println("Microbiosima " + VERSION); System.exit(0); } if (pct_config.length != 2) { System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got " + pct_config.length + ": " + Arrays.toString(pct_config)); formatter.printHelp(syntax, header, options, footer, true); System.exit(3); } else { pctEnv = Double.parseDouble(pct_config[0]); pctPool = Double.parseDouble(pct_config[1]); if (pctEnv < 0 || pctEnv > 1) { System.out.println( "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv=" + pctEnv + ")! EXIT"); System.exit(3); } if (pctPool < 0 || pctPool > 1) { System.out.println( "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool=" + pctPool + ")! EXIT"); System.exit(3); } } if (cmd.hasOption("config")) { String[] configs = cmd.getOptionValues("config"); populationSize = Integer.parseInt(configs[0]); microSize = Integer.parseInt(configs[1]); numberOfSpecies = Integer.parseInt(configs[2]); numberOfGeneration = Integer.parseInt(configs[3]); } if (cmd.hasOption("obs")) { numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs")); } if (cmd.hasOption("rep")) { numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep")); } } catch (ParseException e) { e.printStackTrace(); System.exit(3); } StringBuilder sb = new StringBuilder(); sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize) .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ") .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration) .append("\n\tNumber generation for observation: ").append(numberOfObservation) .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n"); System.out.println(sb.toString()); // System.exit(3); // LogNormalDistribution lgd=new LogNormalDistribution(0,1); // environment=lgd.sample(150); // double environment_sum=0; // for (int i=0;i<No;i++){ // environment_sum+=environment[i]; // } // for (int i=0;i<No;i++){ // environment[i]/=environment_sum; // } double[] environment = new double[numberOfSpecies]; for (int i = 0; i < numberOfSpecies; i++) { environment[i] = 1 / (double) numberOfSpecies; } for (int rep = 0; rep < numberOfReplication; rep++) { String prefix = "" + (rep + 1) + "_"; String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt"; System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix); try { PrintWriter file1 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix))); PrintWriter file2 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix))); PrintWriter file3 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix))); PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix))); PrintWriter file5 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix))); PrintWriter file6 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix))); Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0, 0); while (population.getNumberOfGeneration() < numberOfGeneration) { population.sumSpecies(); if (population.getNumberOfGeneration() % numberOfObservation == 0) { file1.println(population.gammaDiversity(true)); file2.println(population.alphaDiversity(true)); file3.print(population.betaDiversity(true)); file3.print("\t"); file3.println(population.BrayCurtis(true)); file4.println(population.printOut()); file5.println(population.interGenerationDistance()); file6.println(population.environmentPopulationDistance()); } population.getNextGen(); } file1.close(); file2.close(); file3.close(); file4.close(); file5.close(); file6.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:dk.netarkivet.harvester.tools.CreateIndex.java
/** * The main method that does the parsing of the commandline, and makes the actual index request. * * @param args the arguments// ww w . ja v a 2 s .co m */ public static void main(String[] args) { Options options = new Options(); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; Option indexType = new Option("t", "type", true, "Type of index"); Option jobList = new Option("l", "jobids", true, "list of jobids"); indexType.setRequired(true); jobList.setRequired(true); options.addOption(indexType); options.addOption(jobList); try { // parse the command line arguments cmd = parser.parse(options, args); } catch (MissingOptionException e) { System.err.println("Some of the required parameters are missing: " + e.getMessage()); dieWithUsage(); } catch (ParseException exp) { System.err.println("Parsing of parameters failed: " + exp.getMessage()); dieWithUsage(); } String typeValue = cmd.getOptionValue(INDEXTYPE_OPTION); String jobidsValue = cmd.getOptionValue(JOBIDS_OPTION); String[] jobidsAsStrings = jobidsValue.split(","); Set<Long> jobIDs = new HashSet<Long>(); for (String idAsString : jobidsAsStrings) { jobIDs.add(Long.valueOf(idAsString)); } JobIndexCache cache = null; String indexTypeAstring = ""; if (typeValue.equalsIgnoreCase("CDX")) { indexTypeAstring = "CDX"; cache = IndexClientFactory.getCDXInstance(); } else if (typeValue.equalsIgnoreCase("DEDUP")) { indexTypeAstring = "DEDUP"; cache = IndexClientFactory.getDedupCrawllogInstance(); } else if (typeValue.equalsIgnoreCase("CRAWLLOG")) { indexTypeAstring = "CRAWLLOG"; cache = IndexClientFactory.getFullCrawllogInstance(); } else { System.err.println("Unknown indextype '" + typeValue + "' requested."); dieWithUsage(); } System.out.println("Creating " + indexTypeAstring + " index for ids: " + jobIDs); Index<Set<Long>> index = cache.getIndex(jobIDs); JMSConnectionFactory.getInstance().cleanup(); }
From source file:net.sf.jsignpdf.verify.Verifier.java
/** * @param args//from www .j a va2 s. co m */ public static void main(String[] args) { // create the Options Option optHelp = new Option("h", "help", false, "print this message"); // Option optVersion = new Option("v", "version", false, // "print version info"); Option optCerts = new Option("c", "cert", true, "use external semicolon separated X.509 certificate files"); optCerts.setArgName("certificates"); Option optPasswd = new Option("p", "password", true, "set password for opening PDF"); optPasswd.setArgName("password"); Option optExtract = new Option("e", "extract", true, "extract signed PDF revisions to given folder"); optExtract.setArgName("folder"); Option optListKs = new Option("lk", "list-keystore-types", false, "list keystore types provided by java"); Option optListCert = new Option("lc", "list-certificates", false, "list certificate aliases in a KeyStore"); Option optKsType = new Option("kt", "keystore-type", true, "use keystore type with given name"); optKsType.setArgName("keystore_type"); Option optKsFile = new Option("kf", "keystore-file", true, "use given keystore file"); optKsFile.setArgName("file"); Option optKsPass = new Option("kp", "keystore-password", true, "password for keystore file (look on -kf option)"); optKsPass.setArgName("password"); Option optFailFast = new Option("ff", "fail-fast", false, "flag which sets the Verifier to exit with error code on the first validation failure"); final Options options = new Options(); options.addOption(optHelp); // options.addOption(optVersion); options.addOption(optCerts); options.addOption(optPasswd); options.addOption(optExtract); options.addOption(optListKs); options.addOption(optListCert); options.addOption(optKsType); options.addOption(optKsFile); options.addOption(optKsPass); options.addOption(optFailFast); CommandLine line = null; try { // create the command line parser CommandLineParser parser = new PosixParser(); // parse the command line arguments line = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Illegal command used: " + exp.getMessage()); System.exit(SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM); } final boolean failFast = line.hasOption("ff"); final String[] tmpArgs = line.getArgs(); if (line.hasOption("h") || args == null || args.length == 0) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(70, "java -jar Verifier.jar [file1.pdf [file2.pdf ...]]", "JSignPdf Verifier is a command line tool for verifying signed PDF documents.", options, null, true); } else if (line.hasOption("lk")) { // list keystores for (String tmpKsType : KeyStoreUtils.getKeyStores()) { System.out.println(tmpKsType); } } else if (line.hasOption("lc")) { // list certificate aliases in the keystore for (String tmpCert : KeyStoreUtils.getCertAliases(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp"))) { System.out.println(tmpCert); } } else { final VerifierLogic tmpLogic = new VerifierLogic(line.getOptionValue("kt"), line.getOptionValue("kf"), line.getOptionValue("kp")); tmpLogic.setFailFast(failFast); if (line.hasOption("c")) { String tmpCertFiles = line.getOptionValue("c"); for (String tmpCFile : tmpCertFiles.split(";")) { tmpLogic.addX509CertFile(tmpCFile); } } byte[] tmpPasswd = null; if (line.hasOption("p")) { tmpPasswd = line.getOptionValue("p").getBytes(); } String tmpExtractDir = null; if (line.hasOption("e")) { tmpExtractDir = new File(line.getOptionValue("e")).getPath(); } int exitCode = 0; for (String tmpFilePath : tmpArgs) { int exitCodeForFile = 0; System.out.println("Verifying " + tmpFilePath); final File tmpFile = new File(tmpFilePath); if (!tmpFile.canRead()) { exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_FILE_NOT_READABLE; System.err.println("Couln't read the file. Check the path and permissions."); if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } final VerificationResult tmpResult = tmpLogic.verify(tmpFilePath, tmpPasswd); if (tmpResult.getException() != null) { tmpResult.getException().printStackTrace(); exitCodeForFile = SignatureVerification.SIG_STAT_CODE_ERROR_UNEXPECTED_PROBLEM; if (failFast) { System.exit(exitCodeForFile); } exitCode = Math.max(exitCode, exitCodeForFile); continue; } else { System.out.println("Total revisions: " + tmpResult.getTotalRevisions()); for (SignatureVerification tmpSigVer : tmpResult.getVerifications()) { System.out.println(tmpSigVer.toString()); if (tmpExtractDir != null) { try { File tmpExFile = new File(tmpExtractDir + "/" + tmpFile.getName() + "_" + tmpSigVer.getRevision() + ".pdf"); System.out.println("Extracting to " + tmpExFile.getCanonicalPath()); FileOutputStream tmpFOS = new FileOutputStream(tmpExFile.getCanonicalPath()); InputStream tmpIS = tmpLogic.extractRevision(tmpFilePath, tmpPasswd, tmpSigVer.getName()); IOUtils.copy(tmpIS, tmpFOS); tmpIS.close(); tmpFOS.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } exitCodeForFile = tmpResult.getVerificationResultCode(); if (failFast && SignatureVerification.isError(exitCodeForFile)) { System.exit(exitCodeForFile); } } exitCode = Math.max(exitCode, exitCodeForFile); } if (exitCode != 0 && tmpArgs.length > 1) { System.exit(SignatureVerification.isError(exitCode) ? SignatureVerification.SIG_STAT_CODE_ERROR_ANY_ERROR : SignatureVerification.SIG_STAT_CODE_WARNING_ANY_WARNING); } else { System.exit(exitCode); } } }