List of usage examples for org.apache.commons.cli Options Options
Options
From source file:iac.cnr.it.TestSearcher.java
public static void main(String[] args) throws IOException, ParseException { /** Command line parser and options */ CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption(OPT_INDEX, true, "Index path"); options.addOption(OPT_QUERY, true, "The query"); CommandLine cmd = null;// w ww. ja v a2s . com try { cmd = parser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { logger.fatal("Error while parsing command line arguments"); System.exit(1); } /** Check for mandatory options */ if (!cmd.hasOption(OPT_INDEX) || !cmd.hasOption(OPT_QUERY)) { usage(); System.exit(0); } /** Read options */ File casePath = new File(cmd.getOptionValue(OPT_INDEX)); String query = cmd.getOptionValue(OPT_QUERY); /** Check correctness of the path containing an ISODAC case */ if (!casePath.exists() || !casePath.isDirectory()) { logger.fatal("The case directory \"" + casePath.getAbsolutePath() + "\" is not valid"); System.exit(1); } /** Check existance of the info.dat file */ File infoFile = new File(casePath, INFO_FILENAME); if (!infoFile.exists()) { logger.fatal("Can't find " + INFO_FILENAME + " within the case directory (" + casePath + ")"); System.exit(1); } /** Load the mapping image_uuid --> image_filename */ imagesMap = new HashMap<Integer, String>(); BufferedReader reader = new BufferedReader(new FileReader(infoFile)); while (reader.ready()) { String line = reader.readLine(); logger.info("Read the line: " + line); String currentID = line.split("\t")[0]; String currentImgFile = line.split("\t")[1]; imagesMap.put(Integer.parseInt(currentID), currentImgFile); logger.info("ID: " + currentID + " - IMG: " + currentImgFile + " added to the map"); } reader.close(); /** Load all the directories containing an index */ ArrayList<String> indexesDirs = new ArrayList<String>(); for (File f : casePath.listFiles()) { logger.info("Analyzing: " + f); if (f.isDirectory()) indexesDirs.add(f.getAbsolutePath()); } logger.info(indexesDirs.size() + " directories found!"); /** Set-up the searcher */ Searcher searcher = null; try { String[] array = indexesDirs.toArray(new String[indexesDirs.size()]); searcher = new Searcher(array); TopDocs results = searcher.search(query, Integer.MAX_VALUE); ScoreDoc[] hits = results.scoreDocs; int numTotalHits = results.totalHits; System.out.println(numTotalHits + " total matching documents"); for (int i = 0; i < numTotalHits; i++) { Document doc = searcher.doc(hits[i].doc); String path = doc.get(FIELD_PATH); String filename = doc.get(FIELD_FILENAME); String image_uuid = doc.get(FIELD_IMAGE_ID); if (path != null) { //System.out.println((i + 1) + ". " + path + File.separator + filename + " - score: " + hits[i].score); // System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + image_uuid); System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + imagesMap.get(Integer.parseInt(image_uuid))); } else { System.out.println((i + 1) + ". " + "No path for this document"); } } } catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } finally { if (searcher != null) searcher.close(); } }
From source file:com.ibm.zurich.Main.java
public static void main(String[] args) throws NoSuchAlgorithmException, IOException { Option help = new Option(HELP, "print this message"); Option version = new Option(VERSION, "print the version information"); Options options = new Options(); Option useCurve = Option.builder(USECURVE).hasArg().argName("curve") .desc("Specify the BN Curve. Options: " + curveOptions()).build(); Option isskeygen = Option.builder(IKEYGEN).numberOfArgs(3).argName("ipk><isk><RL") .desc("Generate Issuer key pair and empty revocation list and store it in files").build(); Option join1 = Option.builder(JOIN1).numberOfArgs(3).argName("ipk><authsk><msg1") .desc("Create an authenticator secret key and perform the first step of the join protocol").build(); Option join2 = Option.builder(JOIN2).numberOfArgs(4).argName("ipk><isk><msg1><msg2") .desc("Complete the join protocol").build(); Option verify = Option.builder(VERIFY).numberOfArgs(5).argName("ipk><sig><krd><appId><RL") .desc("Verify a signature").build(); Option sign = Option.builder(SIGN).numberOfArgs(6).argName("ipk><authsk><msg2><appId><krd><sig") .desc("create a signature").build(); options.addOption(help);/*w w w . j a v a 2 s . c o m*/ options.addOption(version); options.addOption(useCurve); options.addOption(isskeygen); options.addOption(sign); options.addOption(verify); options.addOption(join1); options.addOption(join2); HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new DefaultParser(); //FIXME Choose a proper instantiation of SecureRandom depending on the platform SecureRandom random = new SecureRandom(); Base64.Encoder encoder = Base64.getUrlEncoder(); Base64.Decoder decoder = Base64.getUrlDecoder(); try { CommandLine line = parser.parse(options, args); BNCurveInstantiation instantiation = null; BNCurve curve = null; if (line.hasOption(HELP) || line.getOptions().length == 0) { formatter.printHelp(USAGE, options); } else if (line.hasOption(VERSION)) { System.out.println("Version " + Main.class.getPackage().getImplementationVersion()); } else if (line.hasOption(USECURVE)) { instantiation = BNCurveInstantiation.valueOf(line.getOptionValue(USECURVE)); curve = new BNCurve(instantiation); } else { System.out.println("Specify the curve to use."); return; } if (line.hasOption(IKEYGEN)) { String[] optionValues = line.getOptionValues(IKEYGEN); // Create secret key IssuerSecretKey sk = Issuer.createIssuerKey(curve, random); // Store pk writeToFile((new IssuerPublicKey(curve, sk, random)).toJSON(curve), optionValues[0]); // Store sk writeToFile(sk.toJson(curve), optionValues[1]); // Create empty revocation list and store HashSet<BigInteger> rl = new HashSet<BigInteger>(); writeToFile(Verifier.revocationListToJson(rl, curve), optionValues[2]); } else if (line.hasOption(SIGN)) { //("ipk><authsk><msg2><appId><krd><sig") String[] optionValues = line.getOptionValues(SIGN); IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); BigInteger authsk = curve.bigIntegerFromB(decoder.decode(readFromFile(optionValues[1]))); JoinMessage2 msg2 = new JoinMessage2(curve, readStringFromFile(optionValues[2])); // setup a new authenticator Authenticator auth = new Authenticator(curve, ipk, authsk); auth.EcDaaJoin1(curve.getRandomModOrder(random)); if (auth.EcDaaJoin2(msg2)) { EcDaaSignature sig = auth.EcDaaSign(optionValues[3]); // Write krd to file writeToFile(sig.krd, optionValues[4]); // Write signature to file writeToFile(sig.encode(curve), optionValues[5]); System.out.println("Signature written to " + optionValues[5]); } else { System.out.println("JoinMsg2 invalid"); } } else if (line.hasOption(VERIFY)) { Verifier ver = new Verifier(curve); String[] optionValues = line.getOptionValues(VERIFY); String pkFile = optionValues[0]; String sigFile = optionValues[1]; String krdFile = optionValues[2]; String appId = optionValues[3]; String rlPath = optionValues[4]; byte[] krd = Files.readAllBytes(Paths.get(krdFile)); IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(pkFile)); EcDaaSignature sig = new EcDaaSignature(Files.readAllBytes(Paths.get(sigFile)), krd, curve); boolean valid = ver.verify(sig, appId, pk, Verifier.revocationListFromJson(readStringFromFile(rlPath), curve)); System.out.println("Signature is " + (valid ? "valid." : "invalid.")); } else if (line.hasOption(JOIN1)) { String[] optionValues = line.getOptionValues(JOIN1); IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); // Create authenticator key BigInteger sk = curve.getRandomModOrder(random); writeToFile(encoder.encodeToString(curve.bigIntegerToB(sk)), optionValues[1]); Authenticator auth = new Authenticator(curve, ipk, sk); JoinMessage1 msg1 = auth.EcDaaJoin1(curve.getRandomModOrder(random)); writeToFile(msg1.toJson(curve), optionValues[2]); } else if (line.hasOption(JOIN2)) { String[] optionValues = line.getOptionValues(JOIN2); // create issuer with the specified key IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0])); IssuerSecretKey sk = new IssuerSecretKey(curve, readStringFromFile(optionValues[1])); Issuer iss = new Issuer(curve, sk, pk); JoinMessage1 msg1 = new JoinMessage1(curve, readStringFromFile(optionValues[2])); // Note that we do not check for nonce freshness. JoinMessage2 msg2 = iss.EcDaaIssuerJoin(msg1, false); if (msg2 == null) { System.out.println("Join message invalid."); } else { System.out.println("Join message valid, msg2 written to file."); writeToFile(msg2.toJson(curve), optionValues[3]); } } } catch (ParseException e) { System.out.println("Error parsing input."); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:de.cwclan.cwsa.serverendpoint.main.ServerEndpoint.java
/** * @param args the command line arguments *//*from w ww.j av a 2 s. co m*/ public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription( "Used to enter path of configfile. Default file is endpoint.properties. NOTE: If the file is empty or does not exsist, a default config is created.") .create("config")); options.addOption("h", "help", false, "displays this page"); CommandLineParser parser = new PosixParser(); Properties properties = new Properties(); try { /* * parse default config shipped with jar */ CommandLine cmd = parser.parse(options, args); /* * load default configuration */ InputStream in = ServerEndpoint.class.getResourceAsStream("/endpoint.properties"); if (in == null) { throw new IOException("Unable to load default config from JAR. This should not happen."); } properties.load(in); in.close(); log.debug("Loaded default config base: {}", properties.toString()); if (cmd.hasOption("help")) { printHelp(options); System.exit(0); } /* * parse cutom config if exists, otherwise create default cfg */ if (cmd.hasOption("config")) { File file = new File(cmd.getOptionValue("config", "endpoint.properties")); if (file.exists() && file.canRead() && file.isFile()) { in = new FileInputStream(file); properties.load(in); log.debug("Loaded custom config from {}: {}", file.getAbsoluteFile(), properties); } else { log.warn("Config file does not exsist. A default file will be created."); } FileWriter out = new FileWriter(file); properties.store(out, "Warning, this file is recreated on every startup to merge missing parameters."); } /* * create and start endpoint */ log.info("Config read successfull. Values are: {}", properties); ServerEndpoint endpoint = new ServerEndpoint(properties); Runtime.getRuntime().addShutdownHook(endpoint.getShutdownHook()); endpoint.start(); } catch (IOException ex) { log.error("Error while reading config.", ex); } catch (ParseException ex) { log.error("Error while parsing commandline options: {}", ex.getMessage()); printHelp(options); System.exit(1); } }
From source file:eu.freme.bpt.Main.java
public static void main(String[] args) { final List<String> services = new ArrayList<>(); for (EService eService : EService.values()) { services.add(eService.getName()); }/*from w w w .j a v a2 s . c o m*/ Pair<EService, String[]> serviceAndArgs = extractService(args, services); EService service = serviceAndArgs.getName(); // create options that will be parsed from the args /////// General BPT options /////// Option helpOption = new Option("h", "help", false, "Prints this message"); Option inputOption = Option.builder("if").longOpt("input-file").argName("input file").desc( "The input file or directory to process. In case of a directory, each file in that directory is processed. " + "If not given, standard in is used.") .hasArg().build(); Option outputOption = Option.builder("od").longOpt("output-dir").argName("output dir") .desc("The output directory. If not given, output is written to standard out.").hasArg().build(); Option propertiesOption = Option.builder("prop").longOpt("properties").argName("properties file") .desc("The properties file that contains configuration of the tool.").hasArg().build(); Options options = new Options().addOption(helpOption).addOption(inputOption).addOption(outputOption) .addOption(propertiesOption); /////// Common service options /////// Option informatOption = Option.builder("f").longOpt("informat").argName("FORMAT") .desc("The format of the input document(s). Defaults to 'turtle'").hasArg().build(); Option outformatOption = Option.builder("o").longOpt("outformat").argName("FORMAT") .desc("The desired output format of the service. Defaults to 'turtle'").hasArg().build(); options.addOption(informatOption).addOption(outformatOption); /////// Service specific options /////// if (service != null) { switch (service) { case E_TRANSLATION: ETranslation.addOptions(options); break; case E_ENTITY: EEntity.addOptions(options); break; case E_LINK: ELink.addOptions(options); break; case E_TERMINOLOGY: ETerminology.addOptions(options); break; case PIPELINING: Pipelining.addOptions(options); break; case E_PUBLISHING: // TODO ! default: logger.warn("Unknown service {}. Skipping!", service); break; } } else { ETranslation.addOptions(options); EEntity.addOptions(options); ELink.addOptions(options); ETerminology.addOptions(options); Pipelining.addOptions(options); } CommandLine commandLine = null; int exitValue; try { CommandLineParser parser = new DefaultParser(); commandLine = parser.parse(options, serviceAndArgs.getValue()); exitValue = 0; } catch (ParseException e) { System.err.println(e.getMessage()); exitValue = 1; } if ((exitValue != 0) || commandLine.hasOption("h") || service == null) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(132); formatter.printHelp("java -jar <this jar file> <e-service> ", options, true); System.exit(exitValue); } logger.debug("Commandline successfully parsed!"); try { BPT batchProcessingTool = new BPT(); if (commandLine.hasOption("prop")) { batchProcessingTool.loadProperties(commandLine.getOptionValue("prop")); } if (commandLine.hasOption("if")) { batchProcessingTool.setInput(commandLine.getOptionValue("if")); } if (commandLine.hasOption("od")) { batchProcessingTool.setOutput(commandLine.getOptionValue("od")); } if (commandLine.hasOption('f')) { batchProcessingTool.setInFormat(Format.valueOf(commandLine.getOptionValue('f').replace('-', '_'))); } if (commandLine.hasOption('o')) { batchProcessingTool.setOutFormat(Format.valueOf(commandLine.getOptionValue('o').replace('-', '_'))); } switch (service) { case E_TRANSLATION: batchProcessingTool.eTranslation(commandLine.getOptionValue("source-lang"), commandLine.getOptionValue("target-lang"), commandLine.getOptionValue("system"), commandLine.getOptionValue("domain"), commandLine.getOptionValue("key")); break; case E_ENTITY: batchProcessingTool.eEntity(commandLine.getOptionValue("language"), commandLine.getOptionValue("dataset"), commandLine.getOptionValue("mode")); break; case E_LINK: batchProcessingTool.eLink(commandLine.getOptionValue("templateid")); break; case E_TERMINOLOGY: batchProcessingTool.eTerminology(commandLine.getOptionValue("source-lang"), commandLine.getOptionValue("target-lang"), commandLine.getOptionValue("collection"), commandLine.getOptionValue("domain"), commandLine.getOptionValue("key"), commandLine.getOptionValue("mode")); break; case PIPELINING: batchProcessingTool.pipelining(commandLine.getOptionValue("templateid")); break; case E_PUBLISHING: default: logger.error("Unknown service {}. Aborting!", service); System.exit(3); } } catch (Exception e) { logger.error("Cannot handle input or output. Reason: ", e); System.exit(2); } }
From source file:com.jolbox.benchmark.BenchmarkLaunch.java
/** * @param args//from www .j av a 2 s . co m * @throws ClassNotFoundException * @throws PropertyVetoException * @throws SQLException * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException * @throws InterruptedException * @throws SecurityException * @throws IllegalArgumentException * @throws NamingException * @throws ParseException * @throws IOException */ public static void main(String[] args) throws ClassNotFoundException, SQLException, PropertyVetoException, IllegalArgumentException, SecurityException, InterruptedException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NamingException, ParseException, IOException { Options options = new Options(); options.addOption("t", "threads", true, "Max number of threads"); options.addOption("s", "stepping", true, "Stepping of threads"); options.addOption("p", "poolsize", true, "Pool size"); options.addOption("h", "help", false, "Help"); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("benchmark.jar", options); System.exit(1); } BenchmarkTests.threads = 400; BenchmarkTests.stepping = 5; BenchmarkTests.pool_size = 200; if (cmd.hasOption("t")) { BenchmarkTests.threads = Integer.parseInt(cmd.getOptionValue("t", "400")); } if (cmd.hasOption("s")) { BenchmarkTests.stepping = Integer.parseInt(cmd.getOptionValue("s", "20")); } if (cmd.hasOption("p")) { BenchmarkTests.pool_size = Integer.parseInt(cmd.getOptionValue("p", "200")); } System.out.println("Starting benchmark tests with " + BenchmarkTests.threads + " threads (stepping " + BenchmarkTests.stepping + ") using pool size of " + BenchmarkTests.pool_size + " connections"); new MockJDBCDriver(); BenchmarkTests tests = new BenchmarkTests(); plotLineGraph(tests.testMultiThreadedConstantDelay(0), 0, false); plotLineGraph(tests.testMultiThreadedConstantDelay(10), 10, false); plotLineGraph(tests.testMultiThreadedConstantDelay(25), 25, false); plotLineGraph(tests.testMultiThreadedConstantDelay(50), 50, false); plotLineGraph(tests.testMultiThreadedConstantDelay(75), 75, false); plotBarGraph("Single Thread", "bonecp-singlethread-poolsize-" + BenchmarkTests.pool_size + "-threads-" + BenchmarkTests.threads + ".png", tests.testSingleThread()); plotBarGraph( "Prepared Statement\nSingle Threaded", "bonecp-preparedstatement-single-poolsize-" + BenchmarkTests.pool_size + "-threads-" + BenchmarkTests.threads + ".png", tests.testPreparedStatementSingleThread()); plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(0), 0, true); plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(10), 10, true); plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(25), 25, true); plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(50), 50, true); plotLineGraph(tests.testMultiThreadedConstantDelayWithPreparedStatements(75), 75, true); }
From source file:de.dominicscheurer.passwords.Main.java
/** * @param args/*w w w.ja v a 2s.c om*/ * Command line arguments (see code or output of program when * started with no arguments). */ @SuppressWarnings("static-access") public static void main(String[] args) { Options options = new Options(); Option seedPwdOpt = OptionBuilder.withArgName("Seed Password").isRequired().hasArg() .withDescription("Password used as a seed").withLongOpt("seed-password").create("s"); Option serviceIdOpt = OptionBuilder.withArgName("Service Identifier").isRequired().hasArg() .withDescription("The service that the password is created for, e.g. facebook.com") .withLongOpt("service-identifier").create("i"); Option pwdLengthOpt = OptionBuilder.withArgName("Password Length").withType(Integer.class).hasArg() .withDescription("Length of the password in characters").withLongOpt("pwd-length").create("l"); Option specialChars = OptionBuilder.withArgName("With special chars (TRUE|false)").withType(Boolean.class) .hasArg().withDescription("Set to true if special chars !-_?=@/+* are desired, else false") .withLongOpt("special-chars").create("c"); Option suppressPwdOutpOpt = OptionBuilder .withDescription("Suppress password output (copy to clipboard only)").withLongOpt("hide-password") .hasArg(false).create("x"); Option helpOpt = OptionBuilder.withDescription("Prints this help message").withLongOpt("help").create("h"); options.addOption(seedPwdOpt); options.addOption(serviceIdOpt); options.addOption(pwdLengthOpt); options.addOption(specialChars); options.addOption(suppressPwdOutpOpt); options.addOption(helpOpt); CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { SafePwdGen.printHelp(options); System.exit(0); } int pwdLength = STD_PWD_LENGTH; if (cmd.hasOption("l")) { pwdLength = new Integer(cmd.getOptionValue("l")); } boolean useSpecialChars = true; if (cmd.hasOption("c")) { useSpecialChars = new Boolean(cmd.getOptionValue("c")); } if (pwdLength > MAX_PWD_LENGTH_64 && !useSpecialChars) { System.out.println(PASSWORD_SIZE_TOO_BIG + MAX_PWD_LENGTH_64); } if (pwdLength > MAX_PWD_LENGTH_71 && useSpecialChars) { System.out.println(PASSWORD_SIZE_TOO_BIG + MAX_PWD_LENGTH_71); } boolean suppressPwdOutput = cmd.hasOption('x'); String pwd = SafePwdGen.createPwd(cmd.getOptionValue("s"), cmd.getOptionValue("i"), pwdLength, useSpecialChars); if (!suppressPwdOutput) { System.out.print(GENERATED_PASSWORD); System.out.println(pwd); } System.out.println(CLIPBOARD_COPIED_MSG); SystemClipboardInterface.copy(pwd); System.in.read(); } catch (ParseException e) { System.out.println(e.getLocalizedMessage()); SafePwdGen.printHelp(options); } catch (UnsupportedEncodingException e) { System.out.println(e.getLocalizedMessage()); } catch (NoSuchAlgorithmException e) { System.out.println(e.getLocalizedMessage()); } catch (IOException e) { System.out.println(e.getLocalizedMessage()); } }
From source file:name.wagners.bpp.Bpp.java
public static void main(final String[] args) { // create the command line parser CommandLineParser parser = new PosixParser(); // create the Options Options options = new Options(); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("generations") .withDescription("Number of generations [default: 50]").create("g")); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("mutrate") .withDescription("Mutation rate [default: 1]").create()); options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("mutprop") .withDescription("Mutation propability [default: 0.5]").create()); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("populationsize") .withDescription("Size of population [default: 20]").create()); options.addOption(OptionBuilder.hasArg().withArgName("a|b").withLongOpt("recombalg") .withDescription("Recombination algorithm [default: a]").create()); // options.addOption(OptionBuilder // .hasArg()/*from w ww .j a va 2 s . c om*/ // .withArgName("int") // .withLongOpt("recombrate") // .withDescription("Recombination rate [default: 1]") // .create()); options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("recombprop") .withDescription("Recombination propability [default: 0.8]").create()); options.addOption(OptionBuilder.hasArg().withArgName("a").withLongOpt("selalg") .withDescription("Selection algorithm [default: a]").create()); options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("selectionpressure") .withDescription("Selection pressure [default: 4]").create()); options.addOption(OptionBuilder.hasArg().withArgName("bool").withLongOpt("elitism") .withDescription("Enable Elitism [default: 1]").create("e")); options.addOption(OptionBuilder.hasArg().withArgName("filename") // .isRequired() .withLongOpt("datafile").withDescription("Problem data file [default: \"binpack.txt\"]") .create("f")); options.addOptionGroup(new OptionGroup() .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v")) .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q"))); options.addOption(OptionBuilder.withLongOpt("version") .withDescription("print the version information and exit").create("V")); options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h")); try { // parse the command line arguments CommandLine line = parser.parse(options, args); // validate that block-size has been set if (line.hasOption("help")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Bpp", options); System.exit(0); } if (line.hasOption("version")) { log.info("Bpp 0.1 (c) 2007 by Daniel Wagner"); } if (line.hasOption("datafile")) { fname = line.getOptionValue("datafile"); } if (line.hasOption("elitism")) { elitism = Boolean.parseBoolean(line.getOptionValue("elitism")); } if (line.hasOption("generations")) { gen = Integer.parseInt(line.getOptionValue("generations")); } if (line.hasOption("mutprop")) { mp = Double.parseDouble(line.getOptionValue("mutprop")); } if (line.hasOption("mutrate")) { mr = Integer.parseInt(line.getOptionValue("mutrate")); } if (line.hasOption("populationsize")) { ps = Integer.parseInt(line.getOptionValue("populationsize")); } if (line.hasOption("recombalg")) { sel = line.getOptionValue("recombalg").charAt(0); } if (line.hasOption("recombprop")) { rp = Double.parseDouble(line.getOptionValue("recombprop")); } if (line.hasOption("selalg")) { selalg = line.getOptionValue("selalg").charAt(0); } if (line.hasOption("selectionpressure")) { sp = Integer.parseInt(line.getOptionValue("selectionpressure")); } } catch (ParseException exp) { log.info("Unexpected exception:" + exp.getMessage(), exp); // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Bpp", options); System.exit(1); } // Ausgabe der eingestellten Optionen log.info("Configuration"); log.info(" Datafile: " + fname); log.info(" Generations: " + gen); log.info(" Population size: " + ps); log.info(" Elitism: " + elitism); log.info(" Mutation propapility: " + mp); log.info(" Mutation rate: " + mr); log.info(" Recombination algorithm " + (char) sel); log.info(" Recombination propapility: " + rp); log.info(" Selection pressure: " + sp); // Daten laden instance = new Instance(); instance.load(fname); Evolutionizer e = new Evolutionizer(instance); e.run(); }
From source file:com.chezzverse.timelogger.server.TimeLoggerServerMain.java
public static void main(String[] args) { // Initialize the default configuration file to the hard coded default path value. String configFileName = _DEFAULT_CONFIG_FILE; // Create all the available options Option portOpt = new Option("p", "port", true, "Set the listen port for the http server " + "instance."); portOpt.setArgName("number"); Option htmlOpt = new Option("h", "html-root", true, "Set the root directory that " + "contains the required html files."); htmlOpt.setArgName("directory"); Option configOpt = new Option("c", "config", true, "Get configuration options from the " + "specified file"); Option backlogOpt = new Option("b", "backlog", true, "Set the number of connections to " + "queue for the server."); Options opts = new Options(); opts.addOption(portOpt);/* w w w.ja va 2s .c o m*/ opts.addOption(htmlOpt); opts.addOption(configOpt); opts.addOption(backlogOpt); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; HelpFormatter formatter = new HelpFormatter(); try { // Parse the command line arguments. cmd = parser.parse(opts, args); // Fist check to see if there is a custom defined config file, and load the config file. if (cmd.hasOption("c")) { configFileName = cmd.getOptionValue("c"); } TimeLoggerConfig.getInstance().LoadConfigFile(configFileName); // Process the rest of the args and override any settings in the config file. if (cmd.hasOption("h")) { TimeLoggerConfig.getInstance().htmlRoot = cmd.getOptionValue("h"); } if (cmd.hasOption("p")) { TimeLoggerConfig.getInstance().port = Integer.parseInt(cmd.getOptionValue("p")); } if (cmd.hasOption("b")) { TimeLoggerConfig.getInstance().maxBackLog = Integer.parseInt(cmd.getOptionValue("b")); } } catch (ParseException e) { System.out.println("Invalid argument."); formatter.printHelp("TimeLoggerServer", opts); System.exit(1); } catch (NumberFormatException e) { System.out.println("Invalid argument."); formatter.printHelp("TimeLoggerServer", opts); System.exit(1); } catch (Exception e) { e.printStackTrace(); } TimeLoggerApp app = new TimeLoggerApp(); if (app != null) { app.run(); } else { System.exit(3); // Strange termination } }
From source file:com.buddycloud.channeldirectory.cli.Main.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { JsonElement rootElement = new JsonParser().parse(new FileReader(QUERIES_FILE)); JsonArray rootArray = rootElement.getAsJsonArray(); Map<String, Query> queries = new HashMap<String, Query>(); for (int i = 0; i < rootArray.size(); i++) { JsonObject queryElement = rootArray.get(i).getAsJsonObject(); String queryName = queryElement.get("name").getAsString(); String type = queryElement.get("type").getAsString(); Query query = null;//ww w . ja va 2 s .c o m if (type.equals("solr")) { query = new QueryToSolr(queryElement.get("agg").getAsString(), queryElement.get("core").getAsString(), queryElement.get("q").getAsString()); } else if (type.equals("dbms")) { query = new QueryToDBMS(queryElement.get("q").getAsString()); } queries.put(queryName, query); } LinkedList<String> queriesNames = new LinkedList<String>(queries.keySet()); Collections.sort(queriesNames); Options options = new Options(); options.addOption(OptionBuilder.isRequired(true).withLongOpt("query").hasArg(true) .withDescription("The name of the query. Possible queries are: " + queriesNames).create('q')); options.addOption(OptionBuilder.isRequired(false).withLongOpt("args").hasArg(true) .withDescription("Arguments for the query").create('a')); options.addOption(new Option("?", "help", false, "Print this message")); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { printHelpAndExit(options); } if (cmd.hasOption("help")) { printHelpAndExit(options); } String queryName = cmd.getOptionValue("q"); String argsCmd = cmd.getOptionValue("a"); Properties configuration = ConfigurationUtils.loadConfiguration(); Query query = queries.get(queryName); if (query == null) { printHelpAndExit(options); } System.out.println(query.exec(argsCmd, configuration)); }
From source file:Inmemantlr.java
public static void main(String[] args) { LOGGER.info("Inmemantlr tool"); HelpFormatter hformatter = new HelpFormatter(); Options options = new Options(); // Binary arguments options.addOption("h", "print this message"); Option grmr = Option.builder().longOpt("grmrfiles").hasArgs().desc("comma-separated list of ANTLR files") .required(true).argName("grmrfiles").type(String.class).valueSeparator(',').build(); Option infiles = Option.builder().longOpt("infiles").hasArgs() .desc("comma-separated list of files to parse").required(true).argName("infiles").type(String.class) .valueSeparator(',').build(); Option utilfiles = Option.builder().longOpt("utilfiles").hasArgs() .desc("comma-separated list of utility files to be added for " + "compilation").required(false) .argName("utilfiles").type(String.class).valueSeparator(',').build(); Option odir = Option.builder().longOpt("outdir") .desc("output directory in which the dot files will be " + "created").required(false).hasArg(true) .argName("outdir").type(String.class).build(); options.addOption(infiles);//w ww . ja v a 2 s . c o m options.addOption(grmr); options.addOption(utilfiles); options.addOption(odir); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.hasOption('h')) { hformatter.printHelp("java -jar inmemantlr.jar", options); System.exit(0); } } catch (ParseException e) { hformatter.printHelp("java -jar inmemantlr.jar", options); LOGGER.error(e.getMessage()); System.exit(-1); } // input files Set<File> ins = getFilesForOption(cmd, "infiles"); // grammar files Set<File> gs = getFilesForOption(cmd, "grmrfiles"); // utility files Set<File> uf = getFilesForOption(cmd, "utilfiles"); // output dir Set<File> od = getFilesForOption(cmd, "outdir"); if (od.size() > 1) { LOGGER.error("output directories must be less than or equal to 1"); System.exit(-1); } if (ins.size() <= 0) { LOGGER.error("no input files were specified"); System.exit(-1); } if (gs.size() <= 0) { LOGGER.error("no grammar files were specified"); System.exit(-1); } LOGGER.info("create generic parser"); GenericParser gp = null; try { gp = new GenericParser(gs.toArray(new File[gs.size()])); } catch (FileNotFoundException e) { LOGGER.error(e.getMessage()); System.exit(-1); } if (!uf.isEmpty()) { try { gp.addUtilityJavaFiles(uf.toArray(new String[uf.size()])); } catch (FileNotFoundException e) { LOGGER.error(e.getMessage()); System.exit(-1); } } LOGGER.info("create and add parse tree listener"); DefaultTreeListener dt = new DefaultTreeListener(); gp.setListener(dt); LOGGER.info("compile generic parser"); try { gp.compile(); } catch (CompilationException e) { LOGGER.error("cannot compile generic parser: {}", e.getMessage()); System.exit(-1); } String fpfx = ""; for (File of : od) { if (!of.exists() || !of.isDirectory()) { LOGGER.error("output directory does not exist or is not a " + "directory"); System.exit(-1); } fpfx = of.getAbsolutePath(); } Ast ast; for (File f : ins) { try { gp.parse(f); } catch (IllegalWorkflowException | FileNotFoundException e) { LOGGER.error(e.getMessage()); System.exit(-1); } ast = dt.getAst(); if (!fpfx.isEmpty()) { String of = fpfx + "/" + FilenameUtils.removeExtension(f.getName()) + ".dot"; LOGGER.info("write file {}", of); try { FileUtils.writeStringToFile(new File(of), ast.toDot(), "UTF-8"); } catch (IOException e) { LOGGER.error(e.getMessage()); System.exit(-1); } } else { LOGGER.info("Tree for {} \n {}", f.getName(), ast.toDot()); } } System.exit(0); }